Back to snippets

azure_ai_projects_sdk_agent_thread_message_run_quickstart.py

python

This quickstart demonstrates how to create an agent, create a t

15d ago46 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_ai_projects_sdk_agent_thread_message_run_quickstart.py
1import os
2from azure.ai.projects import AIProjectClient
3from azure.identity import DefaultAzureCredential
4
5# Get the project connection string from environment variables
6# Format: <region>.api.azureml.ms; <subscription_id>; <resource_group>; <project_name>
7project_connection_string = os.environ["PROJECT_CONNECTION_STRING"]
8
9# Initialize the Project Client
10project_client = AIProjectClient.from_connection_string(
11    conn_str=project_connection_string,
12    credential=DefaultAzureCredential()
13)
14
15# Create an Agent
16agent = project_client.agents.create_agent(
17    model="gpt-4o",
18    name="my-agent",
19    instructions="You are a helpful assistant.",
20)
21print(f"Created agent, ID: {agent.id}")
22
23# Create a Thread
24thread = project_client.agents.create_thread()
25print(f"Created thread, ID: {thread.id}")
26
27# Create a Message
28message = project_client.agents.create_message(
29    thread_id=thread.id,
30    role="user",
31    content="Hello, how can you help me today?",
32)
33print(f"Created message, ID: {message.id}")
34
35# Create and Run the Agent
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    # List messages in the thread to see the response
41    messages = project_client.agents.list_messages(thread_id=thread.id)
42    print(f"Response: {messages.data[0].content[0].text.value}")
43
44# Delete the agent when done
45project_client.agents.delete_agent(agent.id)
46print("Deleted agent")