File size: 2,138 Bytes
e8ae275
6925a37
 
 
 
86c5c73
beebeb7
6925a37
 
 
 
 
 
 
90ce3e5
6925a37
 
 
 
 
 
 
 
 
 
 
 
e8ae275
67e6563
c5a7712
 
6375661
c5a7712
6925a37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

import openai
import streamlit as st
import os
import time
st.set_page_config(page_title="Books GPT")
st.header("Welcome To Custom Books GPT!")
st.markdown("Currently the ChatBot is taking content only from this [file.](http://kpcode.kp.gov.pk/uploads/1964_35_THE_WEST_PAKISTAN_FAMILY_COURTS_ACT_1964.pdf)")

class OpenAIClient:
    def __init__(self):
        self.client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
        self.thread_id = None
        self.file_id = ["file-Anvyhz2k0puV0NCjWH8mGsuk"]
        self.assistant_id = "asst_jQN8lzPx9NMK79et6kuJ27II"

    def create_thread_id(self):
        if "thread_id" not in st.session_state:
            _id = self.client.beta.threads.create().id
            st.session_state["thread_id"] = _id
        
    def main(self, user_message):
        message = self.client.beta.threads.messages.create(
            st.session_state.get("thread_id"),
            role="user",
            content=user_message,
        )
        run = self.client.beta.threads.runs.create(thread_id=st.session_state.get("thread_id"), assistant_id=self.assistant_id).id
        while run == "queued" or run == "in_progress":
                run = self.client.beta.threads.runs.retrieve(thread_id=st.session_state.get("thread_id"),run_id=run).status
                if run == "completed":
                    return self.get_response()
                time.sleep(0.5)


    def get_response(self):
        messages = self.client.beta.threads.messages.list(
            thread_id=st.session_state.get("thread_id")
        )
        return messages.data[0].content[0].text.value

try:
    client = OpenAIClient()
    client.create_thread_id()
    user_input = st.text_input("Input: ", key='input')
    submit = st.button("Ask the Question")
    if submit:
        st.subheader("The Response is")
        st.write(client.main(user_input))
except openai.AuthenticationError:
    st.write("Your API key or token was invalid, expired, or revoked.")
except openai.RateLimitError:
    st.write("You have hit your assigned rate limit. Please try again in a few minutes.")
except Exception as e:
    st.write(e)