-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassistant_manager.py
More file actions
67 lines (56 loc) · 2.48 KB
/
assistant_manager.py
File metadata and controls
67 lines (56 loc) · 2.48 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
import logging
from openai import AzureOpenAI
logger = logging.getLogger(__name__)
class AssistantManager:
def __init__(self, client: AzureOpenAI):
self.client = client
self.assistants = {}
self.threads = {}
# def create_assistant(self, name: str, instructions: str, tools: list = None):
# """Create an assistant with specified configuration."""
# try:
# if tools is None:
# tools = [{"type": "code_interpreter"}]
# assistant = self.client.beta.assistants.create(
# name=name,
# instructions=instructions,
# tools=tools,
# model="o1-preview"
# )
# self.assistants[name] = assistant
# return assistant
# except Exception as e:
# logger.error(f"Error creating assistant {name}: {str(e)}")
# raise
def get_or_create_thread(self, assistant_name: str):
"""Get existing thread or create a new one for an assistant."""
if assistant_name not in self.threads:
self.threads[assistant_name] = self.client.beta.threads.create()
return self.threads[assistant_name]
def run_conversation(self, assistant_name: str, prompt: str, instructions: str = None) -> str:
"""Run a conversation with an assistant and return the response."""
try:
assistant = self.assistants.get(assistant_name)
if not assistant:
raise ValueError(f"Assistant {assistant_name} not found")
thread = self.get_or_create_thread(assistant_name)
# Add user message to thread
self.client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=prompt
)
# Run the thread
run = self.client.beta.threads.runs.create_and_poll(
thread_id=thread.id,
assistant_id=assistant.id,
instructions=instructions
)
if run.status == "completed":
messages = self.client.beta.threads.messages.list(thread_id=thread.id)
return messages.data[0].content[0].text.value
else:
raise Exception(f"Run failed with status: {run.status}")
except Exception as e:
logger.error(f"Error in conversation with {assistant_name}: {str(e)}")
raise