-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
104 lines (83 loc) · 2.89 KB
/
Copy pathmain.py
File metadata and controls
104 lines (83 loc) · 2.89 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
import os
import dotenv
from openai import OpenAI, BadRequestError
dotenv.load_dotenv()
client = OpenAI(
api_key=os.getenv("OPENAI_KEY"),
base_url=os.getenv("OPENAI_BASE_URL")
)
MODEL = "gpt-4o-mini"
completion_tools = [
{
"type": "function",
"function": {
"name": "exit_conversation",
"description": "Signal for the application to exit the conversation",
"parameters": {
"type": "object",
"properties": {
"call_id": {
"type": "string",
"description": "The Call Id of the termination function"
}
},
"required": ["call_id"],
"additionalProperties": False
},
"strict": True
}
}
]
def exit_conversation(call_id):
print(call_id)
def calculate_cost(input_tokens, output_tokens):
if MODEL != "gpt-4o-mini":
raise ValueError(f"Pricing data is currently unavailable for model: {MODEL}")
input_token_cost = 0.15
output_token_cost = 0.60
input_cost = (input_tokens / 1_000_000) * input_token_cost
output_cost = (output_tokens / 1_000_000) * output_token_cost
return input_cost + output_cost
def main():
should_continue = True
messages = [
{
"role": "system",
"content": "You are a helpful assistant for a simple CLI chat. Only respond with text messages. "
"Get creative with the answers!"
},
]
while should_continue:
query = input("Enter a message: ")
messages.append({"role": "user", "content": query})
try:
completion = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=completion_tools
)
except BadRequestError as e:
print(f"Request failed: {e.message}")
continue
message = completion.choices[0].message
messages.append(message)
usage = completion.usage
for tool_call in (message.tool_calls or []):
if tool_call.type == "function":
try:
if tool_call.function.name == "exit_conversation":
exit_conversation(tool_call.id)
should_continue = False
else:
print(f"Unknown tool: {tool_call.function.name}")
except Exception as e:
print(f"An error occurred: {str(e)}")
print(f"You: {query}")
print(f"Assistant: {message.content}")
try:
total_cost = calculate_cost(usage.prompt_tokens, usage.completion_tokens)
print(f"Cost: ${total_cost:.6f}\n")
except ValueError as e:
print(f"Unable to calculate cost: {e}\n")
if __name__ == "__main__":
main()