A variant of the ongoing conversation employs the while true
strategy, utilizing an infinite loop to sustain the dialogue.
def run_conversation(message: str, thread_id, assistant_id):
message = client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=message,
)
run = client.beta.threads.runs.create(
thread_id=thread_id,
assistant_id=assistant_id,
)
while True:
time.sleep(5)
run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
match run.status:
case "in_progress" | "queued":
continue
case "cancelled":
return "A thread conversation was unexpectedly cancelled due to an unexpected error."
case "failed":
raise Exception(
f"Thread ID [{thread_id}] - A thread conversation was failed"
)
case "requires_action":
tool_calls = run.required_action.submit_tool_outputs.tool_calls
tool_outputs = []
try:
for tool_call in tool_calls:
name = tool_call.function.name
arguments = ast.literal_eval(tool_call.function.arguments)
fn = available_functions[name]
output = fn(**arguments)
tool_outputs.append(
{
"tool_call_id": tool_call.id,
"output": output,
}
)
except Exception as e:
client.beta.threads.runs.cancel(thread_id=thread_id, run_id=run.id)
case "completed":
messages = client.beta.threads.messages.list(
thread_id=thread_id,
)
response = messages.data[0].content[0].text.value
return response
case _:
raise Exception(
f"Thread ID [{thread_id}] - Status do assistente desconhecido: {run.status}"
)