مكتبة عملاء Azure AI Projects لجافا سكريبت - الإصدار 2.4.0

مكتبة عملاء AI Projects (في المعاينة) هي جزء من حزمة تطوير البرمجيات Microsoft Foundry، وتوفر وصولا سهلا إلى الموارد في Microsoft Foundry Project الخاص بك. استخدمها في:

  • قم بإنشاء وتشغيل Agents باستخدام الخاصية .agents على العميل.
  • تعزيز العملاء بأدوات متخصصة:
    • البحث عن ذاكرة الوكيل (معاينة)
    • وكيل إلى وكيل (A2A) (معاينة)
    • البحث باستخدام الذكاء الاصطناعي في Azure
    • البحث المخصص في بينج (معاينة)
    • تأريض Bing
    • أتمتة المتصفح (معاينة)
    • مترجم شفرة
    • استخدام الحاسوب (معاينة)
    • البحث عن الملفات
    • أداة الوظيفة
    • إنشاء الصور
    • Microsoft Fabric (معاينة)
    • بروتوكول سياق النموذج (MCP)
    • OpenAPI
    • Microsoft SharePoint (معاينة)
    • البحث على الويب (معاينة)
    • البحث عن الأدوات
  • احصل على عميل OpenAI يستخدم هذه .getOpenAIClient. الطريقة لتشغيل عمليات الردود، والمحادثات، والتقييمات، والضبط الدقيق مع وكيلك.
  • إدارة جلسات وملفات وكلاء التجريبيين (المعاينة) باستخدام العمليات .beta.agents .
  • إدارة المهارات (المعاينة) لقدرات الوكلاء القابلة لإعادة الاستخدام، باستخدام العمليات .beta.skills .
  • إدارة صناديق الأدوات لتجميع الأدوات في مجموعات قابلة لإعادة الاستخدام، باستخدام العمليات .toolboxes .
  • إدارة مخازن الذاكرة (المعاينة) لمحادثات الوكلاء، باستخدام العمليات .beta.memoryStores .
  • إدارة الروتينات (المعاينة) لجدولة وتوزيع سير العمل الآلي، باستخدام العمليات .beta.routines .
  • إدارة إصدارات النماذج (المعاينة) لإنشاء وتحديث وإدارة إصدارات النماذج المخصصة، باستخدام العمليات .beta.models .
  • استكشف أدوات تقييم إضافية (بعضها في المعاينة) لتقييم أداء تطبيق الذكاء الاصطناعي التوليدي الخاص بك، باستخدام العمليات .evaluationRules، .beta.evaluationTaxonomies، ، .beta.evaluators.beta.insights، و .beta.schedules .
  • شغل مسوحات Red Team (معاينة) لتحديد المخاطر المرتبطة بتطبيق الذكاء الاصطناعي التوليدي الخاص بك، باستخدام العمليات .beta.redTeams .
  • تهذيب نماذج الذكاء الاصطناعي على بياناتك.
  • Enumerate AI Models يتم نشرها في مسبك Project باستخدام عمليات .deployments.
  • تعداد الموارد Azure المتصلة في مشروع Foundry الخاص بك باستخدام عمليات .connections.
  • قم بتحميل المستندات وإنشاء مجموعات البيانات للرجوع إليها باستخدام .datasets العمليات.
  • قم بإنشاء فهارس البحث وتعدادها باستخدام العمليات .indexes .

تستخدم مكتبة العميل النسخة من Microsoft Foundry <واجهات برمجة تطبيقات REST على مستوى البيانات c1>data.

وثائق المنتج | Samples | Package (npm) | API المرجع المستندي | SDK مصدر كود

جدول المحتويات

الشروع في العمل

المتطلب الأساسي

  • <نسخ c0>LTS من Node.js
  • اشتراك Azure.
  • مشروع في Microsoft Foundry.
  • رابط نقطة نهاية المشروع من النموذج https://your-ai-services-account-name.services.ai.azure.com/api/projects/your-project-name. يمكنك العثور عليه في صفحة نظرة عامة على Microsoft Foundry Project الخاص بك. فيما يلي سنفترض أن متغير FOUNDRY_PROJECT_ENDPOINT البيئة تم تعريفه ليحمل هذه القيمة.

التفويض

  • يتطلب الأمر معرف Entra ID لمصادقة العميل. يحتاج التطبيق الخاص بك إلى كائن ينفذ واجهة TokenCredential. نماذج الشيفرة هنا تستخدم DefaultAzureCredential. للحصول على هذا العمل، ستحتاج إلى:
    • تعيين دور مناسب. انظر التحكم في الوصول القائم على الأدوار في بوابة Microsoft Foundry. يمكن تعيين الدور عبر علامة تبويب "Access Control (IAM)" في مورد Azure AI Project الخاص بك في بوابة Azure.
    • Azure CLI مثبت.
    • أنت مسجل الدخول إلى حسابك Azure عبر تشغيل az login.
    • لاحظ أنه إذا كان لديك عدة اشتراكات في Azure، يجب أن يكون الاشتراك الذي يحتوي على مورد Azure AI Project هو اشتراكك الافتراضي. قم بتشغيل az account list --output table لسرد جميع اشتراكاتك ومعرفة الاشتراك الافتراضي. قم بتشغيل az account set --subscription "Your Subscription ID or Name" لتغيير اشتراكك الافتراضي.

تثبيت الحزمة

npm install @azure/ai-projects dotenv

المفاهيم الرئيسية

إنشاء ومصادقة العميل باستخدام Entra ID

Entra ID هو الطريقة الوحيدة للمصادقة التي يدعمها العميل في الوقت الحالي.

لإنشاء AIProjectsClient، يمكن جلب ملف projectEndpoint من projectEndpoint. أدناه سوف نفترض أن متغير FOUNDRY_PROJECT_ENDPOINT البيئة قد تم تعريفه للاحتفاظ بهذه القيمة:

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

const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint string>";
project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential());

مجموعات عمليات المعاينة وأعلام الميزات الاختيارية

بعض عمليات المعاينة foundryFeatures تتطلب وجود علامة اشتراك صريحة. على سبيل المثال:

await project.agents.createVersion(
  "preview-agent",
  {
    kind: "workflow",
  },
  { foundryFeatures: "WorkflowAgents=V1Preview" },
);
for await (const rule of project.evaluationRules.list()) {
  console.log(rule.id);
}

