Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O Interpretador de Código permite que os agentes escrevam e executem código em um ambiente em área restrita. Isso é útil para análise de dados, cálculos matemáticos, processamento de arquivos e outras tarefas que se beneficiam da execução de código.
Note
A disponibilidade do Interpretador de Código depende do provedor de agente subjacente. Consulte a Visão geral dos provedores para obter suporte específico ao provedor.
Aviso
Código, saída de execução e arquivos gerados permanecem gerados por modelo e não confiáveis mesmo quando a execução ocorre em uma área restrita hospedada. Valide os resultados antes de usá-los para decisões, renderizando-os ou passando-os para outro sistema.
O exemplo a seguir mostra como criar um agente com a ferramenta Interpretador de Código e ler a saída gerada:
Criar um agente com o Interpretador de Código
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);
Aviso
DefaultAzureCredential é conveniente para o desenvolvimento, mas requer uma consideração cuidadosa na produção. Em produção, considere o uso de uma credencial específica (por exemplo, ManagedIdentityCredential) para evitar problemas de latência, investigação de credenciais não intencionais e possíveis riscos de segurança de mecanismos de fallback.
Ler a saída do código
// 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}");
}
}
}
O exemplo a seguir mostra como criar um agente com a ferramenta Interpretador de Código:
# 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())
Exemplo de interpretador de código OpenAI atual
O exemplo atual do interpretador de código OpenAI no repositório de código usa OpenAIChatClient e mostra como inspecionar o código gerado mais a saída de execução final:
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())
Interpretador de código
O hostedtool.CodeInterpreter tipo habilita a execução de código do lado do servidor ao usar um provedor compatível com ele.
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},
},
})
Executar o agente e ler a saída do código
Com o Foundry ou o OpenAI Responses, inspecione CodeInterpreterToolCallContent o código gerado e CodeInterpreterToolResultContent a saída de execução. O código Python gerado é armazenado como conteúdo de dados, portanto, decodificá-lo com 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)
}
}
}
}
A resposta inclui a resposta e qualquer saída de código ou execução retornada pelo serviço. Para arquivos gerados, o exemplo de download do Interpretador de Código OpenAI lê anotações de citação e baixa arquivos com a ID do contêiner e a ID do arquivo.
Note
O interpretador de código é uma ferramenta hospedada – a execução de código ocorre no lado do serviço de IA, não localmente.