-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctioncallchatbot.py
More file actions
219 lines (186 loc) · 7.78 KB
/
functioncallchatbot.py
File metadata and controls
219 lines (186 loc) · 7.78 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import json
import streamlit as st
from openai import OpenAI
from tenacity import retry, wait_random_exponential, stop_after_attempt
from termcolor import colored
import time
import config
openai_api_key = config.OPENAI_API_KEY
llm_model = config.LLM_MODEL
GPT_MODEL = llm_model
client = OpenAI(api_key=openai_api_key)
# st.title("Function Call Chatbot")
# # Initialize chat history
# if "messages" not in st.session_state:
# st.session_state.messages = []
# st.session_state.messages.append(
# {"role": "assistant", "content": "Hi, how can I assist you today?"})
# # Display chat messages from history on app rerun
# for message in st.session_state.messages:
# with st.chat_message(message["role"]):
# st.markdown(message["content"])
# if prompt := st.chat_input("Message QA Chatbot..."):
# # Add user message to chat history
# st.session_state.messages.append({"role": "user", "content": prompt})
# # Display user message in chat message container
# with st.chat_message("user"):
# st.markdown(prompt)
# # Display assistant response in chat message container
# with st.chat_message("assistant"):
# message_placeholder = st.empty()
# full_response = ""
# query = [msg["content"]
# for msg in st.session_state.messages if msg["role"] == "user"][-1].lower()
# assistant_response = chat_completion_request(
# st.session_state.messages, tools=tools
# )
# # Simulate stream of response with milliseconds delay
# if "\n" in assistant_response:
# for chunk in assistant_response.split("\n"):
# for item in chunk.split():
# full_response += item + " "
# time.sleep(0.05)
# # Add a blinking cursor to simulate typing
# message_placeholder.markdown(full_response + "▌")
# full_response += "\n"
# else:
# for item in assistant_response.split():
# full_response += item + " "
# time.sleep(0.05)
# # Add a blinking cursor to simulate typing
# message_placeholder.markdown(full_response + "▌")
# message_placeholder.markdown(assistant_response)
# # Add assistant response to chat history
# st.session_state.messages.append(
# {"role": "assistant", "content": full_response})
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The temperature unit to use. Infer this from the users location.",
},
},
"required": ["location", "format"],
},
}
},
{
"type": "function",
"function": {
"name": "get_n_day_weather_forecast",
"description": "Get an N-day weather forecast",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The temperature unit to use. Infer this from the users location.",
},
"num_days": {
"type": "integer",
"description": "The number of days to forecast",
}
},
"required": ["location", "format", "num_days"]
},
}
},
]
@retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
def chat_completion_request(messages, tools=None, tool_choice=None, model=GPT_MODEL):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
tool_choice=tool_choice
)
return response
except Exception as e:
print("Unable to generate ChatCompletion response")
print(f"Exception: {e}")
return e
def pretty_print_conversation(messages):
role_to_color = {
"system": "red",
"user": "green",
"assistant": "blue",
"function": "magenta",
}
for messages in messages:
if message["role"] == "system":
print(colored(f"system: {message['content']}\n", role_to_color[message["role"]]))
elif message["role"] =="user":
print(colored(f"user: {message['content']}\n", role_to_color[message["role"]]))
elif message["role"] =="assistant" and message.get("function_call"):
print(colored(f"assistant: {message['function_call']}\n", role_to_color[message["role"]]))
elif message["role"] =="assistant" and not message.get("function_call"):
print(colored(f"assistant: {message['content']}\n", role_to_color[message["role"]]))
elif message["role"] == "function":
print(colored(f"function ({message['name']}): {message['content']}\n", role_to_color[message["role"]]))
def main():
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "What's the weather like today in Glasgow, Scotland."})
chat_response = chat_completion_request(
messages, tools=tools
)
assistant_message = chat_response.choices[0].message
messages.append(assistant_message)
print(assistant_message)
main()
st.title("Function Call Chatbot")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
st.session_state.messages.append(
{"role": "assistant", "content": "Hi, how can I assist you today?"})
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("Message QA Chatbot..."):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Display assistant response in chat message container
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = ""
query = [msg["content"]
for msg in st.session_state.messages if msg["role"] == "user"][-1].lower()
chat_response = chat_completion_request(
st.session_state.messages, tools=tools
)
assistant_message = chat_response.choices[0].message
if assistant_message.tool_calls:
assistant_message.content = str(assistant_message.tool_calls[0].function)
assistant_response = assistant_message.content
for item in assistant_response.split():
full_response += item + " "
time.sleep(0.05)
# Add a blinking cursor to simulate typing
message_placeholder.markdown(full_response + "▌")
message_placeholder.markdown(assistant_response)
# Add assistant response to chat history
st.session_state.messages.append(
{"role": "assistant", "content": full_response})