Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Клиентская библиотека AI Projects (в предварительном просмотре) является частью Microsoft Foundry SDK и обеспечивает лёгкий доступ к ресурсам в вашем проекте Microsoft Foundry. Он используется для следующих задач:
-
Создайте и запустите агенты с помощью
.agentsсвойства на клиенте.
-
Улучшайте агенты специализированными инструментами:
- Поиск памяти агента (предварительный просмотр)
- Агент-агент (A2A) (Предварительный просмотр)
- Azure AI Search
- Пользовательский поиск Bing (Предварительный просмотр)
- Заземление Bing
- Автоматизация браузера (предварительный просмотр)
- Интерпретатор кода
- Компьютерное использование (предварительный просмотр)
- Поиск файлов
- Функциональный инструмент
- Генерация изображений
- Microsoft Fabric (Предварительный просмотр)
- Протокол контекста модели (MCP)
- OpenAPI
- Microsoft SharePoint (Предварительный просмотр)
- Веб-поиск (предварительный просмотр)
-
Получите клиент OpenAI , используя
.getOpenAIClient.этот метод для запуска операций Responses, Conversations, Evaluation и FineTuning с вашим агентом.
-
Управление хранилищами памяти (предпросмотр) для разговоров с агентами с помощью
.beta.memoryStoresопераций. -
Ознакомьтесь с дополнительными инструментами оценки (некоторые в предварительном просмотре ), чтобы оценить производительность вашего генеративного ИИ-приложения, используя
.evaluationRules,.beta.evaluationTaxonomies,.beta.evaluators,.beta.insightsи.beta.schedulesоперации. -
Проведите сканирование Red Team (предварительный просмотр ), чтобы выявить риски, связанные с вашим генеративным AI-приложением, используя эти
.beta.redTeamsоперации. - Тонкая настройка ИИ моделирует ваши данные.
-
Перечислите модели ИИ , развернутые в проекте Foundry,
.deploymentsс помощью операций. -
Перечислите связанные Azure ресурсы в вашем проекте Foundry, используя операции
.connections. -
Загрузите документы и создайте наборы данных , чтобы ссылаться на них с помощью
.datasetsопераций. -
Создание и перечисление индексов поиска с помощью
.indexesопераций.
Клиентская библиотека использует версию v1REST API плоскости данных Microsoft Foundry.
документация продукта | Samples | Package (npm) | API Reference Documentation | SDK исходный код
Оглавление
- Начало работы
- Основные понятия
- Примеры
- Трассировка
- Troubleshooting
- Дальнейшие действия
- участие
Начало работы
Необходимые условия
- Версии Node.js LTS
- Подписка Azure.
- Проект в Microsoft Foundry.
- URL конечной точки проекта в форме
https://your-ai-services-account-name.services.ai.azure.com/api/projects/your-project-name. Её можно найти на странице обзора Microsoft Foundry Project. Ниже предположим, что переменнаяAZURE_AI_PROJECT_ENDPOINTсреды была определена для хранения этого значения.
Авторизация
- Для аутентификации клиента требуется ID Entra. Приложению требуется объект, реализующий интерфейс TokenCredential. Примеры кода здесь используют DefaultAzureCredential. Чтобы получить эту работу, вам потребуется:
- Подходящее назначение роли. см. Управление доступом по ролям в портале Microsoft Foundry. Назначение роли можно выполнить через вкладку «Access Control (IAM)» вашего ресурса проекта Azure AI в портале Azure.
- Azure CLI установлен.
- Вы входите в свой аккаунт Azure с помощью
az login. - Обратите внимание, что если у вас несколько подписок на Azure, подписка, содержащая ваш ресурс проекта Azure AI, должна быть вашей подпиской по умолчанию. Запустите
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. Ниже мы предположим, что переменная AZURE_AI_PROJECT_ENDPOINT окружения была определена для хранения этого значения:
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
const projectEndpoint = process.env["AZURE_AI_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.memoryStores, .beta.evaluationTaxonomies, .beta.evaluators, .beta.insights, .beta.schedulesи .beta.redTeams.
Примеры
Выполнение операций с ответами с помощью клиента OpenAI
В вашем проекте Microsoft Foundry может быть развернута одна или несколько моделей ИИ. Это могут быть модели OpenAI, модели Microsoft или модели других провайдеров. Используйте приведенный ниже код, чтобы получить аутентифицированный OpenAI из пакета openai и выполнить вызов завершения чата.
Выполните приведенный ниже код. Здесь мы предполагаем, что deploymentName (str) определено. Это имя развертывания модели ИИ в проекте Foundry. Как показано во вкладке "Модели + конечные точки", в столбце "Название".
Смотрите папку «responses» в package samples для дополнительных образцов, включая потоковые ответы.
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, поэтому вам, скорее всего, потребуется заставить 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");
Использование инструментов агентов
Агенты могут быть усилены специализированными инструментами для различных возможностей. Инструменты организованы по требованиям к соединению:
Встроенные инструменты
Эти инструменты работают мгновенно без необходимости внешних соединений.
Интерпретатор кода
Пишите и запускайте код на Javascript в песочнице, обрабатывайте файлы и работайте с разными форматами данных. Документация по 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
Вызывать внешние API, определённые спецификациями 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.
Функциональный инструмент
Определить пользовательские функции, позволяющие агентам взаимодействовать с внешними API, базами данных или логикой приложений. Документация по 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["AZURE_AI_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 Инструменты
Эти инструменты требуют настройки соединений в вашем проекте AI Foundry и использования projectConnectionId.
Поиск по искусственному интеллекту Azure
Интегрируйте с индексами Azure AI Search для мощного поиска знаний и семантического поиска:
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
Ответы наземных агентов с результатами поиска в интернете в реальном времени от 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 (Предварительный просмотр)
Используйте специально настроенные поисковые экземпляры 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 Connection
Интеграция с 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
Вызовите внешние API, определённые спецификациями 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.
Полные рабочие примеры всех инструментов смотрите в каталоге samples-dev.
Evaluation
Клиентская библиотека Azure AI Project предоставляет количественные, с помощью ИИ метрики качества и безопасности для оценки производительности и оценки моделей LLM, приложений GenAI и агентов. Метрики определяются как оценщики. Встроенные или индивидуальные оценщики могут предоставить всестороннюю оценочную аналитику.
Код ниже показывает некоторые операции оценки. Полный список образцов можно найти в папке «оценки» в package samples
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. Полные сэмплы можно найти в папке "deployment" в package samples.
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 Projects. Эти подключения можно увидеть в «Центре управления», во вкладке «Подключенные ресурсы» в вашем проекте Microsoft Foundry. Полные сэмплы можно найти в папке "connections" в package samples.
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)}`);
Операции с набором данных
В приведенном ниже коде показаны некоторые операции с набором данных. Полные сэмплы можно найти в папке "datasets" в package samples.
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, которые позволяют загружать, извлекать, перечислять и удалять файлы. Эти операции полезны для работы с файлами, которые можно использовать для тонкой настройки и других операций модели ИИ. Полные сэмплы можно найти в папке "files" в package samples.
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)}`,
);
Операции с индексами
В приведенном ниже коде показаны некоторые операции с индексами. Полные образцы можно найти в папке "indexes" в 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. Эти операции поддерживают различные методы тонкой настройки, такие как Supervised Fine-Tuning (SFT), Reinforcement Fine-Tuning (RFT) и Direct Performance Optimization (DPO). Полные сэмплы можно найти в папке «finetuning» в package samples.
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));
Трассировка
Заметка: Функция трассировки находится в предварительной предварительной версии и может быть изменена. Диапазоны, атрибуты и события могут быть изменены в будущих версиях.
Вы можете добавить ресурс Application Insights Azure к вашему проекту Microsoft Foundry. Перейдите на вкладку «Трассировка» в проекте Microsoft Foundry. Если она включена, вы можете получить connection string Application Insights, настроить клиент AI Projects и наблюдать полный путь выполнения через Azure Monitor. Как правило, вы можете начать трассировку до создания клиента или агента.
Installation
npm install @azure/monitor-opentelemetry@^1.14.2 @opentelemetry/api@^1.9.0
Как включить трассировку
Вот пример кода, который показывает, как включить трассировку Azure Monitor:
import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";
const TELEMETRY_CONNECTION_STRING = process.env["TELEMETRY_CONNECTION_STRING"];
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: TELEMETRY_CONNECTION_STRING,
},
};
useAzureMonitor(options);
См. полный пример кода в remoteTelemetry.ts.
Устранение неполадок
Исключения
Клиентские методы, которые вызывают службы, вызывают 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 выпуск здесь
Дальнейшие действия
Посмотрите папку package samples с полностью загруженным кодом.
участие
Этот проект приветствует взносы и предложения. Большинство вкладов требуют, чтобы вы согласились с соглашением о лицензии участника (CLA), заявив, что у вас есть право, и на самом деле, предоставьте нам права на использование вашего вклада. Для получения подробных сведений посетите веб-страницу https://cla.microsoft.com.
При отправке запроса на вытягивание бот CLA автоматически определяет, нужно ли предоставить соглашение об уровне обслуживания и украсить pr соответствующим образом (например, метка, комментарий). Просто следуйте инструкциям, предоставленным ботом. Это необходимо сделать только один раз во всех репозиториях с помощью нашего CLA.
В рамках этого проекта действуют правила поведения в отношении продуктов с открытым исходным кодом Майкрософт. Дополнительные сведения см. в разделе "Часто задаваемые вопросы о поведении" или opencode@microsoft.com с дополнительными вопросами или комментариями.
Azure SDK for JavaScript