-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathassistant.py
More file actions
78 lines (69 loc) · 2.39 KB
/
assistant.py
File metadata and controls
78 lines (69 loc) · 2.39 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
from openai import OpenAI
from config import OPENAI_API_KEY, OPENAI_MODEL
import json
from functions import get_my_location, get_current_weather
client = OpenAI(api_key=OPENAI_API_KEY)
def create_function_definitions():
"""
Define the function schemas for the assistant to use.
Returns:
list: A list of function definitions.
"""
functions = [
{
"type": "function",
"name": "get_my_location",
"description": "Get my latitude and longitude location",
"parameters": {
"type": "object",
"properties": {}
}
},
{
"type": "function",
"name": "get_current_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"}
},
"required": ["latitude", "longitude"],
"additionalProperties": False
},
},
]
return functions
# Observation
def process_user_message(messages):
while True:
# Reasoning
response = client.chat.completions.create(
model=OPENAI_MODEL,
messages=messages,
functions=create_function_definitions(),
)
response_message = response.choices[0].message
# Action
if response_message.function_call:
function_name = response_message.function_call.name
arguments = json.loads(response_message.function_call.arguments)
if function_name == "get_current_weather":
function_response = get_current_weather(
arguments["latitude"], arguments["longitude"]
)
elif function_name == "get_my_location":
function_response = get_my_location()
else:
raise ValueError(f"Unknown function name: {function_name}")
# Result
messages.append(response_message)
messages.append({
"role": "function",
"name": function_name,
"content": json.dumps(function_response),
})
else:
# Final Answer
return response_message.content