مشاركة عبر


أداة مفسر الشيفرة المخصصة للوكلاء (معاينة)

مهم

العناصر التي تم وضع علامة عليها (إصدار أولي) في هذه المقالة موجودة حالياً في الإصدار الأولي العام. يتم توفير هذه المعاينة دون اتفاقية على مستوى الخدمة، ولا نوصي بها لأحمال عمل الإنتاج. بعض الميزات ربما لا تكون مدعمة أو بها بعض القدرات المقيدة. لمزيد من المعلومات، راجع شروط الاستخدام الإضافية لمعاينات Microsoft Azure.

يمنحك مفسر الكود المخصص تحكما كاملا في بيئة وقت التشغيل لكود Python الذي يتم إنشاؤه بواسطة الوكلاء. يمكنك تكوين حزم Python مخصصة، وموارد الحوسبة، وإعدادات Azure Container Apps للبيئة. تعرض حاوية مفسر الشيفرة خادم بروتوكول سياق النموذج (MCP).

استخدم مفسر كود مخصص عندما لا تلبي أداة مفسر الكود المدمجة للوكلاء متطلباتك — على سبيل المثال، عندما تحتاج إلى حزم Python محددة، أو صور حاويات مخصصة، أو موارد حوسبة مخصصة.

لمزيد من المعلومات حول MCP وكيفية اتصال الوكلاء بأدوات MCP، راجع خوادم Connect to Model Context Protocol (معاينة).

دعم الاستخدام

تستخدم هذه المقالة Azure CLI ومشروع عينة قابل للتشغيل.

✔️ (GA) تشير إلى التوفر العام، ✔️ (معاينة) تشير إلى معاينة عامة، وشرطة شرطة (-) تشير إلى عدم توفر الميزة.

دعم مايكروسوفت فاوندري حزمة تطوير التطوير الخاصة لبايثون C # SDK حزمة تطوير جافاسكريبت مجموعة تطوير جافا واجهة برمجة تطبيقات REST إعداد العامل الأساسي إعداد العامل القياسي
✔️ ✔️ (GA) ✔️ (معاينة) ✔️ (GA) ✔️ (معاينة) ✔️ (GA) - ✔️

للحصول على أحدث دعم لأدوات SDK وAPI للوكلاء، راجع أفضل الممارسات لاستخدام الأدوات في خدمة وكلاء Microsoft Foundry.

دعم عدة تطوير البرامج

يستخدم مفسر الشيفرة المخصص نوع أداة MCP. أي SDK يدعم أدوات MCP يمكنه إنشاء وكيل مفسر كود مخصص. مجموعات تطوير .NET و Java حاليا قيد المعاينة. لخطوات توفير البنية التحتية (Azure CLI، Bicep)، انظر إنشاء وكيل مع مفسر كود مخصص.

المتطلبات المسبقه

قبل البدء

يوفر هذا الإجراء بنية تحتية Azure، بما في ذلك موارد Azure Container Apps. راجع متطلبات تكلفة Azure وحوكمة مؤسستك قبل النشر.

أنشئ وكيل باستخدام مفسر كود مخصص

توضح الخطوات التالية كيفية توفير البنية التحتية وإنشاء وكيل يستخدم خادم MCP مخصص لمفسر الكود. ينطبق إعداد البنية التحتية على جميع اللغات. تتبع عينات الشيفرة الخاصة باللغة.

تسجيل ميزة المعاينة

تسجيل ميزة MCP server for Azure Container Apps Dynamic Sessions:

az feature register --namespace Microsoft.App --name SessionPoolsSupportMCP
az provider register -n Microsoft.App

الحصول على التعليمات البرمجية للعينة

قم بنسخ كود sample في مستودع GitHub وانتقل إلى مجلد samples/python/prompt-agents/code-interpreter-custom في جهازك.

توفير البنية التحتية

لتوفير البنية التحتية، شغل الأمر التالي باستخدام Azure CLI (az):

az deployment group create \
    --name custom-code-interpreter \
    --subscription <your_subscription> \
    --resource-group <your_resource_group> \
    --template-file ./infra.bicep

