nakamura196 commited on
Commit
86de97d
Β·
1 Parent(s): dec0fcd

feat: initial commit

Browse files
Files changed (4) hide show
  1. .env.example +3 -0
  2. .gitignore +4 -0
  3. app.py +142 -59
  4. requirements.txt +3 -1
.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ AZURE_OPENAI_ENDPOINT=
2
+ AZURE_OPENAI_API_KEY=
3
+ AZURE_OPENAI_VECTOR_STORE_ID=
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .env*
2
+ !.env.example
3
+ .venv
4
+ __pycache__
app.py CHANGED
@@ -1,64 +1,147 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
  import gradio as gr
2
+ from openai import AzureOpenAI
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ def load_environment():
8
+ """Load environment variables."""
9
+ load_dotenv(override=True)
10
+
11
+ def initialize_openai_client():
12
+ """Initialize the Azure OpenAI client."""
13
+ return AzureOpenAI(
14
+ azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
15
+ api_key=os.getenv("AZURE_OPENAI_API_KEY"),
16
+ api_version="2024-10-01-preview"
17
+ )
18
+
19
+ def create_assistant(client, vector_store_id):
20
+ """Create an assistant with specified configuration."""
21
+ return client.beta.assistants.create(
22
+ model="gpt-4o",
23
+ instructions="ζŒ‡η€ΊγŒγͺγ„ι™γ‚Šγ€ζ—₯本θͺžγ§ε›žη­”してください。",
24
+ tools=[{
25
+ "type": "file_search",
26
+ "file_search": {"ranking_options": {"ranker": "default_2024_08_21", "score_threshold": 0}}
27
+ }],
28
+ tool_resources={"file_search": {"vector_store_ids": [vector_store_id]}},
29
+ temperature=0
30
+ )
31
+
32
+ def create_thread(client):
33
+ """Create a new thread."""
34
+ return client.beta.threads.create()
35
+
36
+ def clear_thread(_):
37
+ """Clear the chat history and reset the thread."""
38
+ global thread
39
+ thread = create_thread(client)
40
+ return [], ""
41
+
42
+ def get_annotations(msg):
43
+ annotations = msg.content[0].text.annotations
44
+ file_ids = []
45
+ if annotations:
46
+ for annotation in annotations:
47
+ file_id = annotation.file_citation.file_id
48
+ if file_id in file_ids:
49
+ continue
50
+
51
+ print("file_id", file_id)
52
+
53
+ cited_file = client.files.retrieve(file_id)
54
+
55
+ print("filename", cited_file.filename)
56
+
57
+ try:
58
+ content = client.files.content(file_id)
59
+ except Exception as e:
60
+ print(e)
61
+ pass
62
+
63
+ file_ids.append(file_id)
64
+
65
+ return file_ids
66
+
67
+ def get_chatbot_response(client, thread_id, assistant_id, message):
68
+ """Get chatbot response for a given message."""
69
+ client.beta.threads.messages.create(
70
+ thread_id=thread_id,
71
+ role="user",
72
+ content=message # Ensure the content is an object with a `text` key
73
+ )
74
+
75
+ run = client.beta.threads.runs.create(
76
+ thread_id=thread_id,
77
+ assistant_id=assistant_id
78
+ )
79
+
80
+ while run.status in ["queued", "in_progress", "cancelling"]:
81
+ time.sleep(1)
82
+ run = client.beta.threads.runs.retrieve(
83
+ thread_id=thread_id,
84
+ run_id=run.id
85
+ )
86
+
87
+ if run.status == "completed":
88
+ messages = client.beta.threads.messages.list(thread_id=thread_id)
89
+
90
+ for msg in messages:
91
+ # file_ids = get_annotations(msg)
92
+
93
+ main_text = msg.content[0].text.value
94
+ # main_text += "\n> aaa"
95
+ return main_text
96
+
97
+ elif run.status == "requires_action":
98
+ # Handle cases where the assistant requires further action
99
+ pass
100
+
101
+ return "Unable to retrieve a response." # Fallback response
102
+
103
+ def chatbot_response(history, message):
104
+
105
+ """Wrapper function to generate chatbot response."""
106
+ global thread
107
+ # Get response from the API
108
+ assistant_response = get_chatbot_response(client, thread.id, assistant.id, message)
109
+
110
+ # Update chat history
111
+ history.append({"role": "user", "content": message})
112
+ history.append({"role": "assistant", "content": assistant_response})
113
+
114
+ return history, ""
115
+
116
+ # Load environment variables
117
+ load_environment()
118
+
119
+ # Initialize OpenAI client
120
+ client = initialize_openai_client()
121
+
122
+ # Define vector store ID
123
+ vector_store_id = os.getenv("AZURE_OPENAI_VECTOR_STORE_ID")
124
+
125
+ # Create assistant and thread
126
+ assistant = create_assistant(client, vector_store_id)
127
+ thread = create_thread(client)
128
+
129
+ with gr.Blocks() as demo:
130
+ chatbot = gr.Chatbot(type="messages")
131
+ msg = gr.Textbox()
132
+ clear = gr.ClearButton([msg, chatbot])
133
+
134
+ def respond(message, chat_history):
135
+
136
+ bot_message = get_chatbot_response(client, thread.id, assistant.id, message)
137
+
138
+ chat_history.append({"role": "user", "content": message})
139
+ chat_history.append({"role": "assistant", "content": bot_message})
140
+ return "", chat_history
141
+
142
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
143
+
144
+ clear.click(clear_thread, [chatbot])
145
 
146
  if __name__ == "__main__":
147
  demo.launch()
requirements.txt CHANGED
@@ -1 +1,3 @@
1
- huggingface_hub==0.25.2
 
 
 
1
+ gradio
2
+ openai
3
+ python-dotenv