مشاركة عبر


ربط الوكلاء بأدوات OpenAPI

قم بتوصيل وكلاء Microsoft Foundry الخاص بك بواجهات برمجة تطبيقات خارجية باستخدام مواصفات OpenAPI 3.0 و3.1. يمكن للوكلاء الذين يتصلون بأدوات OpenAPI استدعاء خدمات خارجية، واسترجاع البيانات في الوقت الحقيقي، وتوسيع قدراتهم إلى ما هو أبعد من الوظائف المدمجة.

تحدد مواصفات OpenAPI طريقة معيارية لوصف واجهات برمجة تطبيقات HTTP حتى تتمكن من دمج الخدمات القائمة مع وكلائك. يدعم مايكروسوفت فاوندري ثلاث طرق للمصادقة: anonymous، API key، و managed identity. للحصول على المساعدة في اختيار طريقة مصادقة، راجع اختيار طريقة مصادقة.

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

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

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

‏‫ملاحظة‬

بالنسبة Java، استخدم حزمة com.azure:azure-ai-agents لأدوات وكلاء OpenAPI. com.azure:azure-ai-projects الحزمة لا تكشف حاليا عن أنواع أدوات وكلاء OpenAPI.

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

قبل أن تبدأ، تأكد من أن لديك:

  • اشتراك في Azure مع الأذونات الصحيحة.
  • دور Azure RBAC: مساهم أو مالك في مشروع Foundry.
  • مشروع Foundry تم إنشاؤه مع تكوين نقطة نهاية.
  • نموذج الذكاء الاصطناعي تم تطبيقه في مشروعك.
  • بيئة عامل أساسية أو قياسية.
  • تم تثبيت SDK للغة المفضلة لديك:
    • بايثون: azure-ai-projects
    • C#: Azure.AI.Extensions.OpenAI (قبل الإصدار)
    • TypeScript/JavaScript: @azure/ai-projects
    • Java: com.azure:azure-ai-agents (ما قبل الإصدار)

متغيرات البيئة

المتغير وصف
FOUNDRY_PROJECT_ENDPOINT رابط نقطة نهاية مشروع Foundry الخاص بك (وليس نقطة نهاية خدمة OpenAPI الخارجية).
FOUNDRY_MODEL_DEPLOYMENT_NAME اسم الطراز الذي تم نشره.
OPENAPI_PROJECT_CONNECTION_NAME (للمصادقة على مفاتيح API) اسم اتصال مشروعك لخدمة OpenAPI.
  • ملف مواصفات OpenAPI 3.0 أو 3.1 الذي يستوفي هذه المتطلبات:
    • يجب أن تحتوي كل دالة على ( operationId مطلوب لأداة OpenAPI).
    • operationId يجب أن تحتوي فقط على الحروف، -و _.
    • استخدم الأسماء الوصفية لمساعدة النماذج على تحديد الوظيفة التي يجب استخدامها بكفاءة.
    • أنواع محتوى الطلبات المدعومة: application/json, application/json-patch+json
  • للمصادقة المدارة للهوية: دور القارئ أو أعلى على موارد الخدمة المستهدفة.
  • بالنسبة لمصادقة مفتاح API/الرمز: اتصال مشروع تم تكوينه باستخدام مفتاح أو رمز API الخاص بك. انظر أضف اتصالا جديدا لمشروعك.

‏‫ملاحظة‬

FOUNDRY_PROJECT_ENDPOINT القيمة تشير إلى نقطة نهاية مشروع Microsoft Foundry الخاص بك، وليس نقطة نهاية خدمة OpenAPI الخارجية. يمكنك العثور على هذه النقطة النهائية في بوابة Microsoft Foundry تحت صفحة النظرة العامة لمشروعك. هذه النقطة النهائية مطلوبة لمصادقة خدمة الوكيل وهي منفصلة عن أي نقاط نهاية OpenAPI معرفة في ملف المواصفات الخاص بك.

فهم القيود

  • يجب أن تتضمن operationId مواصفات OpenAPI الخاصة بك لكل عملية، ويمكن operationId أن تتضمن فقط الحروف، -، و _.
  • أنواع محتوى جسم الطلب المدعوم: application/json, application/json-patch+json.
  • للمصادقة على مفاتيح API، استخدم نظام أمان واحد لكل أداة OpenAPI. إذا كنت بحاجة إلى عدة أنظمة أمانية، أنشئ عدة أدوات OpenAPI.

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

‏‫ملاحظة‬

  • تحتاج إلى أحدث حزمة SDK. مجموعات تطوير .NET و Java حاليا قيد المعاينة. راجع البداية السريعة للتفاصيل.
  • إذا كنت تستخدم مفتاح API للمصادقة، يجب أن يكون معرف الاتصال الخاص بك بصيغة /subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}}.

مهم

لكي تعمل مصادقة مفاتيح API، يجب أن يتضمن ملف مواصفات OpenAPI الخاص بك:

  1. قسم securitySchemes يحتوي على تكوين مفتاح واجهة برمجة التطبيقات الخاصة بك، مثل اسم الرأس واسم المعاملات.
  2. security قسم يشير إلى نظام الأمان.
  3. اتصال مشروع مهيأ بنفس اسم المفتاح وقيمته.

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

يمكنك أيضا استخدام المصادقة المعتمدة على الرمز (على سبيل المثال، رمز Bearer) عن طريق تخزين الرمز في اتصال المشروع. للحصول على مصادقة رمز الحامل، أنشئ اتصال مفاتيح مخصص مع تعيين المفتاح إلى Authorization والقيمة على Bearer <token> (استبدله <token> برمزك الفعلي). يجب تضمين الكلمة Bearer التي تلي بمسافة في القيمة. للتفاصيل، انظر إعداد اتصال رمز الحامل.

مثال كامل

import os
import jsonref
from typing import Any, cast
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    OpenApiTool,
    OpenApiFunctionDefinition,
    OpenApiAnonymousAuthDetails,
)

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
OPENAPI_CONNECTION_NAME = "my-openapi-connection"

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

weather_asset_file_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../assets/weather_openapi.json")
)

with open(weather_asset_file_path, "r") as f:
    openapi_weather = cast(dict[str, Any], jsonref.loads(f.read()))

# Initialize agent OpenAPI tool using the read in OpenAPI spec
weather_tool = OpenApiTool(
    openapi=OpenApiFunctionDefinition(
        name="get_weather",
        spec=openapi_weather,
        description="Retrieve weather information for a location.",
        auth=OpenApiAnonymousAuthDetails(),
    )
)

# If you want to use key-based authentication
# IMPORTANT: Your OpenAPI spec must include securitySchemes and security sections
# Example spec structure for API key auth:
# {
#   "components": {
#     "securitySchemes": {
#       "apiKeyHeader": {
#         "type": "apiKey",
#         "name": "x-api-key",  # This must match the key name in your project connection
#         "in": "header"
#       }
#     }
#   },
#   "security": [{"apiKeyHeader": []}]
# }
#
# For Bearer token authentication, use this securitySchemes structure instead:
# {
#   "components": {
#     "securitySchemes": {
#       "bearerAuth": {
#         "type": "apiKey",
#         "name": "Authorization",
#         "in": "header"
#       }
#     }
#   },
#   "security": [{"bearerAuth": []}]
# }
# Then set connection key = "Authorization" and value = "Bearer <token>"
# The word "Bearer" followed by a space MUST be included in the value.

openapi_connection = project.connections.get(OPENAPI_CONNECTION_NAME)
connection_id = openapi_connection.id

openapi_key_auth_tool = {
    "type": "openapi",
    "openapi": {
        "name": "get_weather",
        "spec": openapi_weather,  # Must include securitySchemes and security sections
        "auth": {
            "type": "project_connection",
            "security_scheme": {
                "project_connection_id": connection_id
            }
        },
    }
}

# If you want to use Managed Identity authentication
openapi_mi_auth_tool = {
    "type": "openapi",
    "openapi": {
        "name": "get_weather",
        "description": "Retrieve weather information for a location.",
        "spec": openapi_weather,
        "auth": {
            "type": "managed_identity",
            "security_scheme": {
                "audience": "https://storage.azure.com"  # Resource identifier of the target service
            }
        },
    }
}

