Skip to content

Instantly share code, notes, and snippets.

@johnidm
Created November 2, 2024 16:46
Show Gist options
  • Save johnidm/03cda9edf169a2114b9779e05ce3d491 to your computer and use it in GitHub Desktop.
Save johnidm/03cda9edf169a2114b9779e05ce3d491 to your computer and use it in GitHub Desktop.
Explore OpenAI Assistant in Python - While True to Run a Conversation

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}"
                )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment