-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcmugpt_assistant.py
162 lines (132 loc) · 6.42 KB
/
cmugpt_assistant.py
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
from openai import OpenAI, APITimeoutError, APIError
import json
from dotenv import load_dotenv
import os
import time
from perplexity_integration import CMUPerplexitySearch # Changed from relative import
import requests
#from courses import get_courses, get_course_by_id, get_fces, get_fces_by_id, get_schedules
load_dotenv()
class CMUGPTAssistant:
def __init__(self):
# Set up OpenAI client with timeout configuration
self.client = OpenAI(
api_key=os.getenv('OPENAI_API_KEY'),
timeout=60.0, # 60 second timeout
max_retries=3 # Allow 3 retries
)
# Define the function definitions (tools) for the model
self.tools = self.get_tools()
# Initialize conversation messages
self.messages = [
{
"role": "system",
"content": "You are CMUGPT, an assistant knowledgeable about Carnegie Mellon University in Pittsburgh, Pennsylvania. Use the supplied tools to assist the user."
},
#{
# "role": "system",
# "content": "Write concise, relevant responses, with the skilled style of a Pultizer Prize-winning author. Do not use course search function, all others allowed."
#}
]
# Keep track of functions called
self.functions_called = []
self.perplexity_search = CMUPerplexitySearch()
def get_tools(self):
tools = [
{
"type": "function",
"function": {
"name": "general_purpose_knowledge_search",
"description": "Search for general knowledge about Carnegie Mellon University.",
"parameters": {
"type": "object",
"properties": {
"search_query": {
"type": "string",
"description": "The query to search for general knowledge."
}
},
"required": ["search_query"],
"additionalProperties": False
},
"strict": True # Enabling Structured Outputs
}
},
]
return tools
def process_user_input(self, user_input):
self.messages.append({"role": "user", "content": user_input})
max_retries = 3
retry_delay = 1
for attempt in range(max_retries):
try:
response = self.client.chat.completions.create(
model='gpt-4o-mini', # Fixed model name
messages=self.messages,
tools=self.tools,
)
assistant_message = response.choices[0].message
if assistant_message.tool_calls:
# The model wants to call functions
tool_calls = assistant_message.tool_calls
function_results = []
for tool_call in tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
result = self.execute_function(function_name, arguments)
# Keep track of functions called
self.functions_called.append({
'function_name': function_name,
'arguments': arguments,
'result': result
})
# Prepare the function result message
function_result_message = {
"role": "tool",
"content": json.dumps(result),
"tool_call_id": tool_call.id
}
# Add the assistant's message (function call) and the function result to the conversation
self.messages.append({
"role": "assistant",
"tool_calls": [tool_call]
})
self.messages.append(function_result_message)
# After providing the function results, call the model again to get the final response
response = self.client.chat.completions.create(
model='gpt-4o-mini',
messages=self.messages,
#tools=self.tools,
)
assistant_message = response.choices[0].message
self.messages.append(assistant_message)
return assistant_message.content
else:
self.messages.append(assistant_message)
return assistant_message.content
except APITimeoutError as e:
if attempt == max_retries - 1:
return f"I apologize, but I'm having trouble connecting. Please try again in a moment. (Error: Connection timeout)"
time.sleep(retry_delay)
retry_delay *= 2
except APIError as e:
if attempt == max_retries - 1:
return f"I apologize, but there was an error processing your request. Please try again. (Error: {str(e)})"
time.sleep(retry_delay)
retry_delay *= 2
except Exception as e:
return f"I apologize, but an unexpected error occurred. Please try again. (Error: {str(e)})"
return "I apologize, but I was unable to process your request after multiple attempts. Please try again later."
# Function to execute the functions
def execute_function(self, function_name, arguments):
if function_name == 'general_purpose_knowledge_search':
return self.general_purpose_knowledge_search(arguments.get('search_query'))
#Add elif statements here
else:
return {"error": "Function not found."}
# Define the functions (simulate the functionality)
def general_purpose_knowledge_search(self, search_query):
# Use Perplexity API for general knowledge searches
return self.perplexity_search.search(search_query)
def get_functions_called(self):
return self.functions_called