📘
【Azure AI Agent Service】- code interpriterエージェントの作り方
執筆日
2025/4/2
やること
Azure AI Agent Seriviceでcode interpriterエージェントを作ってみる。
前提
- Azure AI Agent Serviceを構築済みであること
code interpriterとは?
サンドボックス化された実行環境でPythonコードを実行することができます。
それにより、エージェントがPythonコードを実行しデータ分析などを行うことができます。
ただ実行するだけでなくコードの実行が成功するまで、コードを変更して実行することで、このコードを反復処理をすることができます。
対応しているファイル形式は?
以下のDocsに記載されています。
ファイルのサイズは?
Code interpriterだけではなく、Azure AI Agent Seriviceで作成されるエージェントは、以下のクォーターと制限があります。
制限名 | 制限値 |
---|---|
エージェント/スレッドあたりの最大ファイル数 | API または Azure AI Foundry ポータルを使用する場合は 10,000 個。 Azure OpenAI Studio では、制限は 20 でした。 |
エージェントの最大ファイルサイズと微調整 | 512 MB |
エージェント用にアップロードされたすべてのファイルの最大サイズ | 100 GB |
エージェント トークンの制限 | 2,000,000 トークンの制限 |
code interpriterエージェントを作ってみる(GUI)
- Azure AI Agent Serviceを開く
-
エージェント>+新しいエージェントをクリック
-
アクション>+追加をクリック
-
コードインタープリターをクリック
-
ローカルファイルを選択をクリック
- ファイルをアップロード
※今回は大阪市の区別推計人口・世帯数のデータを使う
https://www.city.osaka.lg.jp/contents/wdu290/opendata/#cat-51_data-00000377 -
アップロードして保存するをクリック
-
プレイグラウンドで試すをクリック
- エージェントと会話する
注意点
- 以下のようなエラーが出ることがある(プレビュー版なので仕方ない??)
- データからグラフ化することはできるが日本語は非対応
- ライブラリーのインストールはできない
ちなみに
OCRに関しては、Pythonのコードで出力をしている。
※LLMを使ってのOCRはしていない..(できるようにしてほしい.....)
code interpriterエージェントを作ってみる(code)
MicrosoftからコードのサンプルがGithub上にあります。こちらをベースにします。
市町村の情報を聞く
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.ai.projects.models import FilePurpose, MessageRole
from azure.identity import DefaultAzureCredential
from pathlib import Path
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(), conn_str=<"projectの接続文字列">
)
with project_client:
# Upload a file and wait for it to be processed
# [START upload_file_and_create_agent_with_code_interpreter]
file = project_client.agents.upload_file_and_poll(
file_path="shihyo2023.xlsx", purpose=FilePurpose.AGENTS
)
print(f"Uploaded file, file ID: {file.id}")
code_interpreter = CodeInterpreterTool(file_ids=[file.id])
# Create agent with code interpreter tool and tools_resources
agent = project_client.agents.create_agent(
model=<"model名">,
name="my-assistant",
instructions="You are helpful assistant",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
# [END upload_file_and_create_agent_with_code_interpreter]
print(f"Created agent, agent ID: {agent.id}")
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")
# Create a message
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="該当xlsxに記載されている各市長村の名前を教えて",
)
print(f"Created message, message ID: {message.id}")
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
# Check if you got "Rate limit is exceeded.", then you want to get more quota
print(f"Run failed: {run.last_error}")
project_client.agents.delete_file(file.id)
print("Deleted file")
# [START get_messages_and_save_files]
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
for image_content in messages.image_contents:
file_id = image_content.image_file.file_id
print(f"Image File ID: {file_id}")
file_name = f"{file_id}_image_file.png"
project_client.agents.save_file(file_id=file_id, file_name=file_name)
print(f"Saved image file to: {Path.cwd() / file_name}")
for file_path_annotation in messages.file_path_annotations:
print(f"File Paths:")
print(f"Type: {file_path_annotation.type}")
print(f"Text: {file_path_annotation.text}")
print(f"File ID: {file_path_annotation.file_path.file_id}")
print(f"Start Index: {file_path_annotation.start_index}")
print(f"End Index: {file_path_annotation.end_index}")
# [END get_messages_and_save_files]
last_msg = messages.get_last_text_message_by_role(MessageRole.AGENT)
if last_msg:
print(f"Last Message: {last_msg.text.value}")
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
結果
Last Message: 以下は、該当のExcelファイルに記載されていた各市町村の名前のリストです:
### 市
- 大阪市
- 堺市
- 岸和田市
- 豊中市
- 池田市
- 吹田市
- 泉大津市
- 高槻市
- 貝塚市
- 守口市
- 枚方市
- 茨木市
- 八尾市
- 泉佐野市
- 富田林市
- 寝屋川市
- 河内長野市
- 松原市
- 大東市
- 和泉市
- 箕面市
- 柏原市
- 羽曳野市
- 門真市
- 摂津市
- 高石市
- 藤井寺市
- 東大阪市
- 泉南市
- 四條畷市
- 交野市
- 大阪狭山市
- 阪南市
### 町
- 島本町
- 豊能町
- 能勢町
- 忠岡町
- 熊取町
- 田尻町
- 岬町
- 太子町
- 河南町
### 村
- 千早赤阪村
何か他の情報が必要でしたらお知らせください。
大阪市の人口を聞く
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.ai.projects.models import FilePurpose, MessageRole
from azure.identity import DefaultAzureCredential
from pathlib import Path
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(), conn_str=<"projectの接続文字列">
)
with project_client:
# Upload a file and wait for it to be processed
# [START upload_file_and_create_agent_with_code_interpreter]
file = project_client.agents.upload_file_and_poll(
file_path="shihyo2023.xlsx", purpose=FilePurpose.AGENTS
)
print(f"Uploaded file, file ID: {file.id}")
code_interpreter = CodeInterpreterTool(file_ids=[file.id])
# Create agent with code interpreter tool and tools_resources
agent = project_client.agents.create_agent(
model=<"model名">,
name="my-assistant",
instructions="You are helpful assistant",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
# [END upload_file_and_create_agent_with_code_interpreter]
print(f"Created agent, agent ID: {agent.id}")
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")
# Create a message
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="該当xlsxに記載されている大阪市の人口を教えて",
)
print(f"Created message, message ID: {message.id}")
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
# Check if you got "Rate limit is exceeded.", then you want to get more quota
print(f"Run failed: {run.last_error}")
project_client.agents.delete_file(file.id)
print("Deleted file")
# [START get_messages_and_save_files]
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
for image_content in messages.image_contents:
file_id = image_content.image_file.file_id
print(f"Image File ID: {file_id}")
file_name = f"{file_id}_image_file.png"
project_client.agents.save_file(file_id=file_id, file_name=file_name)
print(f"Saved image file to: {Path.cwd() / file_name}")
for file_path_annotation in messages.file_path_annotations:
print(f"File Paths:")
print(f"Type: {file_path_annotation.type}")
print(f"Text: {file_path_annotation.text}")
print(f"File ID: {file_path_annotation.file_path.file_id}")
print(f"Start Index: {file_path_annotation.start_index}")
print(f"End Index: {file_path_annotation.end_index}")
# [END get_messages_and_save_files]
last_msg = messages.get_last_text_message_by_role(MessageRole.AGENT)
if last_msg:
print(f"Last Message: {last_msg.text.value}")
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
結果
Last Message: 大阪市の人口は、以下の通りです。
- **総人口**: 2,756,807人
- **男性**: 1,326,742人
- **女性**: 1,430,065人
他に知りたい情報があれば教えてください。
Deleted agent
グラフを作成
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.ai.projects.models import FilePurpose, MessageRole
from azure.identity import DefaultAzureCredential
from pathlib import Path
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(), conn_str=<"projectの接続文字列">
)
with project_client:
# Upload a file and wait for it to be processed
# [START upload_file_and_create_agent_with_code_interpreter]
file = project_client.agents.upload_file_and_poll(
file_path="shihyo2023.xlsx", purpose=FilePurpose.AGENTS
)
print(f"Uploaded file, file ID: {file.id}")
code_interpreter = CodeInterpreterTool(file_ids=[file.id])
# Create agent with code interpreter tool and tools_resources
agent = project_client.agents.create_agent(
model=<"model名">,
name="my-assistant",
instructions="You are helpful assistant",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
# [END upload_file_and_create_agent_with_code_interpreter]
print(f"Created agent, agent ID: {agent.id}")
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")
# Create a message
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="該当xlsxに記載されている大阪市の人口分布をグラフにしてください",
)
print(f"Created message, message ID: {message.id}")
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
# Check if you got "Rate limit is exceeded.", then you want to get more quota
print(f"Run failed: {run.last_error}")
project_client.agents.delete_file(file.id)
print("Deleted file")
# [START get_messages_and_save_files]
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
for image_content in messages.image_contents:
file_id = image_content.image_file.file_id
print(f"Image File ID: {file_id}")
file_name = f"{file_id}_image_file.png"
project_client.agents.save_file(file_id=file_id, file_name=file_name)
print(f"Saved image file to: {Path.cwd() / file_name}")
for file_path_annotation in messages.file_path_annotations:
print(f"File Paths:")
print(f"Type: {file_path_annotation.type}")
print(f"Text: {file_path_annotation.text}")
print(f"File ID: {file_path_annotation.file_path.file_id}")
print(f"Start Index: {file_path_annotation.start_index}")
print(f"End Index: {file_path_annotation.end_index}")
# [END get_messages_and_save_files]
last_msg = messages.get_last_text_message_by_role(MessageRole.AGENT)
if last_msg:
print(f"Last Message: {last_msg.text.value}")
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
結果
以下のようにグラフがExportされる
まとめ
Code interpriterエージェントを作ってみました。
データ分析エージェントとして開発するのに役立つなと感じました。
ライブラリーがインストールできないのだけネック。
Discussion