‏‫ملاحظة‬

قد يستغرق النشر حتى ساعة، حسب عدد الحالات الاحتياطية التي تطلبها. تخصيص تجمع الجلسات الديناميكي هو أطول خطوة.

تكوين وتشغيل الوكيل

انسخ الملف .env.sample من المستودع إلى .env واملأ القيم من مخرجات النشر الخاصة بك. يمكنك العثور على هذه القيم في بوابة Azure تحت مجموعة الموارد.

قم بتثبيت تبعيات Python باستخدام uv sync أو pip install. أخيرا، اركض ./main.py.

مثال عَلى الرمز

يوضح المثال التالي في Python كيفية إنشاء وكيل باستخدام أداة MCP مخصصة لمفسر الكود:

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, MCPTool

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
MCP_SERVER_URL = "https://your-mcp-server-url"
# Optional: set to your project connection ID if your MCP server requires authentication
MCP_CONNECTION_ID = "your-mcp-connection-id"

# Create clients to call Foundry API
project = AIProjectClient(
    endpoint=PROJECT_ENDPOINT,
    credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()

# Configure the custom code interpreter MCP tool
custom_code_interpreter = MCPTool(
    server_label="custom-code-interpreter",
    server_url=MCP_SERVER_URL,
    project_connection_id=MCP_CONNECTION_ID,
)

# Create an agent with the custom code interpreter
agent = project.agents.create_version(
    agent_name="CustomCodeInterpreterAgent",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions="You are a helpful assistant that can run Python code to analyze data and solve problems.",
        tools=[custom_code_interpreter],
    ),
    description="Agent with custom code interpreter for data analysis.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

# Test the agent with a simple calculation
response = openai.responses.create(
    input="Calculate the factorial of 10 using Python.",
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response: {response.output_text}")

# Clean up
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")

الإخراج المتوقع

عند تشغيل العينة، ترى مخرجا مشابها ل:

Agent created (id: agent-xxxxxxxxxxxx, name: CustomCodeInterpreterAgent, version: 1)
Response: The factorial of 10 is 3,628,800. I calculated this using Python's math.factorial() function.
Agent deleted

مثال عَلى الرمز

يوضح المثال التالي في C# كيفية إنشاء وكيل باستخدام أداة MCP مخصصة لمفسر الكود. لمزيد من المعلومات حول العمل مع أدوات MCP في .NET، راجع عينة أدوات MCP في Azure SDK المستودع .NET على GitHub.

using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var mcpServerUrl = "https://your-mcp-server-url";
// Optional: set to your project connection ID if your MCP server requires authentication
var mcpConnectionId = "your-mcp-connection-id";

// Create project client to call Foundry API
AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Create agent with custom code interpreter MCP tool
// Code runs in a sandboxed Azure Container Apps session
McpTool tool = ResponseTool.CreateMcpTool(
    serverLabel: "custom-code-interpreter",
    serverUri: new Uri(mcpServerUrl));
tool.ProjectConnectionId = mcpConnectionId;

PromptAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful assistant that can run Python code to analyze data and solve problems.",
    Tools = { tool }
};

AgentVersion agent = projectClient.Agents.CreateAgentVersion(
    agentName: "CustomCodeInterpreterAgent",
    options: new(agentDefinition));

Console.WriteLine($"Agent created: {agent.Name} (version {agent.Version})");

// Create a response using the agent
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agent.Name);

ResponseResult response = responseClient.CreateResponse(
    new([ResponseItem.CreateUserMessageItem("Calculate the factorial of 10 using Python.")]));

Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.Agents.DeleteAgentVersion(
    agentName: agent.Name,
    agentVersion: agent.Version);
Console.WriteLine("Agent deleted");

الإخراج المتوقع

Agent created: CustomCodeInterpreterAgent (version 1)
The factorial of 10 is 3,628,800.
Agent deleted

مثال عَلى الرمز