تشمل .beta.agentsمجموعات عمليات المعاينة ، .beta.skills، .beta.memoryStores، .beta.routines، .beta.models، .beta.evaluationTaxonomies.beta.schedules.beta.evaluators.beta.insightsو ..beta.redTeams

الأمثلة

تنفيذ عمليات الاستجابات باستخدام عميل OpenAI

قد يحتوي مشروع Microsoft Foundry الخاص بك على نموذج أو أكثر من نماذج الذكاء الاصطناعي المنشورة. قد تكون هذه نماذج OpenAI، أو نماذج Microsoft، أو نماذج من مزودين آخرين. استخدم الكود أدناه للحصول على OpenAI مصادق عليه من حزمة openai ، وقم بتنفيذ مكالمة إكمال الدردشة.

قم بتشغيل الكود أدناه. هنا نفترض deploymentName أن (str) محدد. إنه اسم نشر نموذج ذكاء اصطناعي في Project Foundry الخاص بك. كما هو موضح في علامة التبويب "النماذج + نقاط النهاية"، ضمن عمود "الاسم".

راجع مجلد "الإجابات" في <عينات c0>package للحصول على عينات إضافية، بما في ذلك الردود المتدفقة.

const openAIClient = project.getOpenAIClient();
const response = await openAIClient.responses.create({
  model: deploymentName,
  input: "What is the size of France in square miles?",
});
console.log("response = ", JSON.stringify(response, null, 2));
const detailResponse = await openAIClient.responses.create({
  model: deploymentName,
  input: "And what is the capital city?",
  previous_response_id: response.id,
});
console.log("detailed response = ", JSON.stringify(detailResponse, null, 2));

تنفيذ عمليات الوكيل