agent = project.agents.create_version(
    agent_name="MyAgent",
    definition=PromptAgentDefinition(
        model="gpt-4.1-mini",
        instructions="You are a helpful assistant.",
        tools=[weather_tool],
    ),
)
response = openai.responses.create(
    input="What's the weather in Seattle?",
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(response.output_text)

# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)

ماذا يفعل هذا الكود

هذا المثال ينشئ وكيلا باستخدام أداة OpenAPI تستدعي واجهة الطقس wttr.in باستخدام المصادقة المجهولة. عند تشغيل الكود:

  1. يقوم بتحميل مواصفة OpenAPI الخاصة بالطقس من ملف JSON محلي.
  2. ينشئ وكيلا مع أداة الطقس مهيأة للوصول المجهول.
  3. يرسل استفسارا يسأل عن طقس سياتل.
  4. يستخدم الوكيل أداة OpenAPI لاستدعاء واجهة الطقس ويعيد النتائج المنسقة.
  5. ينظف عن طريق حذف نسخة الوكيل.

المدخلات المطلوبة

  • قيم السلاسل النصية في أعلى السكربت: PROJECT_ENDPOINT، OPENAPI_CONNECTION_NAME
  • الملف المحلي: weather_openapi.json (مواصفة OpenAPI)

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

Agent created (id: asst_abc123, name: MyAgent23, version: 1)
Response created: The weather in Seattle is currently cloudy with a temperature of 52°F (11°C)...

Cleaning up...
Agent deleted

الأخطاء الشائعة

  • FileNotFoundError: ملف مواصفات OpenAPI غير موجود في المسار المحدد
  • AuthenticationError: بيانات اعتماد غير صالحة أو صلاحيات غير كافية، أو مفقودة securitySchemes في مواصفات OpenAPI لمصادقة مفاتيح API:
  • تنسيق غير صالح operationId في مواصفات OpenAPI يسبب فشل تسجيل الأداة
  • مفتاح API غير محقن: تحقق من أن مواصفة OpenAPI الخاصة بك تشمل كلا securitySchemes القسمين و security ، وأن اسم المفتاح يتطابق مع اتصال مشروعك

عينة من استخدام الوكلاء مع أداة OpenAPI

يوضح هذا المثال كيفية استخدام الخدمات الموصوفة بمواصفة OpenAPI باستخدام وكيل. يستخدم خدمة wttr.in للحصول على الطقس وملف المواصفات weather_openapi.json. يستخدم هذا المثال الطرق المتزامنة لمكتبة عملاء Azure AI Projects. لمثال يستخدم طرقا غير متزامنة، راجع sample في Azure SDK المستودع .NET على GitHub.

using System;
using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

class OpenAPIDemo
{
    // Utility method to get the OpenAPI specification file from the Assets folder.
    private static string GetFile([CallerFilePath] string pth = "")
    {
        var dirName = Path.GetDirectoryName(pth) ?? "";
        return Path.Combine(dirName, "Assets", "weather_openapi.json");
    }

    public static void Main()
    {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        var projectEndpoint = "your_project_endpoint";

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

        // Create an Agent with `OpenAPIAgentTool` and anonymous authentication.
        string filePath = GetFile();
        OpenAPIFunctionDefinition toolDefinition = new(
            name: "get_weather",
            spec: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
            auth: new OpenAPIAnonymousAuthenticationDetails()
        );
        toolDefinition.Description = "Retrieve weather information for a location.";
        OpenAPITool openapiTool = new(toolDefinition);

        // Create the agent definition and the agent version.
        PromptAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
        {
            Instructions = "You are a helpful assistant.",
            Tools = { openapiTool }
        };
        AgentVersion agentVersion = projectClient.Agents.CreateAgentVersion(
            agentName: "myAgent",
            options: new(agentDefinition));

        // Create a response object and ask the question about the weather in Seattle, WA.
        ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
        ResponseResult response = responseClient.CreateResponse(
                userInputText: "Use the OpenAPI tool to print out, what is the weather in Seattle, WA today."
            );
        Console.WriteLine(response.GetOutputText());

        // Finally, delete all the resources created in this sample.
        projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
    }
}

ماذا يفعل هذا الكود

هذا المثال في C# ينشئ وكيلا باستخدام أداة OpenAPI تسترجع معلومات الطقس من wttr.in باستخدام المصادقة المجهولة. عند تشغيل الكود:

  1. يقرأ مواصفة OpenAPI الخاصة بالطقس من ملف JSON محلي.
  2. ينشئ وكيلا مع أداة الطقس مضبوطة.
  3. يرسل طلبا يسأل عن طقس سياتل باستخدام أداة OpenAPI.
  4. يقوم الوكيل باستدعاء واجهة برمجة تطبيقات الطقس ويعيد النتائج.
  5. ينظف عن طريق حذف الوكيل.

المدخلات المطلوبة

  • قيمة السلسلة النصية الداخلية: projectEndpoint (نقطة نهاية مشروع Foundry الخاص بك)
  • الملف المحلي: Assets/weather_openapi.json (مواصفة OpenAPI)

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

The weather in Seattle, WA today is cloudy with temperatures around 52°F...

الأخطاء الشائعة

  • FileNotFoundExceptionملف مواصفات OpenAPI غير موجود في مجلد الأصول:
  • UnauthorizedAccessException: بيانات الاعتماد غير الصالحة أو عدم صلاحيات RBAC
  • مفتاح API غير محقن: تحقق من أن مواصفات OpenAPI الخاصة بك تشمل كل من securitySchemes (in components) وأقسام security بأسماء أنظمة مطابقة

مثال على استخدام الوكلاء مع أداة OpenAPI على خدمة الويب، ويتطلب المصادقة

في هذا المثال، تستخدم خدمات بمواصفات OpenAPI باستخدام الوكيل في سيناريو يتطلب مصادقة. أنت تستخدم مواصفة تريب أدفايزر.

خدمة TripAdvisor تتطلب المصادقة عبر المفاتيح. لإنشاء اتصال في بوابة Azure، افتح Microsoft Foundry وفي اللوحة اليسرى اختر Management center ثم اختر Connected resources. وأخيرا، أنشئ اتصالا جديدا من نوع مفاتيح مخصصة . اذكر وأضف tripadvisor زوج قيم مفتاح. أضف المفتاح المسمى key وأدخل قيمة بمفتاح TripAdvisor الخاص بك.

class OpenAPIConnectedDemo
{
    // Utility method to get the OpenAPI specification file from the Assets folder.
    private static string GetFile([CallerFilePath] string pth = "")
    {
        var dirName = Path.GetDirectoryName(pth) ?? "";
        return Path.Combine(dirName, "Assets", "tripadvisor_openapi.json");
    }

    public static void Main()
    {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        var projectEndpoint = "your_project_endpoint";

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

        // Create an Agent with `OpenAPIAgentTool` and authentication by project connection security scheme.
        string filePath = GetFile();
        AIProjectConnection tripadvisorConnection = projectClient.Connections.GetConnection("tripadvisor");
        OpenAPIFunctionDefinition toolDefinition = new(
            name: "tripadvisor",
            spec: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
            auth: new OpenAPIProjectConnectionAuthenticationDetails(new OpenAPIProjectConnectionSecurityScheme(
                projectConnectionId: tripadvisorConnection.Id
            ))
        );
        toolDefinition.Description = "Trip Advisor API to get travel information.";
        OpenAPITool openapiTool = new(toolDefinition);

        // Create the agent definition and the agent version.
        PromptAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
        {
            Instructions = "You are a helpful assistant.",
            Tools = { openapiTool }
        };
        AgentVersion agentVersion = projectClient.Agents.CreateAgentVersion(
            agentName: "myAgent",
            options: new(agentDefinition));

        // Create a response object and ask the question about the hotels in France.
        // Test the Web service access before you run production scenarios.
        // It can be done by setting:
        // ToolChoice = ResponseToolChoice.CreateRequiredChoice()`
        // in the ResponseCreationOptions. This setting will
        // force Agent to use tool and will trigger the error if it is not accessible.
        ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
        CreateResponseOptions responseOptions = new()
        {
            ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
            InputItems =
            {
                ResponseItem.CreateUserMessageItem("Recommend me 5 top hotels in paris, France."),
            }
        };
        ResponseResult response = responseClient.CreateResponse(
            options: responseOptions
        );
        Console.WriteLine(response.GetOutputText());

        // Finally, delete all the resources we have created in this sample.
        projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
    }
}

ماذا يفعل هذا الكود

يوضح مثال C# هذا استخدام أداة OpenAPI مع مصادقة مفاتيح API من خلال اتصال المشروع. عند تشغيل الكود:

  1. يقوم بتحميل مواصفة TripAdvisor OpenAPI من ملف محلي.
  2. يسترجع اتصال المشروع الذي tripadvisor يحتوي على مفتاح واجهة برمجة التطبيقات الخاصة بك.
  3. ينشئ وكيلا باستخدام أداة TripAdvisor المهيأة لاستخدام الاتصال للمصادقة.
  4. يرسل طلبا لتوصيات فنادق في باريس.
  5. يقوم الوكيل باستدعاء واجهة برمجة تطبيقات TripAdvisor باستخدام مفتاح API المخزن الخاص بك ويعيد النتائج.
  6. ينظف عن طريق حذف الوكيل.

المدخلات المطلوبة

  • قيمة السلسلة النصية الداخلية: projectEndpoint (نقطة نهاية مشروع Foundry الخاص بك)
  • الملف المحلي: Assets/tripadvisor_openapi.json
  • اتصال المشروع: tripadvisor مع مفتاح API صالح مهيأ

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

Here are 5 top hotels in Paris, France:
1. Hotel Name - Rating: 4.5/5, Location: ...
2. Hotel Name - Rating: 4.4/5, Location: ...
...

الأخطاء الشائعة

  • ConnectionNotFoundException: لم يتم العثور على أي صلة بمشروع مسمى tripadvisor .
  • AuthenticationException: مفتاح API غير صالح في اتصال المشروع، أو إعداد مفقود/غير صحيح securitySchemes في مواصفات OpenAPI.
  • الأداة غير المستخدمة: تحقق ToolChoice = ResponseToolChoice.CreateRequiredChoice() من استخدام الأدوات القوية.
  • مفتاح API غير مرر إلى API: تأكد من أن مواصفات OpenAPI محددة وأقسام securitySchemes محددةsecurity.

أنشئ وكيل Java مع قدرات أداة OpenAPI

هذا المثال Java ينشئ وكيلا باستخدام أداة OpenAPI باستخدام com.azure:azure-ai-agents وملف مواصفات محلي ل OpenAPI. تستخدم العينة المصادقة المجهولة وتستدعي نقطة نهاية واجهة برمجة تطبيقات عامة.

import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ConversationsClient;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.*;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.json.JsonProviders;
import com.azure.json.JsonReader;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.items.ItemCreateParams;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;

public class OpenApiAgentJavaSample {
    public static void main(String[] args) throws Exception {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .endpoint(projectEndpoint)
            .credential(new DefaultAzureCredentialBuilder().build());

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

        Map<String, BinaryData> spec = OpenApiFunctionDefinition.readSpecFromFile(
            Paths.get("openapi_spec.json"));

        OpenApiFunctionDefinition toolDefinition = new OpenApiFunctionDefinition(
            "httpbin_get",
            spec,
            new OpenApiAnonymousAuthDetails())
            .setDescription("Get request metadata from an OpenAPI endpoint.");

        PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-4.1-mini")
            .setInstructions("Use the OpenAPI tool for HTTP request metadata.")
            .setTools(Arrays.asList(new OpenApiTool(toolDefinition)));

        AgentVersionDetails agentVersion = agentsClient.createAgentVersion("openapiValidationAgentJava", agentDefinition);
        System.out.println("Agent: " + agentVersion.getName() + ", version: " + agentVersion.getVersion());

        Conversation conversation = conversationsClient.getConversationService().create();
        conversationsClient.getConversationService().items().create(
            ItemCreateParams.builder()
                .conversationId(conversation.id())
                .addItem(EasyInputMessage.builder()
                    .role(EasyInputMessage.Role.USER)
                    .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.")
                    .build())
                .build());

        try {
            AgentReference agentReference = new AgentReference(agentVersion.getName()).setVersion(agentVersion.getVersion());
            ResponseCreateParams.Builder options = ResponseCreateParams.builder().maxOutputTokens(300L);
            Response response = responsesClient.createAzureResponse(
                new AzureCreateResponseOptions().setAgentReference(agentReference),
                options.conversation(conversation.id()));

            String text = response.output().stream()
                .filter(item -> item.isMessage())
                .map(item -> item.asMessage().content()
                    .get(item.asMessage().content().size() - 1)
                    .asOutputText()
                    .text())
                .reduce((first, second) -> second)
                .orElse("<no message output>");

            System.out.println("Status: " + response.status().map(Object::toString).orElse("unknown"));
            System.out.println("Response: " + text);
        } finally {
            agentsClient.deleteAgentVersion(agentVersion.getName(), agentVersion.getVersion());
            System.out.println("Agent deleted");
        }
    }
}

ماذا يفعل هذا الكود

هذا المثال في Java ينشئ وكيلا باستخدام أداة OpenAPI ويشغل استجابة موجهة للمحادثة:

  1. يقوم بتحميل مواصفة OpenAPI من openapi_spec.json.
  2. ينشئ نسخة وكيل باستخدام OpenApiTool.
  3. ينشئ محادثة ويضيف رسالة مستخدم.
  4. ينشئ استجابة عن طريق تمرير AgentReference ومعرف المحادثة.
  5. ينظف عن طريق حذف نسخة الوكيل.

المدخلات المطلوبة

  • قيمة السلسلة النصية الداخلية: projectEndpoint (نقطة نهاية مشروع Foundry الخاص بك)
  • الملف المحلي: openapi_spec.json (مواصفة OpenAPI 3.0 أو 3.1)

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

Agent: openapiValidationAgentJava, version: 1
Status: completed
Response: The API response reports URL ... and origin ...
Agent deleted

الأخطاء الشائعة

  • Invalid OpenAPI specification: قم بتحليل JSON الخاص ب OpenAPI إلى كائن قبل تمريره إلى OpenApiFunctionDefinition.
  • Invalid conversation id: أنشئ محادثة ومرر conversation.id() إلى createAzureResponse عبر ResponseCreateParams.builder().conversation().
  • AuthenticationFailedException: يمكن للتحقق DefaultAzureCredential الحصول على رمز لحسابك المسجل.

توضح الأمثلة التالية كيفية استدعاء أداة OpenAPI باستخدام واجهة برمجة تطبيقات REST.

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

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

مصادقة مجهولة

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": { "type": "anonymous" },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            }
          }
        }
      }
    ]
  }'

