Interpretér kódu

Interpret kódu umožňuje agentům psát a spouštět kód v prostředí v izolovaném prostoru (sandbox). To je užitečné pro analýzu dat, matematické výpočty, zpracování souborů a další úlohy, které využívají provádění kódu.

Poznámka:

Dostupnost interpreta kódu závisí na příslušném poskytovateli agenta. Viz Přehled poskytovatelů podpory pro konkrétního poskytovatele.

Warning

Kód, výstup spuštění a vygenerované soubory zůstanou vygenerované modelem a nedůvěryhodné i v případě, že dojde ke spuštění v hostovaném sandboxu. Než je použijete k rozhodování, vykreslování nebo předání výsledků jinému systému, ověřte výsledky.

Následující příklad ukazuje, jak vytvořit agenta pomocí nástroje Code Interpret a přečíst vygenerovaný výstup:

Vytvoření agenta pomocí interpretu kódu

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 je vhodný pro vývoj, ale vyžaduje pečlivé zvážení v produkčním prostředí. V produkčním prostředí zvažte použití konkrétních přihlašovacích údajů (např ManagedIdentityCredential. ) k zabránění problémům s latencí, neúmyslnému testování přihlašovacích údajů a potenciálním bezpečnostním rizikům z náhradních mechanismů.

Čtení výstupu kódu

// 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}");
        }
    }
}

Následující příklad ukazuje, jak vytvořit agenta pomocí nástroje Interpret kódu:

# 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())

Ukázka interpretu kódu OpenAI

Aktuální ukázka interpretu kódu OpenAI v úložišti kódu používá OpenAIChatClient a ukazuje, jak zkontrolovat vygenerovaný kód a výstup konečného spuštění:

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())

Interpret kódu

Typ hostedtool.CodeInterpreter umožňuje spuštění kódu na straně serveru při použití zprostředkovatele, který ho podporuje.

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},
    },
})

Spuštění agenta a čtení výstupu kódu

S foundry nebo OpenAI Odpovědi, zkontrolujte CodeInterpreterToolCallContent vygenerovaný kód a CodeInterpreterToolResultContent výstup spuštění. Vygenerovaný Python kód je uložen jako datový obsah, takže dekódujte ho .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)
            }
        }
    }
}

Odpověď zahrnuje odpověď a jakýkoli kód nebo výstup spuštění vrácený službou. U vygenerovaných souborů si ukázka stažení interpretu kódu OpenAI přečte poznámky k citaci a stáhne soubory s ID kontejneru i ID souboru.

Poznámka:

Interpret kódu je hostovaný nástroj – provádění kódu probíhá na straně služby AI, ne místně.

Další kroky