Back to snippets
azure_ai_projects_agent_creation_with_thread_messaging.py
pythonThis quickstart demonstrates how to connect to an Azure AI Project and
Agent Votes
1
0
100% positive
azure_ai_projects_agent_creation_with_thread_messaging.py
1import os
2from azure.ai.projects import AIProjectClient
3from azure.identity import DefaultAzureCredential
4
5# Get your connection string from the Azure AI Studio project settings
6# It should look like: <region>.api.azureml.ms; <subscription_id>; <resource_group>; <project_name>
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
15agent = project_client.agents.create_agent(
16 model="gpt-4-1106-preview",
17 name="my-assistant",
18 instructions="You are a helpful assistant.",
19)
20print(f"Created agent, ID: {agent.id}")
21
22# Create a thread
23thread = project_client.agents.create_thread()
24print(f"Created thread, ID: {thread.id}")
25
26# Create a message
27message = project_client.agents.create_message(
28 thread_id=thread.id,
29 role="user",
30 content="Hello, how are you?",
31)
32print(f"Created message, ID: {message.id}")
33
34# Run the agent
35run = project_client.agents.create_run(thread_id=thread.id, assistant_id=agent.id)
36print(f"Created run, ID: {run.id}")
37
38while run.status in ["queued", "in_progress", "requires_action"]:
39 import time
40 time.sleep(1)
41 run = project_client.agents.get_run(thread_id=thread.id, run_id=run.id)
42
43print(f"Run completed with status: {run.status}")
44
45# Get messages from the thread
46messages = project_client.agents.list_messages(thread_id=thread.id)
47print(f"Messages: {messages.data[0].content[0].text.value}")
48
49# Delete the agent when done
50project_client.agents.delete_agent(agent.id)
51print("Deleted agent")