-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathclient_with_code_interpreter.py
More file actions
57 lines (44 loc) · 1.77 KB
/
client_with_code_interpreter.py
File metadata and controls
57 lines (44 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework import (
Agent,
Content,
)
from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
"""
OpenAI Chat Client with Code Interpreter Example
This sample demonstrates using get_code_interpreter_tool() with OpenAI Chat Client
for Python code execution and mathematical problem solving.
"""
async def main() -> None:
"""Example showing how to use the code interpreter tool with OpenAI Chat."""
print("=== OpenAI Chat Client Agent with Code Interpreter Example ===")
client = OpenAIChatClient()
agent = Agent(
client=client,
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=client.get_code_interpreter_tool(),
)
query = "Use code to get the factorial of 100?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Result: {result}\n")
for message in result.messages:
code_blocks = [c for c in message.contents if c.type == "code_interpreter_tool_call"]
outputs = [c for c in message.contents if c.type == "code_interpreter_tool_result"]
if code_blocks:
code_inputs = code_blocks[0].inputs or []
for content in code_inputs:
if isinstance(content, Content) and content.type == "text":
print(f"Generated code:\n{content.text}")
break
if outputs:
print("Execution outputs:")
for out in outputs[0].outputs or []:
if isinstance(out, Content) and out.type == "text":
print(out.text)
if __name__ == "__main__":
asyncio.run(main())