توضح عينة TypeScript التالية كيفية إنشاء وكيل باستخدام أداة MCP مخصصة لمفسر الكود. للحصول على نسخة جافاسكريبت، راجع نموذج أداة MCP في Azure SDK مستودع جافاسكريبت على GitHub.

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const MCP_SERVER_URL = "https://your-mcp-server-url";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create agent with custom code interpreter MCP tool
  // The custom code interpreter uses require_approval: "never" because code
  // runs in a sandboxed Azure Container Apps session
  const agent = await project.agents.createVersion("CustomCodeInterpreterAgent", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions:
      "You are a helpful assistant that can run Python code to analyze data and solve problems.",
    tools: [
      {
        type: "mcp",
        server_label: "custom-code-interpreter",
        server_url: MCP_SERVER_URL,
        require_approval: "never",
      },
    ],
  });
  console.log(`Agent created (name: ${agent.name}, version: ${agent.version})`);

  // Send a request to the agent
  const response = await openai.responses.create(
    {
      input: "Calculate the factorial of 10 using Python.",
    },
    {
      body: { agent: { name: agent.name, type: "agent_reference" } },
    },
  );
  console.log(`Response: ${response.output_text}`);

  // Clean up
  await project.agents.deleteVersion(agent.name, agent.version);
  console.log("Agent deleted");
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

الإخراج المتوقع

Agent created (name: CustomCodeInterpreterAgent, version: 1)
Response: The factorial of 10 is 3,628,800. I calculated this using Python's math.factorial() function.
Agent deleted

أضف الاعتماد إلى :pom.xml

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.0.0-beta.3</version>
</dependency>

مثال عَلى الرمز

import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

import java.util.Collections;

public class CustomCodeInterpreterExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";
        String mcpServerUrl = "https://your-mcp-server-url";
        // Optional: set to your project connection ID if your MCP server requires authentication
        String mcpConnectionId = "your-mcp-connection-id";

        // Create clients to call Foundry API
        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint);

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create custom code interpreter MCP tool
        // Uses require_approval: "never" because code runs in a sandboxed Container Apps session
        McpTool customCodeInterpreter = new McpTool("custom-code-interpreter")
            .setServerUrl(mcpServerUrl)
            .setProjectConnectionId(mcpConnectionId)
            .setRequireApproval("never");

        PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
            .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.")
            .setTools(Collections.singletonList(customCodeInterpreter));

        AgentVersionDetails agent = agentsClient.createAgentVersion(
            "CustomCodeInterpreterAgent", agentDefinition);
        System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());

        // Create a response
        AgentReference agentReference = new AgentReference(agent.getName())
            .setVersion(agent.getVersion());

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions().setAgentReference(agentReference),
            ResponseCreateParams.builder()
                .input("Calculate the factorial of 10 using Python."));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
        System.out.println("Agent deleted");
    }
}

الإخراج المتوقع

Agent created: CustomCodeInterpreterAgent (version 1)
Response: The factorial of 10 is 3,628,800.
Agent deleted

المتطلبات المسبقه

اضبط هذه المتغيرات البيئية:

  • FOUNDRY_PROJECT_ENDPOINT: رابط نقطة نهاية مشروعك.
  • AGENT_TOKEN: رمز حامل للمفاهرة.

الحصول على رمز مميز للوصول:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

مثال عَلى الرمز

1. إنشاء وكيل مع مفسر كود مخصص

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "name": "CustomCodeInterpreterAgent",
    "definition": {
      "kind": "prompt",
      "model": "<MODEL_DEPLOYMENT>",
      "instructions": "You are a helpful assistant that can run Python code to analyze data and solve problems.",
      "tools": [
        {
          "type": "mcp",
          "server_label": "custom-code-interpreter",
          "server_url": "<MCP_SERVER_URL>",
          "project_connection_id": "<MCP_PROJECT_CONNECTION_ID>",
          "require_approval": "never"
        }
      ]
    }
  }'

2. إنشاء رد

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "agent_reference": {"type": "agent_reference", "name": "CustomCodeInterpreterAgent"},
    "input": "Calculate the factorial of 10 using Python."
  }'

3. التنظيف

curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/CustomCodeInterpreterAgent?api-version=v1" \
  -H "Authorization: Bearer $AGENT_TOKEN"

الإخراج المتوقع

{
  "id": "resp_xxxxxxxxxxxx",
  "output": [
    {
      "type": "message",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The factorial of 10 is 3,628,800."
        }
      ]
    }
  ]
}

التحقق من الإعداد

بعد أن تقوم بتوفير البنية التحتية وتشغيل العينة:

  1. أكد أن نشر Azure قد اكتمل بنجاح.
  2. تأكد من أن العينة متصلة باستخدام القيم الموجودة في ملفك .env .
  3. في Microsoft Foundry، تحقق من استدعاء وكيلك للأداة باستخدام التتبع. لمزيد من المعلومات، راجع أفضل الممارسات لاستخدام الأدوات في خدمة وكلاء مايكروسوفت فاوندري.

استكشاف الأخطاء وإصلاحها

مشكلة السبب المحتمل الحل
لا يزال تسجيل الميزات قيد الانتظار الأمر az feature register يعيد Registering الحالة. انتظر حتى يكتمل التسجيل (قد يستغرق من 15 إلى 30 دقيقة). تحقق من الحالة مع az feature show --namespace Microsoft.App --name SessionPoolsSupportMCP. ثم اركض az provider register -n Microsoft.App مرة أخرى.
فشل النشر مع خطأ في الإذن تفويت المهام المطلوبة. تأكد من أن لديك أدوار Azure AI Owner وContainer Apps ManagedEnvironment Contributor في مجموعة الاشتراك أو الموارد.
فشل النشر بسبب خطأ في المنطقة المنطقة المحددة لا تدعم Azure Container Apps Dynamic Sessions. جرب منطقة مختلفة. انظر Azure Container Apps regions للمناطق المدعومة.
العميل لا يتصل بالأداة اتصال MCP غير مضبط بشكل صحيح، أو تعليمات الوكيل لا تطلب استخدام الأداة. استخدم التتبع في Microsoft Foundry لتأكيد استدعاء الأداة. تحقق من تطابق MCP_SERVER_URL نقطة نهاية تطبيقات الحاويات التي تم نشرها. اطلع على أفضل الممارسات.
مهلة الاتصال بخادم MCP مجموعة جلسات تطبيقات الحاويات لا تعمل أو لا تحتوي على نسخ احتياطية. تحقق من حالة مجموعة الجلسات في بوابة Azure. زد standbyInstanceCount في قالب Bicep إذا لزم الأمر.
فشل تنفيذ الشيفرة في الحاوية حزم Python مفقودة في الحاوية المخصصة. قم بتحديث صورة الحاوية لتشمل الطرود المطلوبة. أعد بناء الحاوية وأعد نشرها.
خطأ في المصادقة في الاتصال بخادم MCP بيانات الاتصال بالمشروع غير صالحة أو منتهية الصلاحية. أعد توليد بيانات الاتصال وحدث الملف .env . تحقق من التنسيق MCP_PROJECT_CONNECTION_ID .

القيود

واجهات برمجة التطبيقات لا تدعم مباشرة إدخال أو إخراج الملفات، أو استخدام مخازن الملفات. لإدخال وخروج البيانات، يجب استخدام عناوين URL، مثل عناوين URL للملفات الصغيرة وعناوين توقيع الوصول المشترك (SAS) لخدمة Azure Blob للملفات الكبيرة.

الأمان

إذا كنت تستخدم عناوين URL الخاصة ب SAS لتمرير البيانات داخل أو خارج وقت التشغيل:

  • استخدم رموز SAS قصيرة العمر.
  • لا تسجل عناوين SAS أو تخزنها في التحكم المصدري.
  • اجعل صلاحيات النطاق إلى الحد الأدنى المطلوب (على سبيل المثال، القراءة فقط أو الكتابة فقط).

تنظيف

لإيقاف الفوترة للموارد المخصصة، قم بحذف الموارد التي تم إنشاؤها بواسطة نشر العينة. إذا استخدمت مجموعة موارد مخصصة لهذا المقال، احذف مجموعة الموارد.