コード インタープリター

コード インタープリターを使用すると、エージェントはサンドボックス環境でコードを記述して実行できます。 これは、データ分析、数学的計算、ファイル処理、およびコード実行のメリットを得るその他のタスクに役立ちます。

Note

コード インタープリターの可用性は、基になるエージェント プロバイダーによって異なります。 プロバイダー固有のサポートについては、「 プロバイダーの概要 」を参照してください。

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 コード インタープリターのサンプル

コード リポジトリの現在の OpenAI コード インタープリター サンプルでは、 OpenAIChatClient を使用し、生成されたコードと最終的な実行出力を検査する方法を示します。

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 応答を使用して、生成されたコードの CodeInterpreterToolCallContent を調べ、実行出力の CodeInterpreterToolResultContent を調べます。 生成された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 Code インタープリターのダウンロード サンプル では、引用文献の注釈を読み取り、コンテナー ID とファイル ID の両方を持つファイルをダウンロードします。

Note

コード インタープリターはホステッド ツールです。コードの実行は、ローカルではなく AI サービス側で行われます。

次のステップ