-
Notifications
You must be signed in to change notification settings - Fork 4k
Python: Add chat completion agent code interpreter sample #12393
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
TaoChenOSU
merged 2 commits into
main
from
taochen/python_chat_completion_agent_code_interpreter_sample
Jun 6, 2025
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
116 changes: 116 additions & 0 deletions
116
...ting_started_with_agents/chat_completion/step12_chat_completion_agent_code_interpreter.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
# Copyright (c) Microsoft. All rights reserved. | ||
|
||
import asyncio | ||
import datetime | ||
import os | ||
|
||
from azure.core.credentials import AccessToken | ||
from azure.core.exceptions import ClientAuthenticationError | ||
from azure.identity import DefaultAzureCredential | ||
|
||
from semantic_kernel.agents import ChatCompletionAgent | ||
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion | ||
from semantic_kernel.contents import ChatMessageContent, FunctionCallContent, FunctionResultContent | ||
from semantic_kernel.core_plugins import SessionsPythonTool | ||
|
||
""" | ||
The following sample demonstrates how to create a chat completion agent with | ||
code interpreter capabilities using the Azure Container Apps session pool service. | ||
""" | ||
|
||
auth_token: AccessToken | None = None | ||
|
||
ACA_TOKEN_ENDPOINT: str = "https://acasessions.io/.default" | ||
|
||
|
||
async def auth_callback() -> str: | ||
TaoChenOSU marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Auth callback for the SessionsPythonTool. | ||
|
||
This is a sample auth callback that shows how to use Azure's DefaultAzureCredential | ||
to get an access token. | ||
""" | ||
global auth_token | ||
current_utc_timestamp = int(datetime.datetime.now(datetime.timezone.utc).timestamp()) | ||
|
||
if not auth_token or auth_token.expires_on < current_utc_timestamp: | ||
credential = DefaultAzureCredential() | ||
|
||
try: | ||
auth_token = credential.get_token(ACA_TOKEN_ENDPOINT) | ||
except ClientAuthenticationError as cae: | ||
err_messages = getattr(cae, "messages", []) | ||
raise RuntimeError( | ||
f"Failed to retrieve the client auth token with messages: {' '.join(err_messages)}" | ||
) from cae | ||
|
||
return auth_token.token | ||
|
||
|
||
async def handle_intermediate_steps(message: ChatMessageContent) -> None: | ||
for item in message.items or []: | ||
if isinstance(item, FunctionResultContent): | ||
print(f"# Function Result:> {item.result}") | ||
elif isinstance(item, FunctionCallContent): | ||
print(f"# Function Call:> {item.name} with arguments: {item.arguments}") | ||
else: | ||
print(f"# {message.name}: {message} ") | ||
|
||
|
||
async def main(): | ||
# 1. Create the python code interpreter tool using the SessionsPythonTool | ||
python_code_interpreter = SessionsPythonTool(auth_callback=auth_callback) | ||
|
||
# 2. Create the agent | ||
agent = ChatCompletionAgent( | ||
service=AzureChatCompletion(), | ||
name="Host", | ||
instructions="Answer questions about the menu.", | ||
plugins=[python_code_interpreter], | ||
) | ||
|
||
# 3. Upload a CSV file to the session | ||
csv_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "resources", "sales.csv") | ||
file_metadata = await python_code_interpreter.upload_file(local_file_path=csv_file_path) | ||
|
||
# 4. Invoke the agent for a response to a task | ||
TASK = ( | ||
"What's the total sum of all sales for all segments using Python? " | ||
f"Use the uploaded file {file_metadata.full_path} for reference." | ||
) | ||
print(f"# User: '{TASK}'") | ||
async for response in agent.invoke( | ||
messages=TASK, | ||
on_intermediate_message=handle_intermediate_steps, | ||
): | ||
print(f"# {response.name}: {response} ") | ||
|
||
""" | ||
Sample output: | ||
# User: 'What's the total sum of all sales for all segments using Python? | ||
Use the uploaded file /mnt/data/sales.csv for reference.' | ||
# Function Call:> SessionsPythonTool-execute_code with arguments: { | ||
"code": " | ||
import pandas as pd | ||
|
||
# Load the sales data | ||
file_path = '/mnt/data/sales.csv' | ||
sales_data = pd.read_csv(file_path) | ||
|
||
# Calculate the total sum of sales | ||
# Assuming there's a column named 'Sales' which contains the sales amounts | ||
total_sales = sales_data['Sales'].sum() | ||
total_sales" | ||
} | ||
# Function Result:> Status: | ||
Success | ||
Result: | ||
118726350.28999999 | ||
Stdout: | ||
|
||
Stderr: | ||
# Host: The total sum of all sales for all segments is approximately $118,726,350.29. | ||
""" | ||
|
||
|
||
if __name__ == "__main__": | ||
asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.