1# pylint: disable=line-too-long,useless-suppression
2# ------------------------------------
3# Copyright (c) Microsoft Corporation.
4# Licensed under the MIT License.
5# ------------------------------------
6
7"""
8DESCRIPTION:
9 This sample demonstrates how to use agent operations with code interpreter from
10 the Azure Agents service using a synchronous client.
11
12USAGE:
13 python sample_agents_code_interpreter.py
14
15 Before running the sample:
16
17 pip install azure-ai-projects azure-ai-agents azure-identity
18
19 Set these environment variables with your own values:
20 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview
21 page of your Azure AI Foundry portal.
22 2) MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in
23 the "Models + endpoints" tab in your Azure AI Foundry project.
24"""
25
26import os
27from azure.ai.projects import AIProjectClient
28from azure.ai.agents.models import CodeInterpreterTool
29from azure.ai.agents.models import FilePurpose, MessageRole
30from azure.identity import DefaultAzureCredential
31from pathlib import Path
32
33asset_file_path = os.path.abspath(
34 os.path.join(os.path.dirname(__file__), "../assets/synthetic_500_quarterly_results.csv")
35)
36
37project_client = AIProjectClient(
38 endpoint=os.environ["PROJECT_ENDPOINT"],
39 credential=DefaultAzureCredential(),
40)
41
42with project_client:
43 agents_client = project_client.agents
44
45 # Upload a file and wait for it to be processed
46 # [START upload_file_and_create_agent_with_code_interpreter]
47 file = agents_client.files.upload_and_poll(file_path=asset_file_path, purpose=FilePurpose.AGENTS)
48 print(f"Uploaded file, file ID: {file.id}")
49
50 code_interpreter = CodeInterpreterTool(file_ids=[file.id])
51
52 # Create agent with code interpreter tool and tools_resources
53 agent = agents_client.create_agent(
54 model=os.environ["MODEL_DEPLOYMENT_NAME"],
55 name="my-agent",
56 instructions="You are helpful agent",
57 tools=code_interpreter.definitions,
58 tool_resources=code_interpreter.resources,
59 )
60 # [END upload_file_and_create_agent_with_code_interpreter]
61 print(f"Created agent, agent ID: {agent.id}")
62
63 thread = agents_client.threads.create()
64 print(f"Created thread, thread ID: {thread.id}")
65
66 # Create a message
67 message = agents_client.messages.create(
68 thread_id=thread.id,
69 role="user",
70 content="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
71 )
72 print(f"Created message, message ID: {message.id}")
73
74 run = agents_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
75 print(f"Run finished with status: {run.status}")
76
77 if run.status == "failed":
78 # Check if you got "Rate limit is exceeded.", then you want to get more quota
79 print(f"Run failed: {run.last_error}")
80
81 agents_client.files.delete(file.id)
82 print("Deleted file")
83
84 # [START get_messages_and_save_files]
85 messages = agents_client.messages.list(thread_id=thread.id)
86 print(f"Messages: {messages}")
87
88 for msg in messages:
89 # Save every image file in the message
90 for img in msg.image_contents:
91 file_id = img.image_file.file_id
92 file_name = f"{file_id}_image_file.png"
93 agents_client.files.save(file_id=file_id, file_name=file_name)
94 print(f"Saved image file to: {Path.cwd() / file_name}")
95
96 # Print details of every file-path annotation
97 for ann in msg.file_path_annotations:
98 print("File Paths:")
99 print(f" Type: {ann.type}")
100 print(f" Text: {ann.text}")
101 print(f" File ID: {ann.file_path.file_id}")
102 print(f" Start Index: {ann.start_index}")
103 print(f" End Index: {ann.end_index}")
104 # [END get_messages_and_save_files]
105
106 last_msg = agents_client.messages.get_last_message_text_by_role(thread_id=thread.id, role=MessageRole.AGENT)
107 if last_msg:
108 print(f"Last Message: {last_msg.text.value}")
109
110 agents_client.delete_agent(agent.id)
111 print("Deleted agent")