코드 인터프리터를 사용하면 에이전트가 샌드박스 환경에서 코드를 작성하고 실행할 수 있습니다. 이는 데이터 분석, 수학 계산, 파일 처리 및 코드 실행의 이점을 활용하는 기타 작업에 유용합니다.
비고
코드 인터프리터 가용성은 기본 에이전트 공급자에 따라 달라집니다. 공급자별 지원은 공급자 개요를 참조하세요.
Warning
코드, 실행 출력 및 생성된 파일은 호스트된 샌드박스에서 실행이 발생하는 경우에도 모델 생성 및 신뢰할 수 없는 상태로 유지됩니다. 결정에 대해 결과를 사용하거나, 렌더링하거나, 다른 시스템에 전달하기 전에 결과의 유효성을 검사합니다.
다음 예제에서는 코드 인터프리터 도구를 사용하여 에이전트를 만들고 생성된 출력을 읽는 방법을 보여줍니다.
코드 인터프리터를 사용하여 에이전트 만들기
using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
// Requires: dotnet add package Microsoft.Agents.AI.Foundry --prerelease
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
// Create an agent with the code interpreter hosted tool
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant that can write and execute Python code.",
tools: [new CodeInterpreterToolDefinition()]);
var response = await agent.RunAsync("Calculate the factorial of 100 using code.");
Console.WriteLine(response);
Warning
DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.
코드 출력 읽기
// Inspect code interpreter output from the response
foreach (var message in response.Messages)
{
foreach (var content in message.Contents)
{
if (content is CodeInterpreterContent codeContent)
{
Console.WriteLine($"Code:\n{codeContent.Code}");
Console.WriteLine($"Output:\n{codeContent.Output}");
}
}
}
다음 예제에서는 코드 인터프리터 도구를 사용하여 에이전트를 만드는 방법을 보여줍니다.
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework import (
Agent,
Content,
)
from agent_framework.openai import OpenAIChatClient
"""
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())
현재 OpenAI 코드 인터프리터 샘플
코드 리포지토리 OpenAIChatClient 의 현재 OpenAI 코드 인터프리터 샘플은 생성된 코드와 최종 실행 출력을 검사하는 방법을 보여 줍니다.
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())
코드 인터프리터
이 형식은 hostedtool.CodeInterpreter 지원하는 공급자를 사용할 때 서버 쪽 코드를 실행할 수 있도록 합니다.
import "github.com/microsoft/agent-framework-go/tool/hostedtool"
codeInterpreter := &hostedtool.CodeInterpreter{}
a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
Config: agent.Config{
Tools: []tool.Tool{codeInterpreter},
},
})
에이전트 실행 및 코드 출력 읽기
Foundry 또는 OpenAI 응답을 사용하여 생성된 코드와 CodeInterpreterToolResultContent 실행 출력을 검사 CodeInterpreterToolCallContent 합니다. 생성된 Python 코드는 데이터 콘텐츠로 저장되므로 디코딩합니다DataContent.Bytes.
import (
"context"
"fmt"
"github.com/microsoft/agent-framework-go/message"
)
response, err := a.RunText(
context.Background(),
"Calculate the factorial of 100 using code.",
).Collect()
if err != nil {
panic(err)
}
fmt.Println(response.String())
for content := range response.Contents() {
switch value := content.(type) {
case *message.CodeInterpreterToolCallContent:
for _, input := range value.Inputs {
if data, ok := input.(*message.DataContent); ok {
code, err := data.Bytes()
if err != nil {
panic(err)
}
fmt.Printf("Code:\n%s\n", code)
}
}
case *message.CodeInterpreterToolResultContent:
for _, output := range value.Outputs {
switch result := output.(type) {
case *message.TextContent:
fmt.Println(result.Text)
case *message.URIContent:
fmt.Println(result.URI)
}
}
}
}
응답에는 응답과 서비스에서 반환하는 모든 코드 또는 실행 출력이 포함됩니다. 생성된 파일의 경우 OpenAI 코드 인터프리터 다운로드 샘플 은 인용 주석을 읽고 컨테이너 ID와 파일 ID를 모두 사용하여 파일을 다운로드합니다.
비고
코드 인터프리터는 호스트된 도구입니다. 코드 실행은 로컬이 아닌 AI 서비스 쪽에서 수행됩니다.