مصادقة مفاتيح API (اتصال المشروع)

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": {
            "type": "project_connection",
            "security_scheme": {
              "project_connection_id": "'$WEATHER_APP_PROJECT_CONNECTION_ID'"
            }
          },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            },
            "components": {
              "securitySchemes": {
                "apiKeyHeader": {
                  "type": "apiKey",
                  "name": "x-api-key",
                  "in": "header"
                }
              }
            },
            "security": [
              { "apiKeyHeader": [] }
            ]
          }
        }
      }
    ]
  }'

استخدام مُصادقة الهوية المدارة

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": {
            "type": "managed_identity",
            "security_scheme": {
              "audience": "'$MANAGED_IDENTITY_AUDIENCE'"
            }
          },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            }
          }
        }
      }
    ]
  }'

ماذا يفعل هذا الكود

يوضح مثال واجهة برمجة التطبيقات REST هذا كيفية استدعاء أداة OpenAPI باستخدام طرق مصادقة مختلفة. الطلب:

  1. يرسل استفسارا إلى الوكيل يسأل عن حالة الطقس في سياتل.
  2. يتضمن تعريف أداة OpenAPI المتوافق مع مواصفة واجهة الطقس.
  3. يعرض ثلاثة خيارات للمصادقة (مجهول، مفتاح API عبر اتصال المشروع، هوية مدارة) كبدائل معلقة.
  4. يستخدم الوكيل الأداة لاستدعاء واجهة الطقس ويعيد النتائج المنسقة.

