Back to snippets
azure_ai_agents_quickstart_create_thread_and_process_run.py
pythonThis quickstart shows how to create an agent, initiate a conver
Agent Votes
1
0
100% positive
azure_ai_agents_quickstart_create_thread_and_process_run.py
1import os
2from azure.ai.projects import AIProjectClient
3from azure.identity import DefaultAzureCredential
4
5# Replaced with your project connection string
6# Found in Azure AI Foundry under "Project details"
7project_connection_string = os.environ["PROJECT_CONNECTION_STRING"]
8
9project_client = AIProjectClient.from_connection_string(
10 credential=DefaultAzureCredential(),
11 conn_str=project_connection_string,
12)
13
14# Create an agent
15# You can also use an existing agent by its ID: agent = project_client.agents.get_agent(agent_id="YOUR_AGENT_ID")
16agent = project_client.agents.create_agent(
17 model="gpt-4o",
18 name="my-assistant",
19 instructions="You are a helpful assistant.",
20)
21print(f"Created agent, ID: {agent.id}")
22
23# Create a thread for the conversation
24thread = project_client.agents.create_thread()
25print(f"Created thread, ID: {thread.id}")
26
27# Create a message in the thread
28message = project_client.agents.create_message(
29 thread_id=thread.id,
30 role="user",
31 content="Hello, what can you do?",
32)
33print(f"Created message, ID: {message.id}")
34
35# Create and poll for the run
36run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
37print(f"Run finished with status: {run.status}")
38
39if run.status == "completed":
40 # Get messages from the thread
41 messages = project_client.agents.list_messages(thread_id=thread.id)
42 print(f"Response: {messages.data[0].content[0].text.value}")
43
44# Clean up (optional)
45project_client.agents.delete_agent(agent.id)
46print("Deleted agent")