Skip to content

Commit 8bdcd4e

Browse files
authored
Python: Added Samples for HostedCodeInterpreterTool with files (microsoft#1583)
* code interpreter with files * import fix
1 parent 73bff48 commit 8bdcd4e

3 files changed

Lines changed: 182 additions & 0 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import os
5+
import tempfile
6+
7+
from agent_framework import ChatAgent, HostedCodeInterpreterTool
8+
from agent_framework.azure import AzureOpenAIResponsesClient
9+
from azure.identity import AzureCliCredential
10+
from openai import AsyncAzureOpenAI
11+
12+
"""
13+
Azure OpenAI Responses Client with Code Interpreter and Files Example
14+
15+
This sample demonstrates using HostedCodeInterpreterTool with Azure OpenAI Responses
16+
for Python code execution and data analysis with uploaded files.
17+
"""
18+
19+
# Helper functions
20+
21+
22+
async def create_sample_file_and_upload(openai_client: AsyncAzureOpenAI) -> tuple[str, str]:
23+
"""Create a sample CSV file and upload it to Azure OpenAI."""
24+
csv_data = """name,department,salary,years_experience
25+
Alice Johnson,Engineering,95000,5
26+
Bob Smith,Sales,75000,3
27+
Carol Williams,Engineering,105000,8
28+
David Brown,Marketing,68000,2
29+
Emma Davis,Sales,82000,4
30+
Frank Wilson,Engineering,88000,6
31+
"""
32+
33+
# Create temporary CSV file
34+
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as temp_file:
35+
temp_file.write(csv_data)
36+
temp_file_path = temp_file.name
37+
38+
# Upload file to Azure OpenAI
39+
print("Uploading file to Azure OpenAI...")
40+
with open(temp_file_path, "rb") as file:
41+
uploaded_file = await openai_client.files.create(
42+
file=file,
43+
purpose="assistants", # Required for code interpreter
44+
)
45+
46+
print(f"File uploaded with ID: {uploaded_file.id}")
47+
return temp_file_path, uploaded_file.id
48+
49+
50+
async def cleanup_files(openai_client: AsyncAzureOpenAI, temp_file_path: str, file_id: str) -> None:
51+
"""Clean up both local temporary file and uploaded file."""
52+
# Clean up: delete the uploaded file
53+
await openai_client.files.delete(file_id)
54+
print(f"Cleaned up uploaded file: {file_id}")
55+
56+
# Clean up temporary local file
57+
os.unlink(temp_file_path)
58+
print(f"Cleaned up temporary file: {temp_file_path}")
59+
60+
61+
async def main() -> None:
62+
print("=== Azure OpenAI Code Interpreter with File Upload ===")
63+
64+
# Initialize Azure OpenAI client for file operations
65+
credential = AzureCliCredential()
66+
67+
async def get_token():
68+
token = credential.get_token("https://cognitiveservices.azure.com/.default")
69+
return token.token
70+
71+
openai_client = AsyncAzureOpenAI(
72+
azure_ad_token_provider=get_token,
73+
api_version="2024-05-01-preview",
74+
)
75+
76+
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
77+
78+
# Create agent using Azure OpenAI Responses client
79+
agent = ChatAgent(
80+
chat_client=AzureOpenAIResponsesClient(credential=credential),
81+
instructions="You are a helpful assistant that can analyze data files using Python code.",
82+
tools=HostedCodeInterpreterTool(inputs=[{"file_id": file_id}]),
83+
)
84+
85+
# Test the code interpreter with the uploaded file
86+
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
87+
print(f"User: {query}")
88+
result = await agent.run(query)
89+
print(f"Agent: {result.text}")
90+
91+
await cleanup_files(openai_client, temp_file_path, file_id)
92+
93+
94+
if __name__ == "__main__":
95+
asyncio.run(main())

python/samples/getting_started/agents/openai/openai_assistants_with_file_search.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ async def delete_vector_store(client: OpenAIAssistantsClient, file_id: str, vect
3939

4040

4141
async def main() -> None:
42+
print("=== OpenAI Assistants Client Agent with File Search Example ===\n")
43+
4244
client = OpenAIAssistantsClient()
4345
async with ChatAgent(
4446
chat_client=client,
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import os
5+
import tempfile
6+
7+
from agent_framework import ChatAgent, HostedCodeInterpreterTool
8+
from agent_framework.openai import OpenAIResponsesClient
9+
from openai import AsyncOpenAI
10+
11+
"""
12+
OpenAI Responses Client with Code Interpreter and Files Example
13+
14+
This sample demonstrates using HostedCodeInterpreterTool with OpenAI Responses Client
15+
for Python code execution and data analysis with uploaded files.
16+
"""
17+
18+
# Helper functions
19+
20+
21+
async def create_sample_file_and_upload(openai_client: AsyncOpenAI) -> tuple[str, str]:
22+
"""Create a sample CSV file and upload it to OpenAI."""
23+
csv_data = """name,department,salary,years_experience
24+
Alice Johnson,Engineering,95000,5
25+
Bob Smith,Sales,75000,3
26+
Carol Williams,Engineering,105000,8
27+
David Brown,Marketing,68000,2
28+
Emma Davis,Sales,82000,4
29+
Frank Wilson,Engineering,88000,6
30+
"""
31+
32+
# Create temporary CSV file
33+
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as temp_file:
34+
temp_file.write(csv_data)
35+
temp_file_path = temp_file.name
36+
37+
# Upload file to OpenAI
38+
print("Uploading file to OpenAI...")
39+
with open(temp_file_path, "rb") as file:
40+
uploaded_file = await openai_client.files.create(
41+
file=file,
42+
purpose="assistants", # Required for code interpreter
43+
)
44+
45+
print(f"File uploaded with ID: {uploaded_file.id}")
46+
return temp_file_path, uploaded_file.id
47+
48+
49+
async def cleanup_files(openai_client: AsyncOpenAI, temp_file_path: str, file_id: str) -> None:
50+
"""Clean up both local temporary file and uploaded file."""
51+
# Clean up: delete the uploaded file
52+
await openai_client.files.delete(file_id)
53+
print(f"Cleaned up uploaded file: {file_id}")
54+
55+
# Clean up temporary local file
56+
os.unlink(temp_file_path)
57+
print(f"Cleaned up temporary file: {temp_file_path}")
58+
59+
60+
async def main() -> None:
61+
"""Complete example of uploading a file to OpenAI and using it with code interpreter."""
62+
print("=== OpenAI Code Interpreter with File Upload ===")
63+
64+
openai_client = AsyncOpenAI()
65+
66+
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
67+
68+
# Create agent using OpenAI Responses client
69+
agent = ChatAgent(
70+
chat_client=OpenAIResponsesClient(),
71+
instructions="You are a helpful assistant that can analyze data files using Python code.",
72+
tools=HostedCodeInterpreterTool(inputs=[{"file_id": file_id}]),
73+
)
74+
75+
# Test the code interpreter with the uploaded file
76+
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
77+
print(f"User: {query}")
78+
result = await agent.run(query)
79+
print(f"Agent: {result.text}")
80+
81+
await cleanup_files(openai_client, temp_file_path, file_id)
82+
83+
84+
if __name__ == "__main__":
85+
asyncio.run(main())

0 commit comments

Comments
 (0)