المدخلات المطلوبة

  • متغيرات البيئة: FOUNDRY_PROJECT_ENDPOINT, AGENT_TOKEN, . FOUNDRY_MODEL_DEPLOYMENT_NAME
  • بالنسبة لمصادقة مفتاح API: WEATHER_APP_PROJECT_CONNECTION_ID.
  • للمصادقة على الهوية المدارة: MANAGED_IDENTITY_AUDIENCE.
  • مواصفة OpenAPI المضمنة في جسم الطلب.

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

{
  "id": "resp_abc123",
  "object": "response",
  "output": [
    {
      "type": "message",
      "content": [
        {
          "type": "text",
          "text": "The weather in Seattle, WA today is cloudy with a temperature of 52°F (11°C)..."
        }
      ]
    }
  ]
}

الأخطاء الشائعة

  • 401 Unauthorized: غير صالح أو مفقود AGENT_TOKEN، أو مفتاح API غير محشور لأن securitySchemes و security مفقودان في مواصفات OpenAPI الخاصة بك
  • 404 Not Found: اسم نقطة نهاية أو نشر نموذج غير صحيح
  • 400 Bad Request: مواصفة OpenAPI مشوهة أو تكوين مصادقة غير صالح
  • مفتاح API لم يرسل مع الطلب: تحقق من أن components.securitySchemes القسم في مواصفات OpenAPI لديك مهيأ بشكل صحيح (وليس فارغا) ويتطابق اسم مفتاح اتصال المشروع الخاص بك

أنشئ وكيلا بقدرات أداة OpenAPI

يوضح المثال التالي لكود TypeScript كيفية إنشاء وكيل ذكاء اصطناعي بقدرات أداة OpenAPI باستخدام عميل OpenApiTool ومشروع Azure المتزامن للذكاء الاصطناعي. يمكن للوكيل استدعاء واجهات برمجة التطبيقات الخارجية المعرفة بمواصفات OpenAPI. للحصول على نسخة جافا سكريبت من هذا المثال، راجع sample في Azure SDK مستودع جافاسكريبت على GitHub.