.agents تمنحك الخاصية الموجودة على ملف AIProjectsClient الوصول إلى جميع عمليات الوكيل. يستخدم الوكلاء امتدادا لبروتوكول OpenAI Responses، لذلك ستحتاج على الأرجح إلى الحصول على OpenAI عميل للقيام بعمليات الوكيل، كما هو موضح في المثال أدناه.

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("my-agent-basic", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that answers general questions",
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
const conversation = await openAIClient.conversations.create({
  items: [
    { type: "message", role: "user", content: "What is the size of France in square miles?" },
  ],
});
console.log(`Created conversation with initial user message (id: ${conversation.id})`);
// Generate response using the agent
console.log("\nGenerating response...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response output: ${response.output_text}`);
// Add a second user message to the conversation
console.log("\nAdding a second user message to the conversation...");
await openAIClient.conversations.items.create(conversation.id, {
  items: [{ type: "message", role: "user", content: "And what is the capital city?" }],
});
console.log("Added a second user message to the conversation");
// Generate second response
console.log("\nGenerating second response...");
const response2 = await openAIClient.responses.create(
  {
    conversation: conversation.id,
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response output: ${response2.output_text}`);
// Clean up
console.log("\nCleaning up resources...");
await openAIClient.conversations.delete(conversation.id);
console.log("Conversation deleted");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");

استخدام أدوات الوكيل

يمكن تعزيز الوكلاء بأدوات متخصصة لقدرات متنوعة. يتم تنظيم الأدوات حسب متطلبات الاتصال الخاصة بها:

الأدوات المدمجة

تعمل هذه الأدوات فورا دون الحاجة إلى اتصالات خارجية.

مترجم شفرة

اكتب وشغل كود جافاسكريبت في بيئة مفتوحة، وأعالج الملفات وعمل مع تنسيقات بيانات متنوعة. توثيق OpenAI

const openAIClient = project.getOpenAIClient();
const response = await openAIClient.responses.create({
  model: deploymentName,
  input: "I need to solve the equation 3x + 11 = 14. Can you help me?",
  tools: [{ type: "code_interpreter", container: { type: "auto" } }],
});
console.log(`Response output: ${response.output_text}`);

انظر الكود النموذجي الكامل في agentCodeInterpreter.ts.

البحث عن الملفات

أداة RAG مدمجة (Retrieval-Augmented Generation) لمعالجة والبحث في المستندات باستخدام مخازن متجهة لاسترجاع المعرفة. توثيق OpenAI

const openAIClient = project.getOpenAIClient();
const assetFilePath = path.join(
  __dirname,
  "..",
  "samples-dev",
  "agents",
  "assets",
  "product_info.txt",
);
const vectorStore = await openAIClient.vectorStores.create({
  name: "ProductInfoStreamStore",
});
console.log(`Vector store created (id: ${vectorStore.id})`);
// Upload file to vector store
const fileStream = fs.createReadStream(assetFilePath);
const uploadedFile = await openAIClient.vectorStores.files.uploadAndPoll(
  vectorStore.id,
  fileStream,
);
console.log(`File uploaded to vector store (id: ${uploadedFile.id})`);
// Create agent with file search tool
const agent = await project.agents.createVersion("StreamingFileSearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that can search through product information and provide detailed responses. Use the file search tool to find relevant information before answering.",
  tools: [
    {
      type: "file_search",
      vector_store_ids: [vectorStore.id],
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentFileSearchStream.ts.

توليد الصور

قم بإنشاء صور بناء على تعليمات نصية مع إعدادات دقة وجودة ونمط قابلة للتخصيص حسب الطلب:

const agent = await project.agents.createVersion("agent-image-generation", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Generate images based on user prompts",
  tools: [
    {
      type: "image_generation",
      quality: "low",
      size: "1024x1024",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

بعد الاتصال responses.create()، يمكنك تحميل الملف باستخدام الرد الوارد:

import { fileURLToPath } from "url";

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("agent-image-generation", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Generate images based on user prompts",
  tools: [
    {
      type: "image_generation",
      quality: "low",
      size: "1024x1024",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
const response = await openAIClient.responses.create(
  {
    input: "Generate an image of Microsoft logo.",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response created: ${response.id}`);
const imageData = response.output?.filter((output) => output.type === "image_generation_call");
if (imageData && imageData.length > 0 && imageData[0].result) {
  console.log("Downloading generated image...");
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);
  const filename = "microsoft.png";
  const filePath = path.join(__dirname, filename);
  // Decode base64 and save to file
  const imageBuffer = Buffer.from(imageData[0].result, "base64");
  fs.writeFileSync(filePath, imageBuffer);
  console.log(`Image downloaded and saved to: ${path.resolve(filePath)}`);
} else {
  console.log("No image data found in the response.");
}

البحث على الويب (معاينة)

قم بإجراء عمليات بحث عامة على الإنترنت لاسترجاع المعلومات الحالية من الإنترنت. توثيق OpenAI

const openAIClient = project.getOpenAIClient();
// Create Agent with web search tool
const agent = await project.agents.createVersion("agent-web-search", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that can search the web",
  tools: [
    {
      type: "web_search_preview",
      user_location: {
        type: "approximate",
        country: "GB",
        city: "London",
        region: "London",
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation for the agent interaction
const conversation = await openAIClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send a query to search the web
console.log("\nSending web search query...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
    input: "Show me the latest London Underground service updates",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response: ${response.output_text}`);

انظر الكود النموذجي الكامل في agentWebSearch.ts.

استخدام الحاسوب (معاينة)

تمكين الوكلاء من التفاعل المباشر مع أنظمة الحاسوب لأتمتة المهام وعمليات النظام:

const agent = await project.agents.createVersion("ComputerUseAgent", {
  kind: "prompt" as const,
  model: deploymentName,
  instructions: `
You are a computer automation assistant.

Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.
    `.trim(),
  tools: [
    {
      type: "computer_use_preview",
      display_width: 1026,
      display_height: 769,
      environment: "windows" as const,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

بعد الاستدعاء responses.create()، يعالج الاستجابة في حلقة تفاعل. تعامل computer_call مع العناصر المخرجة وقدم لقطات شاشة حسب computer_call_outputcomputer_screenshot الشكل لمواصلة التفاعل.

راجع الكود النموذجي الكامل في agentComputerUse.ts.

بروتوكول سياق النموذج (MCP)

دمج خوادم MCP لتوسيع قدرات الوكلاء باستخدام أدوات وموارد موحدة. توثيق OpenAI

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("agent-mcp", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
  tools: [
    {
      type: "mcp",
      server_label: "api-specs",
      server_url: "https://gitmcp.io/Azure/azure-rest-api-specs",
      require_approval: "always",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation thread to maintain context across multiple interactions
console.log("\nCreating conversation...");
const conversation = await openAIClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send initial request that will trigger the MCP tool to access Azure REST API specs
// This will generate an approval request since requireApproval="always"
console.log("\nSending request that will trigger MCP approval...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
    input: "Please summarize the Azure REST API specifications Readme",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);

بعد الاتصال responses.create()، تحقق من العناصر mcp_approval_request في مخرج الرد. أعد McpApprovalResponse مع قرارك الموافق للسماح للوكيل بمواصلة عمله.

انظر الكود النموذجي الكامل في agentMcp.ts.

OpenAPI

استدعاء واجهات برمجة التطبيقات الخارجية المعرفة بمواصفات OpenAPI دون الحاجة إلى كود إضافي على جانب العميل. توثيق OpenAI

const weatherSpecPath = path.resolve(__dirname, "../assets", "weather_openapi.json");
const agent = await project.agents.createVersion("MyOpenApiAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that can call external APIs defined by OpenAPI specs to answer user questions. When calling the weather tool, always include the query parameter format=j1.",
  tools: [
    {
      type: "openapi",
      openapi: {
        name: "get_weather",
        description: "Retrieve weather information for a location using wttr.in",
        spec: weatherSpecPath,
        auth: { type: "anonymous" },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentOpenApi.ts.

أداة الوظيفة

تعريف وظائف مخصصة تسمح للوكلاء بالتفاعل مع واجهات برمجة التطبيقات الخارجية، قواعد البيانات، أو منطق التطبيقات. توثيق OpenAI

/**
 * Define a function tool for the model to use
 */
const funcTool = {
  type: "function" as const,
  function: {
    name: "get_horoscope",
    description: "Get today's horoscope for an astrological sign.",
    strict: true,
    parameters: {
      type: "object",
      properties: {
        sign: {
          type: "string",
          description: "An astrological sign like Taurus or Aquarius",
        },
      },
      required: ["sign"],
      additional_properties: false,
    },
  },
};
const agent = await project.agents.createVersion("function-tool-agent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that can use function tools.",
  tools: [funcTool],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

بعد استدعاء responses.create()، قم بمعالجة function_call العناصر من مخرجات الاستجابة، ونفذ منطق الدالة باستخدام الوسيطات المقدمة، وأرسل FunctionCallOutput النتائج.

انظر الكود النموذجي الكامل في agentFunctionTool.ts.

  • أداة البحث عن الذاكرة (المعاينة)

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

هذا embeddingModelDeployment هو اسم النموذج المستخدم لإنشاء تضمينات متجهية لتخزين والبحث في الذكريات.

const memoryStoreName = "AgentMemoryStore";
const embeddingModelDeployment =
  process.env["MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME"] || "<embedding model>";
const scope = "user_123";
const memoryStore = await project.beta.memoryStores.create(
  memoryStoreName,
  {
    kind: "default",
    chat_model: deploymentName,
    embedding_model: embeddingModelDeployment,
    options: {
      user_profile_enabled: true,
      chat_summary_enabled: true,
    },
  },
  {
    description: "Memory store for agent conversations",
  },
);
console.log(
  `Created memory store: ${memoryStore.name} (${memoryStore.id}) using chat model '${deploymentName}'`,
);
// Create an agent that will use the Memory Search tool
const agent = await project.agents.createVersion("MemorySearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that remembers user preferences using the memory search tool.",
  tools: [
    {
      type: "memory_search_preview",
      memory_store_name: memoryStore.name,
      scope,
      update_delay: 1, // wait briefly after conversation inactivity before updating memories
    },
  ],
});

انظر الكود النموذجي الكامل في agentMemorySearch.ts.

أدواتConnection-Based

تتطلب هذه الأدوات تكوين الاتصالات في مشروع الذكاء الاصطناعي Foundry الخاص بك وتستخدمه projectConnectionId.

Azure بحث الذكاء الاصطناعي

التكامل مع فهارس البحث باستخدام الذكاء الاصطناعي في Azure لقدرات قوية لاسترجاع المعرفة والبحث الدلالي:

const aiSearchConnectionId = process.env["AI_SEARCH_CONNECTION_ID"] || "";
const aiSearchIndexName = process.env["AI_SEARCH_INDEX_NAME"] || "";
const agent = await project.agents.createVersion("MyAISearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant. You must always provide citations for answers using the tool and render them as: `[message_idx:search_idx†source]`.",
  tools: [
    {
      type: "azure_ai_search",
      azure_ai_search: {
        indexes: [
          {
            project_connection_id: aiSearchConnectionId,
            index_name: aiSearchIndexName,
            query_type: "simple",
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentAiSearch.ts.

التأريض في بينج

ردود الوكلاء الأرضية مع نتائج بحث ويب فورية من Bing لتوفير معلومات up-toبتاريخ التاريخ:

const bingProjectConnectionId = process.env["BING_GROUNDING_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyBingGroundingAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  tools: [
    {
      type: "bing_grounding",
      bing_grounding: {
        search_configurations: [
          {
            project_connection_id: bingProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentBingGrounding.ts.

البحث المخصص في بينج (معاينة)

استخدم مثيلات بحث Bing المهيأة خصيصا لنتائج البحث الخاصة بالمجال أو المفلترة:

const bingCustomSearchProjectConnectionId = process.env["BING_CUSTOM_SEARCH_CONNECTION_ID"] || "";
const bingCustomSearchInstanceName = process.env["BING_CUSTOM_SEARCH_INSTANCE_NAME"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use Bing Custom Search tools to assist users. Use the available Bing Custom Search tools to answer questions and perform tasks.",
  tools: [
    {
      type: "bing_custom_search_preview",
      bing_custom_search_preview: {
        search_configurations: [
          {
            project_connection_id: bingCustomSearchProjectConnectionId,
            instance_name: bingCustomSearchInstanceName,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentBingCustomSearch.ts.

Microsoft Fabric (معاينة)

اتصل واستعلام Microsoft Fabric:

const fabricProjectConnectionId = process.env["FABRIC_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyFabricAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  tools: [
    {
      type: "fabric_dataagent_preview",
      fabric_dataagent_preview: {
        project_connections: [
          {
            project_connection_id: fabricProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentFabric.ts.

Microsoft SharePoint (معاينة)

الوصول والبحث في مستندات SharePoint والقوائم والمواقع لدمج المعرفة المؤسسية:

const sharepointProjectConnectionId = process.env["SHAREPOINT_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use SharePoint tools to assist users. Use the available SharePoint tools to answer questions and perform tasks.",
  // Define SharePoint tool that searches SharePoint content
  tools: [
    {
      type: "sharepoint_grounding_preview",
      sharepoint_grounding_preview: {
        project_connections: [
          {
            project_connection_id: sharepointProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentSharepoint.ts.

أتمتة المتصفح (معاينة)

أتمتة تفاعلات المتصفح لجمع البيانات من الويب، والاختبار، والتفاعل مع تطبيقات الويب:

const browserAutomationProjectConnectionId = process.env["BROWSER_AUTOMATION_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: `You are an Agent helping with browser automation tasks.
              You can answer questions, provide information, and assist with various tasks
              related to web browsing using the Browser Automation tool available to you.`,
  // Define Browser Automation tool
  tools: [
    {
      type: "browser_automation_preview",
      browser_automation_preview: {
        connection: {
          project_connection_id: browserAutomationProjectConnectionId,
        },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentBrowserAutomation.ts.

MCP مع اتصال Project

تكامل MCP باستخدام الاتصالات الخاصة بالمشروع للوصول إلى خوادم MCP المتصلة:

const mcpProjectConnectionId = process.env["MCP_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("agent-mcp-connection-auth", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Use MCP tools as needed",
  tools: [
    {
      type: "mcp",
      server_label: "api-specs",
      server_url: "https://api.githubcopilot.com/mcp",
      require_approval: "always",
      project_connection_id: mcpProjectConnectionId,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentMcpConnectionAuth.ts.

وكيل إلى وكيل (A2A) (معاينة)

تمكين التعاون متعدد الوكلاء حيث يمكن للوكلاء التواصل وتفويض المهام إلى وكلاء متخصصين آخرين:

const a2aProjectConnectionId = process.env["A2A_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyA2AAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  // Define A2A tool for agent-to-agent communication
  tools: [
    {
      type: "a2a_preview",
      project_connection_id: a2aProjectConnectionId,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentAgentToAgent.ts.

OpenAPI مع Project Connection

استدعاء واجهات برمجة التطبيقات الخارجية المعرفة بمواصفات OpenAPI باستخدام مصادقة اتصال المشروع:

const tripAdvisorProjectConnectionId = process.env["TRIPADVISOR_PROJECT_CONNECTION_ID"] || "";
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}`);
  }
}
const tripAdvisorSpecPath = path.resolve(__dirname, "../assets", "tripadvisor_openapi.json");
const tripAdvisorSpec = loadOpenApiSpec(tripAdvisorSpecPath);
const agent = await project.agents.createVersion("MyOpenApiConnectionAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a travel assistant that consults the TripAdvisor Content API via project connection to answer user questions about locations.",
  tools: [
    {
      type: "openapi",
      openapi: {
        name: "get_tripadvisor_location_details",
        description:
          "Fetch TripAdvisor location details, reviews, or photos using the Content API via project connection auth.",
        spec: tripAdvisorSpec,
        auth: {
          type: "project_connection",
          security_scheme: {
            project_connection_id: tripAdvisorProjectConnectionId,
          },
        },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

انظر الكود النموذجي الكامل في agentOpenApiConnectionAuth.ts.

للحصول على أمثلة كاملة لجميع الأدوات، راجع <دليل c0>samples-dev.

التقييم

يوفر التقييم في مكتبة عملاء Azure AI Project مقاييس كمية مدعومة بالذكاء الاصطناعي للجودة والسلامة لتقييم الأداء وتقييم نماذج نماذج اللغة الكبيرة وتطبيقات الذكاء الاصطناعي التوليد والوكلاء. تعرف المقاييس بأنها مقيمون. يمكن للمقيمين المدمجين أو المخصصين تقديم رؤى تقييم شاملة.

الكود أدناه يوضح بعض عمليات التقييم. يمكن العثور على القائمة الكاملة للعينات تحت مجلد "التقييمات" في <عينات الحزمة>

const openAIClient = project.getOpenAIClient();
const dataSourceConfig = {
  type: "custom" as const,
  item_schema: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"],
  },
  include_sample_schema: true,
};
const evalObject = await openAIClient.evals.create({
  name: "Agent Evaluation",
  data_source_config: dataSourceConfig,
  testing_criteria: [
    {
      type: "azure_ai_evaluator",
      name: "violence_detection",
      evaluator_name: "builtin.violence",
      data_mapping: { query: "{{item.query}}", response: "{{item.response}}" },
    } as any,
  ],
});
console.log(`Evaluation created (id: ${evalObject.id}, name: ${evalObject.name})`);

انظر الكود النموذجي الكامل في agentEvaluation.ts.

عمليات النشر

الكود أدناه يوضح بعض عمليات النشر، التي تتيح لك تعداد نماذج الذكاء الاصطناعي المنتشرة في مشاريع Microsoft Foundry الخاصة بك. يمكن رؤية هذه النماذج في تبويب "النماذج + نقاط النهاية" في Microsoft Foundry Project الخاص بك. يمكن العثور على العينات الكاملة تحت مجلد "النشر" في <عينات الحزمة c0>.

import { ModelDeployment } from "@azure/ai-projects";

const modelPublisher = process.env["MODEL_PUBLISHER"] || "<model publisher>";
console.log("List all deployments:");
const deployments: ModelDeployment[] = [];
const properties: Array<Record<string, string>> = [];

for await (const deployment of project.deployments.list()) {
  // Check if this is a ModelDeployment (has the required properties)
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    deployments.push(deployment);
    properties.push({
      name: deployment.name,
      modelPublisher: deployment.modelPublisher,
      modelName: deployment.modelName,
    });
  }
}
console.log(`Retrieved deployments: ${JSON.stringify(properties, null, 2)}`);

// List all deployments by a specific model publisher (assuming we have one from the list)
console.log(`List all deployments by the model publisher '${modelPublisher}':`);
const filteredDeployments: ModelDeployment[] = [];
for await (const deployment of project.deployments.list({
  modelPublisher,
})) {
  // Check if this is a ModelDeployment
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    filteredDeployments.push(deployment);
  }
}
console.log(
  `Retrieved ${filteredDeployments.length} deployments from model publisher '${modelPublisher}'`,
);

// Get a single deployment by name
if (deployments.length > 0) {
  const deploymentName = deployments[0].name;
  console.log(`Get a single deployment named '${deploymentName}':`);
  const singleDeployment = await project.deployments.get(deploymentName);
  console.log(`Retrieved deployment: ${JSON.stringify(singleDeployment, null, 2)}`);
}

عمليات التوصيلات

الكود أدناه يوضح بعض عمليات الاتصال، التي تتيح لك تعداد موارد Azure المتصلة بمشاريع Microsoft Foundry الخاصة بك. يمكن رؤية هذه الاتصالات في "مركز الإدارة"، وفي تبويب "الموارد المتصلة" في Microsoft Foundry Project الخاص بك. يمكن العثور على العينات الكاملة تحت مجلد "الاتصالات" في <عينات العبوة c0>package.

import { Connection } from "@azure/ai-projects";

// List the details of all the connections
const connections: Connection[] = [];
const connectionNames: string[] = [];
for await (const connection of project.connections.list()) {
  connections.push(connection);
  connectionNames.push(connection.name);
}
console.log(`Retrieved connections: ${connectionNames}`);

// Get the details of a connection, without credentials
const connectionName = connections[0].name;
const connection = await project.connections.get(connectionName);
console.log(`Retrieved connection ${JSON.stringify(connection, null, 2)}`);

const connectionWithCredentials = await project.connections.getWithCredentials(connectionName);
console.log(
  `Retrieved connection with credentials ${JSON.stringify(connectionWithCredentials, null, 2)}`,
);

// List all connections of a specific type
const azureAIConnections: Connection[] = [];
for await (const azureOpenAIConnection of project.connections.list({
  connectionType: "AzureOpenAI",
  defaultConnection: true,
})) {
  azureAIConnections.push(azureOpenAIConnection);
}
console.log(`Retrieved ${azureAIConnections.length} Azure OpenAI connections`);

// Get the details of a default connection
const defaultConnection = await project.connections.getDefault("AzureOpenAI", {
  includeCredentials: true,
});
console.log(`Retrieved default connection ${JSON.stringify(defaultConnection, null, 2)}`);

عمليات مجموعة البيانات

توضح التعليمات البرمجية أدناه بعض عمليات مجموعة البيانات. يمكن العثور على العينات الكاملة تحت مجلد "مجموعات البيانات" في <عينات الحزمة>.

import { DatasetVersionUnion } from "@azure/ai-projects";

const VERSION1 = "1.0";
const VERSION2 = "2.0";
const VERSION3 = "3.0";

// sample files to use in the demonstration
const sampleFolder = "sample_folder";
// Create a unique dataset name for this sample run
const datasetName = `sample-dataset-basic`;
console.log("Upload a single file and create a new Dataset to reference the file.");
console.log("Here we explicitly specify the dataset version.");

const dataset1 = await project.datasets.uploadFile(
  datasetName,
  VERSION1,
  path.join(__dirname, sampleFolder, "sample_file1.txt"),
);
console.log("Dataset1 created:", JSON.stringify(dataset1, null, 2));

const credential = project.datasets.getCredentials(dataset1.name, dataset1.version, {});
console.log("Credential for the dataset:", credential);
console.log(
  "Upload all files in a folder (including subfolders) to the existing Dataset to reference the folder.",
);
console.log("Here again we explicitly specify a new dataset version");
const dataset2 = await project.datasets.uploadFolder(
  datasetName,
  VERSION2,
  path.join(__dirname, sampleFolder),
);
console.log("Dataset2 created:", JSON.stringify(dataset2, null, 2));
console.log(
  "Upload a single file to the existing dataset, while letting the service increment the version",
);
const dataset3 = await project.datasets.uploadFile(
  datasetName,
  VERSION3,
  path.join(__dirname, sampleFolder, "sample_file2.txt"),
);
console.log("Dataset3 created:", JSON.stringify(dataset3, null, 2));

console.log("Get an existing Dataset version `1`:");
const datasetVersion1 = await project.datasets.get(datasetName, VERSION1);
console.log("Dataset version 1:", JSON.stringify(datasetVersion1, null, 2));
console.log(`Listing all versions of the Dataset named '${datasetName}':`);
const datasetVersions = project.datasets.listVersions(datasetName);
for await (const version of datasetVersions) {
  console.log("List versions:", version);
}
console.log("List latest versions of all Datasets:");
const latestDatasets = project.datasets.list();
for await (const dataset of latestDatasets) {
  console.log("List datasets:", dataset);
}
// List the details of all the datasets
const datasets = project.datasets.listVersions(datasetName);
const allDatasets: DatasetVersionUnion[] = [];
for await (const dataset of datasets) {
  allDatasets.push(dataset);
}
console.log(`Retrieved ${allDatasets.length} datasets`);
console.log("Delete all Datasets created above:");
await project.datasets.delete(datasetName, VERSION1);
await project.datasets.delete(datasetName, VERSION2);
await project.datasets.delete(datasetName, dataset3.version);
console.log("All specified Datasets have been deleted.");

عمليات الملفات

يوضح الكود أدناه بعض عمليات الملفات باستخدام عميل OpenAI ، والتي تتيح لك تحميل الملفات واستردادها وإدراجها وحذفها. هذه العمليات مفيدة للعمل مع الملفات التي يمكن استخدامها للضبط الدقيق وعمليات نموذج الذكاء الاصطناعي الأخرى. يمكن العثور على العينات الكاملة تحت مجلد "الملفات" في <>عينات الحزمة.

const openAIClient = project.getOpenAIClient();
console.log("Uploading file");
const created = await openAIClient.files.create({
  file: fs.createReadStream(filePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${created.id}`);
const uploadedFile = await openAIClient.files.retrieve(created.id);
console.log("Processed file metadata:\n", JSON.stringify(uploadedFile, null, 2));
console.log(`Retrieving file content with ID: ${uploadedFile.id}`);
const contentResponse = await openAIClient.files.content(uploadedFile.id);
const buf = Buffer.from(await contentResponse.arrayBuffer());
console.log(buf.toString("utf-8"));
// 4) List all files
console.log("Listing all files:");
const filesList = await openAIClient.files.list();
for (const f of filesList.data ?? []) {
  console.log(JSON.stringify(f));
}
// 5) Delete the file
console.log(`Deleting file with ID: ${uploadedFile.id}`);
const deleted = await openAIClient.files.delete(uploadedFile.id);
console.log(
  `Successfully deleted file: ${deleted?.id || uploadedFile.id}, deleted=${String(deleted?.deleted ?? true)}`,
);

عمليات الفهارس

يوضح الكود أدناه بعض عمليات الفهارس. يمكن العثور على العينات الكاملة تحت مجلد "الفهارس" في package samples.

import { AzureAISearchIndex } from "@azure/ai-projects";

const indexName = "sample-index";
const version = "1";
const azureAIConnectionConfig: AzureAISearchIndex = {
  name: indexName,
  type: "AzureSearch",
  version,
  indexName,
  connectionName: "sample-connection",
};

// Create a new Index
const newIndex = await project.indexes.createOrUpdate(indexName, version, azureAIConnectionConfig);
console.log("Created a new Index:", newIndex);
console.log(`Get an existing Index version '${version}':`);
const index = await project.indexes.get(indexName, version);
console.log(index);
console.log(`Listing all versions of the Index named '${indexName}':`);
const indexVersions = project.indexes.listVersions(indexName);
for await (const indexVersion of indexVersions) {
  console.log(indexVersion);
}
console.log("List all Indexes:");
const allIndexes = project.indexes.list();
for await (const i of allIndexes) {
  console.log("Index:", i);
}
console.log("Delete the Index versions created above:");
await project.indexes.delete(indexName, version);

عمليات الضبط الدقيق

الكود أدناه يوضح كيفية إنشاء وظائف الضبط الدقيق باستخدام عميل OpenAI. تدعم هذه العمليات تقنيات ضبط دقيقة متنوعة مثل Fine-Tuning المراقبة (SFT)، Fine-Tuning التعزيز (RFT)، وتحسين الأداء المباشر (DPO). يمكن العثور على العينات الكاملة تحت مجلد "finetuning" في ><عينات الحزمة .

import { JobCreateParams } from "openai/resources/fine-tuning/jobs";

const trainingFilePath = "training_data_path.jsonl";
const validationFilePath = "validation_data_path.jsonl";
const openAIClient = project.getOpenAIClient();
// 1) Create the training and validation files
const trainingFile = await openAIClient.files.create({
  file: fs.createReadStream(trainingFilePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${trainingFile.id}`);
const validationFile = await openAIClient.files.create({
  file: fs.createReadStream(validationFilePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${validationFile.id}`);
// 2) Wait for the files to be processed
await openAIClient.files.waitForProcessing(trainingFile.id);
await openAIClient.files.waitForProcessing(validationFile.id);
console.log("Files processed.");
// 3) Create a supervised fine-tuning job
const fineTuningJob = await openAIClient.fineTuning.jobs.create({} as JobCreateParams, {
  body: {
    trainingType: "Standard",
    training_file: trainingFile.id,
    validation_file: validationFile.id,
    model: deploymentName,
    method: {
      type: "supervised",
      supervised: {
        hyperparameters: {
          n_epochs: 3,
          batch_size: 1,
          learning_rate_multiplier: 1.0,
        },
      },
    },
  },
});
console.log("Created fine-tuning job:\n", JSON.stringify(fineTuningJob));

عمليات جلسات الوكيل التجريبية (معاينة)

تتيح لك العمليات .beta.agents إدارة جلسات الوكلاء وملفات الجلسات للوكلاء المستضافين. توفر الجلسات بيئات صندوق رمل معزولة لتفاعلات الوكلاء.

import { VersionRefIndicator } from "@azure/ai-projects";

const agentName = "MyBetaAgent";
// Create a session for the agent
const versionIndicator: VersionRefIndicator = {
  type: "version_ref",
  agent_version: "1.0",
};
const session = await project.beta.agents.createSession(agentName, versionIndicator);
console.log(`Session created: ${session.agent_session_id}`);
// Upload a file to the session sandbox
const filePath = "/sandbox/hello.txt";
const fileContent = new TextEncoder().encode("Hello from the beta agents sample!");
const uploadResult = await project.beta.agents.uploadSessionFile(
  agentName,
  session.agent_session_id,
  filePath,
  fileContent,
);
console.log(`Uploaded file: ${uploadResult.path} (${uploadResult.bytes_written} bytes)`);

انظر الكود النموذجي الكامل في betaAgents.ts.

عمليات المهارات (معاينة)

تتيح لك العمليات .beta.skills إنشاء وإدارة مهارات قابلة لإعادة الاستخدام تحدد قدرات الوكلاء.

const skillName = "sample-skill";
// Create a new skill
const created = await project.beta.skills.create(skillName, {
  description: "Example skill created by the @azure/ai-projects sample.",
  instructions: "You are a helpful assistant that answers questions concisely.",
  metadata: { owner: "sample" },
});
console.log(`Skill created: ${created.name} (id: ${created.skill_id})`);
// Retrieve the skill
const fetched = await project.beta.skills.get(skillName);
console.log(`Retrieved skill: ${fetched.name} (id: ${fetched.skill_id})`);

انظر الكود النموذجي الكامل في skillBasic.ts.

عمليات صناديق الأدوات (معاينة)

تتيح لك العمليات .toolboxes إنشاء وإدارة صناديق الأدوات — مجموعات قابلة لإعادة الاستخدام من الأدوات يمكن مشاركتها بين الوكلاء.

import { ToolUnion, MCPTool } from "@azure/ai-projects";

const toolboxName = "mcp";
// Define tools for the toolbox
const tools: ToolUnion[] = [
  {
    type: "mcp",
    server_label: "api_specs",
    server_url: "https://github.com/Azure/azure-rest-api-specs",
    require_approval: "never",
  } satisfies MCPTool,
];
// Create a new toolbox version
const created = await project.toolboxes.createVersion(toolboxName, tools, {
  description: "Example toolbox created by the @azure/ai-projects sample.",
  metadata: { status: "created" },
});
console.log(`Toolbox: ${created.name} (tools: ${created.tools.length})`);
// Retrieve the toolbox
const fetched = await project.toolboxes.get(toolboxName);
console.log(`Retrieved toolbox: ${fetched.name} (${fetched.id})`);

انظر الكود النموذجي الكامل في toolboxesCrud.ts.

تتبع

بوابة الميزات التجريبية

مهم: أجهزة تتبع GenAI هي ميزة معاينة تجريبية. قد يتم تعديل الامتدادات والسمات والأحداث في الإصدارات المستقبلية. لاستخدامه، يجب عليك الاختيار صراحة عن طريق التمرير tracingOptions مع experimental: true عند بناء ، AIProjectClientأو بتعيين متغير البيئة:

AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true

قم بتفعيل هذه الميزة فقط بعد مراجعة متطلباتك وفهم أن سلوك التتبع قد يتغير في الإصدارات المستقبلية.

البدء في التتبع

يمكنك إضافة مورد Application Insights Azure إلى مشروع Microsoft Foundry الخاص بك. إذا كان أحدها مفعلا، يمكنك الحصول على سلسلة سلسلة الاتصال الخاصة ب Application Insights وتكوين عميل مشاريع الذكاء الاصطناعي الخاصة بك، وملاحظة الآثار في Azure Monitor. عادة، قد ترغب في بدء التتبع قبل إنشاء عميل أو عامل.

التثبيت

لإرسال التتبع إلى Azure Monitor:

npm install @azure/monitor-opentelemetry @opentelemetry/api

لطباعة الآثار إلى وحدة التحكم (مفيدة للتطوير المحلي):

npm install @opentelemetry/sdk-trace-node @opentelemetry/api

كيفية تمكين التتبع

يتم تمكين التتبع عن طريق التمرير tracingOptions إلى الصانع AIProjectClient . إذا tracingOptions لم يتم توفيرها، يتم تعطيل تتبع الذكاء الاصطناعي المولد تماما ولا يتم إصدار أي مدى أو مقاييس للذكاء الاصطناعي المولد. يتحكم هذا الإعداد فقط في تتبع خاص بالذكاء الاصطناعي المولد (فترات الاتفاقيات الدلالية لاستدعاءات النماذج، عمليات الوكيل، استخدام الرموز، إلخ). ينطبق تكوين التتبع على جميع العمليات التي تنفذ عبر ذلك النسخة المحددة من العميل، بما في ذلك عمليات الوكيل وأي عميل OpenAI يتم الحصول عليه عبر project.getOpenAIClient(). يمكن أن يكون لحالات العميل المختلفة تكوينات تتبع مستقلة.

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

const endpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const credential = new DefaultAzureCredential();

// Tracing enabled
const project = new AIProjectClient(endpoint, credential, {
  tracingOptions: { experimental: true },
});

// Tracing disabled (default — no tracingOptions passed)
const projectNoTrace = new AIProjectClient(endpoint, credential);

console.log(project, projectNoTrace);

تمرير tracingOptions: {} (كائن فارغ) يتيح أيضا التتبع — في هذه الحالة، يتم حل جميع الإعدادات الفردية من متغيرات البيئة المقابلة.

يقبل الكائن tracingOptions الخصائص التالية:

خيار متغير بيئي الإعداد الافتراضي الوصف
experimental AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING false اعترف بالطبيعة التجريبية لهذه الميزة (المطلوبة لإصدار الامتدادات)
contentRecording OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT false التقاط محتوى المطالبة والمحتوى المكتمل في التراث
traceContextPropagation AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION true حقن رؤوس سياق تتبع W3C في الطلبات

يتم حل كل خيار باستخدام ترتيب الأسبقية التالي:

  1. القيمة الصريحة في tracingOptions (أعلى أولوية)
  2. متغير البيئة (يتم التحقق منه عند حذف أو عدم معرفته)
  3. القيمة الافتراضية (تستخدم عندما لا يكون أي منهما محددا أو عندما لا يمكن قراءة متغير البيئة)

ملاحظة: نظرا لأن جميع ميزات التتبع حاليا تجريبية، experimental: true يجب أيضا ضبطها (إما بشكل صريح أو عبر متغير البيئة) لأي امتدادات يمكن إصدارها.

Azure Monitor tracing

إليك عينة كود توضح كيفية تفعيل تتبع Azure Monitor:

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

const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
// Configure Azure Monitor tracing (must be done before creating the client)
const connectionString =
  process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<connection string>";
useAzureMonitor({
  azureMonitorExporterOptions: { connectionString },
  samplingRatio: 1,
  tracesPerSecond: 0,
});
// Create client with tracing enabled (experimental)
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

قد ترغب أيضا في إنشاء فترة زمنية لسيناريوك:

import { trace, context } from "@opentelemetry/api";

const tracer = trace.getTracer("MyScenario");
const span = tracer.startSpan("myOperation");
const ctx = trace.setSpan(context.active(), span);
await context.with(ctx, async () => {
  // Your agent operations here
});
span.end();

شاهد الكود النموذجي الكامل في agentBasicWithAzureMonitorTracing.ts.

تتبع وحدة التحكم

للتطوير المحلي، يمكنك طباعة الآثار على وحدة التحكم:

import {
  NodeTracerProvider,
  SimpleSpanProcessor,
  ConsoleSpanExporter,
} from "@opentelemetry/sdk-trace-node";
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";

// Set up OpenTelemetry with a console exporter (must be done before creating the client)
const provider = new NodeTracerProvider({
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});
provider.register();
// Create client with tracing enabled (experimental)
const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

شاهد الكود النموذجي الكامل في agentBasicWithConsoleTracing.ts.

تمكين تسجيل المحتوى

يتحكم تسجيل المحتوى فيما إذا كانت محتويات الرسائل وتفاصيل استدعاء الأدوات (مثل المعلمات وقيم الإرجاع) محفوظة في المسار. قد تتضمن هذه البيانات معلومات حساس للمستخدمين.

لتمكين تسجيل المحتوى، قم بتمرير contentRecording: true المفتاح tracingOptions عند إنشاء العميل، أو تعيين متغير OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT البيئة إلى true. تسجيل المحتوى يقيم افتراضيا على false.

تمكين انتشار السياق الأثري

يسمح انتشار السياق التتبع بربط امتدادات جانب العميل مع امتدادات على جانب الخادم من Azure OpenAI وخدمات Azure الأخرى. عند تفعيلها، تقوم مجموعة تطوير البرمجيات تلقائيا بحقن رؤوس سياق تتبع W3C (traceparent و tracestate) في طلبات HTTP التي يقدمها عملاء OpenAI والتي تم الحصول عليها عبر project.getOpenAIClient().

هذا يضمن أن جميع العمليات داخل التتبع الموزع تشترك في نفس معرف الأتراس، مما يوفر رؤية شاملة عبر تطبيقك وخدمات Azure في خلفية قابلية الملاحظة.

يتم تفعيل انتشار تتبع السياق بشكل افتراضي. لتعطيله، قم بتمريره traceContextPropagation: falsetracingOptions عند بناء العميل، أو اضبط متغير AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION البيئة على false.

اعتبارات مهمة للأمان والخصوصية:

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

قم بتمكين نشر السياق الأثري فقط بعد مراجعة متطلبات الملاحظة والخصوصية والأمان بعناية.

Troubleshooting

الاستثناءات

تؤدي أساليب العميل التي تجري استدعاءات الخدمة إلى رفع RestError لاستجابة رمز حالة HTTP غير ناجحة من الخدمة. سيحتفظ code الاستثناء برمز حالة استجابة HTTP. يحتوي error.message الاستثناء على رسالة مفصلة قد تكون مفيدة في تشخيص المشكلة:

import { isRestError } from "@azure/core-rest-pipeline";

try {
  const result = await project.connections.list();
} catch (e) {
  if (isRestError(e)) {
    console.log(`Status code: ${e.code}`);
    console.log(e.message);
  } else {
    console.error(e);
  }
}

على سبيل المثال، عند توفير بيانات اعتماد خاطئة:

Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'

مشاكل إعداد التقارير

للإبلاغ عن مشاكل في مكتبة العميل، أو طلب ميزات إضافية، يرجى فتح عدد GitHub here

الخطوات التالية

اطلع على مجلد package samples، الذي يحتوي على كود قابل للتشغيل بالكامل.

إعادة التجديد من TypeSpec (القائمون)

يتم إعادة توليد هذه الحزمة من مواصفة TypeSpec في Azure/azure-rest-api-specs. يتم ترميز سير العمل الكامل بست مهارات تحت .github/skills/ ويمكن دفعه من البداية إلى النهاية بواسطة مهمة وكيل ترميز GitHub Copilot.

لإرسال عملية تجديد كمهمة وكيل سحابة، قم بتشغيل هذا الدليل:

pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1                     # latest commit on feature/foundry-release
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -TspCommit <sha>    # pin a specific commit
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -DryRun             # render the prompt locally, do not dispatch
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -Repo myuser/azure-sdk-for-js -Follow   # smoke-test on a fork

على Windows، قد يتم حظر استدعاء السكريبت مباشرة (مثل ./scripts/start-cloud-regen.ps1) بواسطة سياسة التنفيذ الافتراضية Restricted. النموذج pwsh -NoProfile -File ... أعلاه يتجنب ذلك. بدلا من ذلك، شغل Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned مرة واحدة للسماح بالسكريبتات المحلية.

المتطلبات الأساسية:

  • gh تم تثبيت CLI والتحقق من (gh auth login) ضد المستودع المستهدف. agent-task الأمر الفرعي في مرحلة المعاينة ويتطلب تحديث gh.
  • العضوية في منظمة تتيح لك وكيل الترميز GitHub Copilot المستودع المستهدف.
  • ادفع الوصول إلى المستودع المستهدف (وكيل السحابة يستخدم هوية تطبيق GitHub الخاصة به لدفع وفتح مسودة الPR).

تنبيه: التوجيه المرسل ينفذ pnpm install --filter @azure/ai-projects... ويعمل pnpm --filter @azure/ai-projects... build بشكل خطي في بداية المهمة. إذا قام صندوق الرمل الخاص بوكيل السحابة بحجب تلك المكالمات الشبكية، ستفشل المهمة عند الإعداد؛ في هذه الحالة، شغل المهارات محليا، أو تنسيق مع فريق بناء SDK لإضافة سير عمل مدار copilot-setup-steps.yml مركزيا في جذر المستودع.

المساهمة في

يرحب هذا المشروع بالمساهمات والاقتراحات. تتطلب معظم المساهمات منك الموافقة على اتفاقية ترخيص المساهمين (CLA) التي تعلن أن لديك الحق في منحنا حقوق استخدام مساهمتك. لمزيد من التفاصيل، تفضل بزيارة https://cla.microsoft.com.

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

وقد اعتمد هذا المشروع مدونة السلوك مفتوحة المصدر Microsoft. لمزيد من المعلومات، راجع الأسئلة المتداولة حول قواعد السلوك أو الاتصال opencode@microsoft.com مع أي أسئلة أو تعليقات إضافية.