import { DefaultAzureCredential } from "@azure/identity";
import {
  AIProjectClient,
  OpenApiTool,
  OpenApiFunctionDefinition,
  OpenApiAnonymousAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const weatherSpecPath = path.resolve(__dirname, "../assets", "weather_openapi.json");

function loadOpenApiSpec(specPath: string): unknown {
  if (!fs.existsSync(specPath)) {
    throw new Error(`OpenAPI specification not found at: ${specPath}`);
  }

  try {
    const data = fs.readFileSync(specPath, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
  }
}

function createWeatherTool(spec: unknown): OpenApiTool {
  const auth: OpenApiAnonymousAuthDetails = { type: "anonymous" };
  const definition: OpenApiFunctionDefinition = {
    name: "get_weather",
    description: "Retrieve weather information for a location using wttr.in",
    spec,
    auth,
  };

  return {
    type: "openapi",
    openapi: definition,
  };
}

export async function main(): Promise<void> {
  const weatherSpec = loadOpenApiSpec(weatherSpecPath);

  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create an agent with the OpenAPI weather tool
  const agent = await project.agents.createVersion("MyOpenApiAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions:
      "You are a helpful assistant that can call external APIs defined by OpenAPI specs to answer user questions.",
    tools: [createWeatherTool(weatherSpec)],
  });

  // Send a request and stream the response
  const streamResponse = await openai.responses.create(
    {
      input:
        "What's the weather in Seattle and how should I plan my outfit for the day based on the forecast?",
      stream: true,
    },
    {
      body: {
        agent: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n");
    }
  }

  // Clean up resources
  await project.agents.deleteVersion(agent.name, agent.version);
}

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

ماذا يفعل هذا الكود

ينشئ هذا المثال من TypeScript وكيلا باستخدام أداة OpenAPI لبيانات الطقس باستخدام المصادقة المجهولة. عند تشغيل الكود:

  1. يقوم بتحميل مواصفة OpenAPI الخاصة بالطقس من ملف JSON محلي.
  2. ينشئ وكيلا مع أداة الطقس مضبوطة.
  3. يرسل طلب بث يسأل عن تخطيط الطقس والملابس في سياتل.
  4. يعالج استجابة البث ويعرض الدلتا عند وصولها.
  5. يجبر استخدام الأدوات من خلال التأكد tool_choice: "required" من استدعاء واجهة برمجة التطبيقات (API).
  6. ينظف عن طريق حذف الوكيل.

المدخلات المطلوبة

  • قيمة السلسلة النصية الداخلية: PROJECT_ENDPOINT (نقطة نهاية مشروع Foundry الخاص بك)
  • الملف المحلي: ../assets/weather_openapi.json (مواصفة OpenAPI)

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

Loading OpenAPI specifications from assets directory...
Creating agent with OpenAPI tool...
Agent created (id: asst_abc123, name: MyOpenApiAgent, version: 1)

Sending request to OpenAPI-enabled agent with streaming...
Follow-up response created with ID: resp_xyz789
The weather in Seattle is currently...
Tool call completed: get_weather

Follow-up completed!

Cleaning up resources...
Agent deleted

OpenAPI agent sample completed!

الأخطاء الشائعة

  • Error: OpenAPI specification not found: مسار الملف غير صحيح أو الملف مفقود
  • AuthenticationError: بيانات Azure غير صالحة
  • مفتاح API لا يعمل: إذا كنت تنتقل من مصادقة مفتاح المجهول إلى مصادقة مفتاح API، تأكد من أن مواصفات OpenAPI لديك مهيأة securitySchemes بشكل security صحيح

أنشئ وكيلا يستخدم أدوات OpenAPI مصادقة مع اتصال مشروع

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

import { DefaultAzureCredential } from "@azure/identity";
import {
  AIProjectClient,
  OpenApiTool,
  OpenApiFunctionDefinition,
  OpenApiProjectConnectionAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const TRIPADVISOR_CONNECTION_ID = "your-tripadvisor-connection-id";
const tripAdvisorSpecPath = path.resolve(__dirname, "../assets", "tripadvisor_openapi.json");

function loadOpenApiSpec(specPath: string): unknown {
  if (!fs.existsSync(specPath)) {
    throw new Error(`OpenAPI specification not found at: ${specPath}`);
  }

  try {
    const data = fs.readFileSync(specPath, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
  }
}

function createTripAdvisorTool(spec: unknown): OpenApiTool {
  const auth: OpenApiProjectConnectionAuthDetails = {
    type: "project_connection",
    security_scheme: {
      project_connection_id: TRIPADVISOR_CONNECTION_ID,
    },
  };

  const definition: OpenApiFunctionDefinition = {
    name: "get_tripadvisor_location_details",
    description:
      "Fetch TripAdvisor location details, reviews, or photos using the Content API via project connection auth.",
    spec,
    auth,
  };

  return {
    type: "openapi",
    openapi: definition,
  };
}

export async function main(): Promise<void> {
  const tripAdvisorSpec = loadOpenApiSpec(tripAdvisorSpecPath);

  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create an agent with the OpenAPI project-connection tool
  const agent = await project.agents.createVersion("MyOpenApiConnectionAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions:
      "You are a travel assistant that consults the TripAdvisor Content API via project connection to answer user questions about locations.",
    tools: [createTripAdvisorTool(tripAdvisorSpec)],
  });

  // Send a request and stream the response
  const streamResponse = await openai.responses.create(
    {
      input:
        "Provide a quick overview of the TripAdvisor location 293919 including its name, rating, and review count.",
      stream: true,
    },
    {
      body: {
        agent: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n");
    }
  }

  // Clean up resources
  await project.agents.deleteVersion(agent.name, agent.version);
}

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

ماذا يفعل هذا الكود

يوضح هذا المثال من TypeScript استخدام أداة OpenAPI مع مصادقة مفاتيح API من خلال اتصال المشروع. عند تشغيل الكود:

  1. يقوم بتحميل مواصفة TripAdvisor OpenAPI من ملف محلي.
  2. يقوم بتكوين المصادقة باستخدام الثابت TRIPADVISOR_CONNECTION_ID .
  3. ينشئ وكيلا باستخدام أداة TripAdvisor يستخدم اتصال المشروع للمصادقة على مفاتيح API.
  4. يرسل طلب بث لتفاصيل موقع TripAdvisor لنقل المشروع.
  5. يجبر استخدام الأدوات من خلال التأكد tool_choice: "required" من استدعاء واجهة برمجة التطبيقات (API).
  6. يعالج ويعرض استجابة البث.
  7. يتم التنظيف عن طريق حذف الوكيل.

المدخلات المطلوبة

  • قيم السلاسل النصية الداخلية: PROJECT_ENDPOINT، TRIPADVISOR_CONNECTION_ID
  • الملف المحلي: ../assets/tripadvisor_openapi.json
  • اتصال المشروع مكونا بمفتاح واجهة برمجة تطبيقات TripAdvisor

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

Loading TripAdvisor OpenAPI specification from assets directory...
Creating agent with OpenAPI project-connection tool...
Agent created (id: asst_abc123, name: MyOpenApiConnectionAgent, version: 1)

Sending request to TripAdvisor OpenAPI agent with streaming...
Follow-up response created with ID: resp_xyz789
Location 293919 is the Eiffel Tower in Paris, France. It has a rating of 4.5 stars with over 140,000 reviews...
Tool call completed: get_tripadvisor_location_details

Follow-up completed!

Cleaning up resources...
Agent deleted

TripAdvisor OpenAPI agent sample completed!

الأخطاء الشائعة

  • Error: OpenAPI specification not foundتحقق من مسار الملف.
  • لم يتم العثور على الاتصال: تحقق TRIPADVISOR_CONNECTION_ID من صحة الاتصال وأن الاتصال موجود.
  • AuthenticationException: مفتاح API غير صالح في اتصال المشروع.
  • مفتاح API غير محقن في الطلبات: يجب أن تتضمن مواصفات OpenAPI الخاصة بك (تحت securitySchemes) وأقسام components صحيحة security . يجب أن يتطابق اسم المفتاح في securitySchemes المفتاح في اتصال مشروعك.
  • Content type is not supported: حاليا، يتم دعم هذين النوعين فقط من محتوى جسم الطلبات: application/json و application/json-patch+json. أنواع محتوى الردود ليست مقيدة.

اعتبارات الأمان والبيانات

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

  • استخدم اتصالات المشاريع للأسرار (مفاتيح API والرموز). تجنب وضع الأسرار في ملف مواصفات OpenAPI أو كود المصدر.
  • راجع البيانات التي تستقبلها واجهة برمجة التطبيقات وما تعيده قبل استخدام الأداة في الإنتاج.
  • استخدم الوصول بأقل امتياز. بالنسبة للهوية المدارة، قم بتعيين الأدوار فقط التي تتطلبها الخدمة المستهدفة.

المصادقة باستخدام مفتاح API

باستخدام مصادقة مفاتيح API، يمكنك التحقق من مواصفات OpenAPI باستخدام طرق مختلفة مثل مفتاح API أو رمز Bearer. يمكنك استخدام مخطط أمان واحد فقط لمفتاح API حسب مواصفات OpenAPI. إذا كنت بحاجة إلى عدة مخططات أمنية، أنشئ عدة أدوات مواصفات OpenAPI.

  1. تحديث مخططات أمان مواصفات OpenAPI. له securitySchemes قسم ومخطط واحد من النوع apiKey. على سبيل المثال:

     "securitySchemes": {
         "apiKeyHeader": {
                 "type": "apiKey",
                 "name": "x-api-key",
                 "in": "header"
             }
     }
    

    عادة ما تحتاج فقط إلى تحديث name الحقل، الذي يتوافق مع اسم key في الاتصال. إذا كانت أنظمة الأمان تتضمن عدة مخططات، احتفظ بواحدة فقط منها.

  2. تحديث مواصفات OpenAPI لتضمين security قسم:

    "security": [
         {  
         "apiKeyHeader": []  
         }  
     ]
    
  3. قم بإزالة أي معلمة في مواصفات OpenAPI تحتاج إلى مفتاح API، لأن مفتاح API يخزن ويمرر عبر اتصال، كما هو موضح لاحقا في هذا المقال.

  4. أنشئ اتصالا لتخزين مفتاح واجهة برمجة التطبيقات الخاصة بك.

  5. اذهب إلى بوابة Foundry وافتح مشروعك.

  6. أنشئ أو اختر اتصالا يخزن السر. انظر أضف اتصالا جديدا لمشروعك.

    ‏‫ملاحظة‬

    إذا قمت بإعادة إنشاء مفتاح API في وقت لاحق، فستحتاج إلى تحديث الاتصال بالمفتاح الجديد.

  7. أدخل المعلومات التالية

    • المفتاح: name حقل نظام الأمان الخاص بك. في هذا المثال، يجب أن يكون x-api-key

             "securitySchemes": {
                "apiKeyHeader": {
                          "type": "apiKey",
                          "name": "x-api-key",
                          "in": "header"
                      }
              }
      
    • القيمة: YOUR_API_KEY

  8. بعد إنشاء الاتصال، يمكنك استخدامه عبر واجهة برمجة تطبيقات SDK أو REST. استخدم علامات التبويب في أعلى هذه المقالة للاطلاع على أمثلة التعليمات البرمجية.

قم بإعداد اتصال رمز حامل

يمكنك استخدام المصادقة المعتمدة على الرموز (مثل رمز الحامل) بنفس project_connection نوع المصادقة المستخدم لمفاتيح API. الفرق الرئيسي هو كيفية تكوين كل من مواصفات OpenAPI واتصال المشروع.

مواصفتك في OpenAPI ستكون كالتالي:

  BearerAuth:
    type: http
    scheme: bearer
    bearerFormat: JWT

تحتاج إلى:

  1. قم بتحديث مواصفات securitySchemes OpenAPI لاستخدامها Authorization كاسم الرأس:

    "securitySchemes": {
        "bearerAuth": {
            "type": "apiKey",
            "name": "Authorization",
            "in": "header"
        }
    }
    
  2. أضف قسما security يشير إلى المخطط:

    "security": [
        {
            "bearerAuth": []
        }
    ]
    
  3. أنشئ اتصال مفاتيح مخصص في مشروع Foundry الخاص بك:

    1. اذهب إلى بوابة Foundry وافتح مشروعك.
    2. أنشئ أو اختر اتصالا يخزن السر. انظر أضف اتصالا جديدا لمشروعك.
    3. أدخل القيم التالية:
      • المفتاح: Authorization (يجب أن يطابق الحقل name في )securitySchemes
      • القيمة: Bearer <token> (استبدلها <token> برمزك الفعلي)

    مهم

    يجب أن تتضمن القيمة الكلمة Bearer متبوعة بمسافة قبل الرمز. على سبيل المثال: Bearer eyJhbGciOiJSUzI1NiIs.... إذا حذفت ، Bearer تتلقى واجهة برمجة التطبيقات رمزا خام بدون بادئة نظام التفويض المطلوبة، ويفشل الطلب.

  4. بعد إنشاء الاتصال، استخدمه مع نوع المصادقة project_connection في كودك، بنفس الطريقة التي تفعل بها مع مصادقة مفاتيح API. يستخدم معرف الاتصال نفس التنسيق: /subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}}.

تحقق من الهوية باستخدام الهوية المدارة (Microsoft Entra ID)

Microsoft Entra ID هي خدمة إدارة هوية ووصول قائمة على السحابة يمكن لموظفيك استخدامها للوصول إلى الموارد الخارجية. باستخدام Microsoft Entra ID، يمكنك إضافة أمان إضافي إلى واجهات برمجة التطبيقات دون الحاجة لاستخدام مفاتيح API. عند إعداد مصادقة الهوية المدارة، يقوم الوكيل بالمصادقة من خلال أداة Foundry التي يستخدمها.

مهم

تعمل المصادقة المدارة للهوية فقط عندما تقبل الخدمة المستهدفة رموز Microsoft Entra ID. إذا كانت واجهة برمجة التطبيقات المستهدفة تستخدم نظام مصادقة مخصص لا يدعم Microsoft Entra ID، فاستخدم مفتاح API أو مصادقة رمز Bearer بدلا من ذلك.

فهم الجمهور في URI

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

‏‫ملاحظة‬

الجمهور ليس نقطة نهاية مشروع Foundry الخاص بك. إنه معرف الموارد للخدمة المستهدفة التي تستدعيها أداة OpenAPI الخاصة بك.

الجدول التالي يسرد URIs الجمهور لخدمات Azure الشائعة:

خدمة الهدف URI الجمهور
تخزين Azure https://storage.azure.com
Azure Key Vault https://vault.azure.net
Azure AI Search https://search.azure.com
تطبيقات Azure Logic https://logic.azure.com
Azure API Management (management plane) https://management.azure.com
واجهة برمجة التطبيقات المحمية بتسجيل تطبيق Microsoft Entra (بما في ذلك APIM مع OAuth) معرف التطبيق URI من تسجيل طلبك (على سبيل المثال، api://<client-id>)

نصيحة

إذا استخدمت Azure API Management لحماية واجهة برمجة تطبيقات مخصصة بسياسة تحقق OAuth 2.0، فالجمهور هو معرف التطبيق URI من تسجيل التطبيق الذي يحمي الواجهة — وليس https://management.azure.com. جمهور مستوى الإدارة ينطبق فقط على عمليات Azure Resource Manager على مورد APIM نفسه.

لمزيد من المعلومات حول كيفية المصادقة الوكلاء باستخدام Microsoft Entra ID، راجع هوية الوكيل والمصادقة.

ابحث عن جمهورك وتحقق من وجوده

استخدم الخطوات التالية لتحديد والتحقق من القيمة الصحيحة للجمهور:

  • بالنسبة لخدمات Azure: تحقق من وثائق الخدمة لمعرفة معرف موارد Microsoft Entra ID. معظم خدمات Azure تدرج URI الجمهور في وثائق المصادقة الخاصة بها.
  • بالنسبة لواجهات برمجة التطبيقات المحمية بتسجيل تطبيق Microsoft Entra: في بوابة Azure، اذهب إلى تسجيلات تطبيق Microsoft Entra ID>واختر> تطبيقك >كشف واجهة برمجة تطبيقات (API). معرف التطبيق URI في أعلى الصفحة هو قيمة جمهورك.
  • للتحقق من جمهور الرمز: فك شفرة رمز الوصول على وتحقق https://jwt.ms من الادعاء aud . يجب أن تتناسب القيمة aud مع الجمهور الذي تتوقعه خدمتك المستهدفة.

إعداد مصادقة هوية مدارة

لإعداد المصادقة باستخدام الهوية المدارة:

  1. تأكد من أن مورد Foundry الخاص بك مفعل لهوية مدارة مخصصة للنظام.

    لقطة شاشة تظهر محدد الهوية المدارة في بوابة Azure.

  2. أنشئ موردا للخدمة التي تريد الاتصال بها عبر مواصفات OpenAPI.

  3. تعيين الوصول المناسب إلى المورد.

    1. اختر Access Control لمصدرك.

    2. اختر إضافة ثم أضف تعيين الأدوار في أعلى الشاشة.

      لقطة شاشة تظهر محدد تعيين الأدوار في بوابة Azure.

    3. اختر التعيين المناسب للدور المطلوب، وعادة يتطلب على الأقل دور القارئ . ثم حدد التالي.

    4. اختر الهوية المدارة ثم اختر اختيار الأعضاء.

    5. في قائمة الهوية المدارة، ابحث عن حساب Foundry ثم اختر حساب Foundry الخاص بوكيلك.

    6. حدد إنهاء.

  4. عند الانتهاء من الإعداد، يمكنك الاستمرار باستخدام الأداة عبر بوابة Foundry أو SDK أو واجهة برمجة تطبيقات REST. استخدم علامات التبويب في أعلى هذه المقالة لمشاهدة نماذج التعليمات البرمجية.

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

العرض السبب المحتمل الحل
مفتاح API غير مدرج في الطلبات. مواصفات OpenAPI مفقودة securitySchemes أو security أقسام. تحقق من أن مواصفات OpenAPI الخاصة بك تتضمن كلاهما components.securitySchemes وقسم أعلى مستوى security . تأكد من تطابق النظام name مع اسم المفتاح في مشروعك.
الوكيل لا يستدعي أداة OpenAPI. اختيار الأداة غير محدد أو operationId غير وصفي. استخدامه tool_choice="required" لإجبار استدعاء الأدوات. تأكد من operationId أن القيم وصفية حتى يتمكن النموذج من اختيار العملية الصحيحة.
تفشل المصادقة في تحديد الهوية المدارة. الهوية المدارة غير مفعلة أو فقدان تعيين الأدوار. فعل هوية مدارة معينة من النظام على مورد Foundry الخاص بك. تعيين الدور المطلوب (قارئ أو أعلى) على الخدمة المستهدفة.
الهوية المدارة تعيد 401 حتى لو تم تعيين الدور. رابط الجمهور لا يتطابق مع توقعات الخدمة المستهدفة. تحقق من تطابق URI للجمهور مع معرف الموارد الخاص بالخدمة المستهدفة. بالنسبة لخدمات Azure، تحقق من وثائق الخدمة. بالنسبة لواجهات برمجة التطبيقات المحمية ب Microsoft Entra، استخدم معرف التطبيق URI من تسجيل التطبيق. فك تشفير الرمز عند https://jwt.ms وتأكد من تطابق المطالبات aud . انظر فهم الجمهور في URI.
تم رفض رمز الهوية المدارة من قبل واجهة برمجة التطبيقات المستهدفة. خدمة Target لا تقبل رموز Microsoft Entra ID. تأكد من أن الخدمة المستهدفة تدعم مصادقة Microsoft Entra ID. إذا لم يكن كذلك، استخدم مفتاح API أو مصادقة رموز Bearer بدلا من ذلك.
فشل الطلب مع 400 طلب سيء. مواصفات OpenAPI لا تتطابق مع واجهة برمجة التطبيقات الفعلية. تحقق من مواصفات OpenAPI الخاصة بك مقابل واجهة البرمجة الفعلية. تحقق من أسماء المعلمات، وأنواعها، والحقول المطلوبة.
الطلب يفشل مع 401 غير مصرح به. مفتاح أو رمز API غير صالح أو منتهية الصلاحية. أعد توليد مفتاح الواجهة (API/Token) وحدث اتصال مشروعك. تحقق من صحة معرف الاتصال.
الأداة تعيد صيغة الاستجابة غير المتوقعة. مخطط الاستجابة غير معرف في مواصفات OpenAPI. أضف مخططات الاستجابة إلى مواصفات OpenAPI لفهم النموذج بشكل أفضل.
operationId خطأ في التحقق. الأحرف غير الصالحة في operationId. استخدم فقط الحروف، -، والقيم _ بالقيم operationId . أزل الأرقام والأحرف الخاصة.
لم يتم العثور على الاتصال، خطأ. اسم الاتصال أو المعرف غير مطابق. التحقق OPENAPI_PROJECT_CONNECTION_NAME من أن Verify يتطابق مع اسم الاتصال في مشروع Foundry الخاص بك.
رمز الحامل لم يرسل بشكل صحيح. قيمة الاتصال مفقودة Bearer في بادئة. اضبط قيمة الاتصال إلى Bearer <token> (مع الكلمة Bearer ومسافة قبل الرمز). تحقق من أن مواصفات securitySchemes OpenAPI تستخدم "name": "Authorization".

اختر طريقة مصادقة

يساعدك الجدول التالي في اختيار طريقة المصادقة المناسبة لأداة OpenAPI الخاصة بك:

أسلوب المصادقة الأفضل ل تعقيد الإعداد
مجهول واجهات برمجة التطبيقات العامة بدون مصادقة منخفضه
API key واجهات برمجة التطبيقات غير التابعة لمايكروسوفت مع وصول قائم على المفاتيح المتوسطه
الهوية المُدارة Azure services وواجهات برمجة التطبيقات المحمية ب Microsoft Entra ID. يتطلب من الخدمة المستهدفة قبول رموز Microsoft Entra ID ودعم Azure RBAC أو التحكم في الوصول القائم على Microsoft Entra. Medium-High