Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
AI Projects istemci kütüphanesi (önizleme aşamasında) Microsoft Foundry SDK'nın bir parçasıdır ve Microsoft Foundry Project'inizdeki kaynaklara kolay erişim sağlar. Bunu şunlar için kullanın:
- İstemcideki özelliği kullanarak
.agents.
-
Ajanları özel araçlarla güçlendirin:
- Ajan Bellek Arama (Önizleme)
- Ajandan Ajana (A2A) (Önizleme)
- Azure Yapay Zeka Arama
- Bing Custom Search (Önizleme)
- Bing Bağlam Sağlama
- Tarayıcı Otomasyonu (Önizleme)
- Kod Yorumlayıcı
- Bilgisayar Kullanımı (Önizleme)
- Dosya Arama
- Fonksiyon Aracı
- Görüntü Üretimi
- Microsoft Fabric (Önizleme)
- Model Bağlam Protokolü (MCP)
- OpenAPI
- Microsoft SharePoint (Önizleme)
- Web Arama (Önizleme)
- Yanıtlar, Konuşmalar, Değerlendirmeler ve İnce Ayarlama işlemlerini Ajanınızla çalıştırmak için bir OpenAI istemcisi
.getOpenAIClient.edinin.
-
İşlemleri kullanarak beta ajan oturumlarını ve dosyalarını (önizleme) yönetin.
.beta.agents - Yeniden kullanılabilir ajan yetenekleri için işlemleri kullanarak
.beta.skills). - Araçları yeniden kullanılabilir koleksiyonlar halinde gruplamak için araç kutularını (önizleme) yönetin, işlemler
.beta.toolboxeskullanılarak. - Ajan konuşmaları için bellek depolarını (önizleme) yönetin, işlemler
.beta.memoryStoreskullanılarak. - Otomatik iş akışlarını planlamak ve göndermek için rutinleri (önizleme) yönetin, işlemler
.beta.routineskullanılarak. - Özel model sürümlerini oluşturmak, güncellemek ve yönetmek için model sürümlerini (önizleme) yönetin, işlemler
.beta.modelskullanılarak. - Üretken yapay zeka uygulamanızın performansını , , ,
.evaluationRules, ve.beta.evaluationTaxonomiesişlemleri.beta.evaluators.beta.insightskullanarak.beta.schedules. - Operasyonları kullanarak üretken yapay zeka uygulamanızla ilgili riskleri belirlemek
.beta.redTeamsçalıştırın. - İnce ayar Verileriniz üzerinde yapay zeka modelleri oluşturun.
-
AI Modelleri
.deploymentsişlemlerini kullanarak Foundry'nize Project dağıtın. -
Foundry projenizde bağlı Azure kaynakları
.connectionsişlemlerini kullanarak sayın. - İşlemleri kullanarak bunlara başvurmak için
.datasets. - İşlemleri kullanarak Arama Dizinleri oluşturun ve numaralandırın
.indexes.
İstemci kütüphanesi, Microsoft Foundry v1'nin sürümünü kullanır.
Ürün dokümantasyonu | Samples | Package (npm) | API referans dokümantasyonu | SDK kaynak kodu
İçindekiler tablosu
-
Başlangıç
- Ön koşul
- Authorization
- Paket yükleme
-
Temel kavramlar
- İstemci oluşturma ve kimliğini doğrulama
- Önizleme operasyon grupları ve isteğe bağlı özellik bayrakları
-
Examples
- OpenAI istemcisini kullanarak Yanıt işlemlerini gerçekleştirme
- Agent işlemlerini gerçekleştirme
- Ajan araçlarının kullanımı
- Değerlendirme operasyonları
- Dağıtım işlemleri
- Bağlantı işlemleri
- Veri kümesi işlemleri
- Dosya işlemleri
- Dizin işlemleri
- İnce ayar işlemleri
- Beta agent oturum işlemleri (önizleme)
- Beceri operasyonları (önizleme)
- Araç kutuları işlemleri (önizleme)
- İzleme
- Sorun giderme
- Sonraki Adımlar
- Katkıda Bulunma
Başlangıç
Ön koşul
- Node.js LTS sürümleri
- Bir Azure abonelik.
- Microsoft Foundry'da bir
proje. - Form
https://your-ai-services-account-name.services.ai.azure.com/api/projects/your-project-nameolan proje uç noktası URL'si . Microsoft Foundry Project genel bakış sayfanızda bulunabilir. Aşağıda, ortam değişkenininFOUNDRY_PROJECT_ENDPOINTbu değeri tutacak şekilde tanımlandığını varsayacağız.
Yetkilendirme
- İstemciyi doğrulamak için bir Entra ID gereklidir. Uygulamanızın TokenCredential arabirimini uygulayan bir nesnesine ihtiyacı var. Burada kod örnekleri DefaultAzureCredential kullanılır. Bunun çalışması için şunları yapmanız gerekir:
- Uygun bir rol ataması. Rol tabanlı erişim kontrolü Microsoft Foundry portalında bkz. Görev atama, Azure portalındaki Azure AI Project kaynağınızın "Access Control (IAM)" sekmesi üzerinden yapılabilir.
- Azure CLI kuruldu.
-
az loginçalıştırarak Azure hesabınıza giriş yapıyorsunuz. - Birden fazla Azure aboneliğiniz varsa, Azure AI Project kaynağınızı içeren abonelik varsayılan aboneliğiniz olmalıdır. Tüm aboneliğinizi listelemek ve hangisinin varsayılan olduğunu görmek için
az account list --output tableçalıştırın. Varsayılan aboneliğinizi değiştirmek içinaz account set --subscription "Your Subscription ID or Name"çalıştırın.
Paket yükleme
npm install @azure/ai-projects dotenv
Temel kavramlar
İstemciyi Entra ID ile oluşturun ve doğrulayın
Entra ID, şu anda istemci tarafından desteklenen tek kimlik doğrulama yöntemidir.
Bir AIProjectsClientoluşturmak için projectEndpoint getirilebilir. Aşağıda, ortam değişkeninin FOUNDRY_PROJECT_ENDPOINT bu değeri tutacak şekilde tanımlandığını varsayacağız:
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());
Önizleme operasyon grupları ve isteğe bağlı özellik bayrakları
Bazı önizleme işlemleri açık foundryFeatures bir opt-in bayrağı gerektirir. Örneğin:
await project.agents.createVersion(
"preview-agent",
{
kind: "workflow",
},
{ foundryFeatures: "WorkflowAgents=V1Preview" },
);
for await (const rule of project.evaluationRules.list()) {
console.log(rule.id);
}
Önizleme operasyon grupları .beta.agents, .beta.skills, .beta.toolboxes, .beta.memoryStores, .beta.routines, , .beta.models.beta.evaluationTaxonomies.beta.evaluators.beta.insights.beta.schedules, ve ..beta.redTeams
Örnekler
OpenAI istemcisini kullanarak Yanıt işlemlerini gerçekleştirme
Microsoft Foundry projenizde bir veya daha fazla yapay zeka modeli kurulmuş olabilir. Bunlar OpenAI modelleri, Microsoft modelleri veya diğer sağlayıcılardan modeller olabilir. OpenAI paketinden kimliği doğrulanmış bir OpenAI almak için aşağıdaki kodu kullanın ve bir sohbet tamamlama çağrısı yürütün.
Aşağıdaki kodu çalıştırın. Burada (str)'nin tanımlandığını varsayıyoruz deploymentName . Bu, Foundry Project'inizdeki bir yapay zeka modelinin dağıtım adıdır. "Modeller + uç noktalar" sekmesinde, "Ad" sütununun altında gösterildiği gibi.
Ek örnekler ve akış yanıtları dahil olmak üzere package samples içindeki "responses" klasörüne bakınız.
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));
Agent işlemlerini gerçekleştirme
üzerindeki .agents özellik, AIProjectsClient tüm Aracı işlemlerine erişmenizi sağlar. Aracılar, OpenAI Yanıtlar protokolünün bir uzantısını kullanır, bu nedenle aşağıdaki örnekte gösterildiği gibi, Aracı işlemlerini yapmak için bir OpenAI istemci bulmanız gerekebilir.
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");
Ajan araçlarının kullanımı
Ajanlar, çeşitli yetenekler için özel araçlarla geliştirilebilir. Araçlar, bağlantı gereksinimlerine göre düzenlenmiştir:
Yerleşik Araçlar
Bu araçlar hemen çalışır ve harici bağlantı gerektirmez.
Kod Yorumlayıcısı
Javascript kodunu sandbox ortamında yazıp çalıştırın, dosyaları işleyin ve çeşitli veri formatlarıyla çalışın. OpenAI Belgeleri
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}`);
Tam örnek kodu agentCodeInterpreter.ts içindeki bekleyin.
Dosya Arama
Bilgi erişimi için vektör depoları kullanarak belgeleri işlemek ve aramak için yerleşik RAG (Retrieval-Augmented Generation) aracı. OpenAI Belgeleri
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})`);
Tam örnek kodu agentFileSearchStream.ts içindeki bekleyin.
Görüntü Üretimi
Metin istemlerine dayanarak özelleştirilebilir çözünürlük, kalite ve stil ayarlarıyla görüntüler oluşturun:
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})`);
Aradıktan responses.create()sonra, geri dönen yanıtla dosyayı indirebilirsiniz:
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.");
}
Web Arama (Önizleme)
İnternetten güncel bilgileri almak için genel web aramaları yapın. OpenAI Belgeleri
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}`);
Tam örnek kodu agentWebSearch.ts içindeki bekleyin.
Bilgisayar Kullanımı (Önizleme)
Ajanların görev otomasyonu ve sistem işlemleri için bilgisayar sistemleriyle doğrudan etkileşime girmesini mümkün kılın:
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})`);
Çağrıldıktan responses.create()sonra, cevabı bir etkileşim döngüsünde işlesin. Çıktı öğelerini yönetin computer_call ve etkileşime devam etmek için yazı gibi computer_call_output ekran computer_screenshot görüntüleri sağlayın.
Tam örnek kodu agentComputerUse.ts içindeki bekleyin.
Model Bağlam Protokolü (MCP)
MCP sunucularını entegre ederek ajanların yeteneklerini standartlaştırılmış araçlar ve kaynaklarla genişletin. OpenAI Belgeleri
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" } },
},
);
Aradıktan responses.create()sonra, yanıt çıkışında öğeleri mcp_approval_request kontrol edin. Temsilcinin işine devam etmesine izin vermek için onay kararınızı geri McpApprovalResponse gönderin.
Tam örnek kodu agentMcp.ts içindeki bekleyin.
OpenAPI
Ek istemci tarafı kod olmadan OpenAPI spesifikasyonlarıyla tanımlanan harici API'leri çağırın. OpenAI Belgeleri
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})`);
Tam örnek kodu agentOpenApi.ts içindeki bekleyin.
Fonksiyon Aracı
Ajanların harici API'ler, veritabanları veya uygulama mantığı ile etkileşime girmesini sağlayan özel fonksiyonlar tanımlayın. OpenAI Belgeleri
/**
* 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})`);
Çağırdıktan responses.create()sonra, yanıt çıktısından öğeleri işleyin function_call , sağlanan argümanlarla fonksiyon mantığını çalıştırın ve sonuçlarla geri FunctionCallOutput gönderin.
Tam örnek kodu agentFunctionTool.ts içindeki bekleyin.
- Bellek Arama Aracı (Önizleme)
Bellek Depolama Aracı, bir Ajan'a Bellek ekler ve bu da Ajanın yapay zeka modelinin mevcut kullanıcı isteğiyle ilgili geçmiş bilgileri aramasına olanak tanır.
Bu embeddingModelDeployment , anıları depolamak ve aramak için vektör gömülmeleri oluşturmak için kullanılan modelin adıdır.
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
},
],
});
Tam örnek kodu agentMemorySearch.ts içindeki bekleyin.
Connection-Based Araçlar
Bu araçlar, AI Foundry projenizde bağlantıların yapılandırılmasını gerektirir ve .projectConnectionId
Azure AI Arama Hizmeti
Güçlü bilgi arama ve anlamsal arama yetenekleri için Azure Yapay Zeka Arama indeksleriyle entegre olun:
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})`);
Tam örnek kodu agentAiSearch.ts içindeki bakışta görün.
Bing Temellendirme
Bing'den gerçek zamanlı web arama sonuçlarıyla yer ajanı yanıtları ile up-totarih bilgisi sağlanır:
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})`);
Tam örnek kodu agentBingGrounding.ts içindeki bekleyin.
Bing Custom Search (Önizleme)
Alan adına özgü veya filtrelenmiş web arama sonuçları için özel yapılandırılmış Bing arama örnekleri kullanın:
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})`);
Tam örnek kodu agentBingCustomSearch.ts içindeki bekleyin.
Microsoft Fabric (Önizleme)
Microsoft Fabric'e bağlanın ve sorgulayın:
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})`);
Tam örnek kodu agentFabric.ts içindeki bekleyin.
Microsoft SharePoint (Önizleme)
Kurumsal bilgi entegrasyonu için SharePoint belgelerine, listelerine ve sitelerine erişim ve arama yöntemi:
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})`);
Tam örnek kodu agentSharepoint.ts içindeki bekleyin.
Tarayıcı Otomasyonu (Önizleme)
Web kazıma, test ve web uygulamalarıyla etkileşim için tarayıcı etkileşimlerini otomatikleştirin:
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})`);
Tam örnek kodu agentBrowserAutomation.ts içindeki bekleyin.
MCP ile Project Bağlantı
Bağlı MCP sunucularına erişmek için proje özel bağlantılar kullanılarak MCP entegrasyonu:
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})`);
Tam örnek kodu agentMcpConnectionAuth.ts içindeki bekleyin.
Ajandan Ajana (A2A) (Önizleme)
Ajanların iletişim kurabileceği ve görevleri diğer uzmanlaşmış ajanlara devredebileceği çoklu ajan iş birliğini mümkün kılın:
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})`);
Tam örnek kodu agentAgentToAgent.ts içindeki bakışta görün.
OpenAPI ile Project Bağlantısı
OpenAPI spesifikasyonlarıyla tanımlanan harici API'leri proje bağlantı doğrulaması kullanarak çağırın:
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})`);
Tam örnek kodu agentOpenApiConnectionAuth.ts içindeki bakışta görün.
Tüm araçların tam çalışma örnekleri için samples-dev directory adresine bakınız.
Evaluation
Azure AI Project istemci kütüphanesinde değerlendirme, performansı değerlendirmek ve LLM modelleri, GenAI uygulamaları ve ajanları değerlendirmek için nicel, yapay zeka destekli kalite ve güvenlik metrikleri sağlar. Metrikler değerlendiriciler olarak tanımlanır. Yerleşik veya özel değerlendiriciler, kapsamlı değerlendirme içgörüleri sağlayabilir.
Aşağıdaki kod bazı değerlendirme işlemlerini göstermektedir. Örnek listesinin tam listesi
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})`);
Tam örnek kodu agentEvaluation.ts içindeki bekleyin.
Dağıtım işlemleri
Aşağıdaki kod, Microsoft Foundry Projelerinize yerleştirilen yapay zeka modellerini saymanıza olanak tanıyan bazı Dağıtım işlemlerini gösteriyor. Bu modeller, Microsoft Foundry Project'inizdeki "Modeller + uç noktalar" sekmesinde görülebilir. Tam örnekler package samples içindeki "deployment" klasörünün altında bulunabilir.
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)}`);
}
Bağlantı işlemleri
Aşağıdaki kod, Microsoft Foundry Projelerinize bağlı Azure Resources'ı saymanıza olanak tanıyan bazı Bağlantı işlemlerini gösteriyor. Bu bağlantılar, Microsoft Foundry Project'inizdeki "Bağlı kaynaklar" sekmesinde "Yönetim Merkezi"nde görülebilir. Tam örnekler package samples içindeki "connections" klasörünün altında bulunabilir.
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)}`);
Veri kümesi işlemleri
Aşağıdaki kodda bazı Veri Kümesi işlemleri gösterilmektedir. Tam örnekler package samples içindeki "veri setleri" klasörünün altında bulunabilir.
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.");
Dosya işlemleri
Aşağıdaki kod, OpenAI istemcisini kullanarak dosyaları karşıya yüklemenize, almanıza, listelemenize ve silmenize olanak tanıyan bazı Dosyalar işlemlerini gösterir. Bu işlemler, ince ayar ve diğer yapay zeka modeli işlemleri için kullanılabilecek dosyalarla çalışmak için kullanışlıdır. Tam örnekler package samples içindeki "files" klasörünün altında bulunabilir.
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)}`,
);
Dizin işlemleri
Aşağıdaki kod bazı Dizin işlemlerini gösterir. Tam örnekler package samples içindeki "indexes" klasörünün altında bulunabilir.
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);
hassas ayarlama işlemleri
Aşağıdaki kod, OpenAI istemcisiyle ince ayar işleri nasıl oluşturulacağını gösteriyor. Bu işlemler, Denetli Fine-Tuning (SFT), Güçlendirme Fine-Tuning (RFT) ve Doğrudan Performans Optimizasyonu (DPO) gibi çeşitli ince ayar tekniklerini destekler. Tam örnekler package samples içindeki "finetuning" klasörünün altında bulunabilir.
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 agent oturum işlemleri (önizleme)
Bu .beta.agents işlemler, barındırılan ajanlar için ajan oturumlarını ve oturum dosyalarını yönetmenizi sağlar. Oturumlar, ajan etkileşimleri için izole sandbox ortamları sağlar.
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)`);
Tam örnek kodu betaAgents.ts içindeki bakışta görün.
Beceri operasyonları (önizleme)
Operasyonlar, .beta.skills ajan yeteneklerini tanımlayan yeniden kullanılabilir beceriler oluşturmanıza ve yönetmenize olanak tanır.
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})`);
Tam örnek kodu skillBasic.ts içindeki bakışta görebilirsiniz.
Araç kutuları işlemleri (önizleme)
Bu .beta.toolboxes işlemler, ajanlar arasında paylaşılabilen yeniden kullanılabilir araç koleksiyonları — araç kutuları oluşturmanıza ve yönetmenize olanak tanıyor.
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})`);
Tam örnek kodu toolboxesCrud.ts bölümünde bekleyin.
İzleme
Deneysel özellik kapısı
Önemli: GenAI izleme enstrümantasyonu deneysel bir önizleme özelliğidir. Yayılma alanları, öznitelikler ve olaylar gelecek sürümlerde değiştirilebilir. Bunu kullanmak için, , oluştururken tracingOptionsile experimental: true geçiş yaparak veya ortam değişkenini ayarlayarak açıkça onay vermeniz AIProjectClient gerekir:
AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true
Bu özelliği ancak gereksinimlerinizi gözden geçirdikten ve takip davranışının gelecekteki sürümlerde değişebileceğini anladıktan sonra etkinleştirin.
İzlemeye başlamak
Microsoft Foundry projenize bir Application Insights Azure kaynağı ekleyebilirsiniz. Eğer bir özellik etkinleştirildiyse, Application Insights bağlantı dizesi'i alabilir, AI Projects istemcinizi yapılandırabilir ve Azure İzleyici'da trace'leri gözlemleyebilirsiniz. Genellikle, bir istemci veya Aracı oluşturmadan önce izlemeye başlamak isteyebilirsiniz.
Installation
Traces to Azure İzleyici:
npm install @azure/monitor-opentelemetry @opentelemetry/api
Konsola izleri yazdırmak için (yerel geliştirme için faydalı):
npm install @opentelemetry/sdk-trace-node @opentelemetry/api
İzlemeyi nasıl etkinleştiririm
İzlemek, yapımcıya aktarılarak tracingOptionsAIProjectClient mümkün olur. Sağlanmazsa tracingOptions , GenAI izleme tamamen devre dışı bırakılır ve GenAI aralıkları veya metrikleri yayımlanmaz. Bu ayar yalnızca GenAI'ye özgü takip işlemlerini (model çağrıları, ajan işlemleri, token kullanımı vb. için anlamsal konvansiyon aralıkları) kontrol eder. İzleme yapılandırması, o özel istemci örneği üzerinden gerçekleştirilen tüm işlemlere uygulanır; ajans işlemleri ve aracılığıyla project.getOpenAIClient()elde edilen herhangi bir OpenAI istemcisi dahil. Farklı istemci örnekleri bağımsız takip yapılandırmalarına sahip olabilir.
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);
Paslama tracingOptions: {} (boş bir nesne) ayrıca takip etmeyi mümkün kılar — bu durumda, tüm bireysel ayarlar ilgili ortam değişkenlerinden çözülür.
Nesne tracingOptions aşağıdaki özellikleri kabul eder:
| Option | Ortam değişkeni | Varsayılan | Description |
|---|---|---|---|
experimental |
AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING |
false |
Bu özelliğin deneysel doğasını kabul etmek (açıklık yaymak için gereklidir) |
contentRecording |
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT |
false |
İzlerde istem ve tamamlama içeriğini yakalama |
traceContextPropagation |
AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION |
true |
İsteklere W3C iz bağlam başlıkları enjekte et |
Her seçenek, aşağıdaki öncelik sırasıyla çözülür:
-
Açık değer (
tracingOptionsen yüksek öncelik) - Ortam değişkeni (seçenek atlandığında/tanımlanmadığında kontrol edilir)
- Varsayılan değer (hiçbiri ayarlanmadığında veya ortam değişkeni okunamazsa kullanılır)
Not: Tüm takip özellikleri şu anda deneysel olduğundan,
experimental: trueherhangi bir açıklığın yayılması için (ya açıkça ya da ortam değişkeni aracılığıyla) ayarlanmalıdır.
Azure İzleyici tracing
İşte Azure İzleyici tracing nasıl etkinleştirileceğini gösteren bir kod örneği:
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,
},
});
Senaryon için bir aralık da oluşturmak isteyebilirsin:
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();
Tam örnek kodu agentBasicWithAzureMonitorTracing.ts'de görün.
Konsol izleme
Yerel geliştirme için, konsola traces yazdırabilirsiniz:
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,
},
});
Tam örnek kodu agentBasicWithConsoleTracing.ts'de görün.
İçerik kaydını etkinleştirmek
İçerik kaydının, mesaj içeriği ve araç çağrısı detaylarının (parametreler ve dönüş değerleri gibi) izlerde yakalanıp kaydedilmediğini kontrol eder. Bu veriler hassas kullanıcı bilgilerini içerebilir.
İçerik kaydını etkinleştirmek için, istemciyi oluştururken in'i contentRecording: truetracingOptions geçirin veya ortam değişkenini OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT 'ye trueayarlayın. İçerik kaydı varsayılan olarak .false
İz bağlam yayılımını etkinleştirmek
İz bağlam yayımı, istemci tarafı spanların Azure OpenAI ve diğer Azure hizmetlerinden gelen sunucu tarafı spanlarla ilişkilendirilmesine olanak tanır. Etkinleştirildiğinde, SDK otomatik olarak W3C İz Bağlam başlıklarını (traceparent ve tracestate) OpenAI istemcileri project.getOpenAIClient()tarafından elde edilen HTTP taleplerine enjekte eder.
Bu, dağıtık bir iz içindeki tüm işlemlerin aynı iz kimliğini paylaşmasını sağlar ve uygulamanız ile gözlemlenebilirlik arka uçunuzdaki Azure hizmetleri arasında uçtan uca görünürlük sağlar.
İz bağlam yayımı varsayılan olarak etkinleştirilmiştir. Bunu devre dışı bırakmak için, traceContextPropagation: false istemciyi oluştururken in'i tracingOptions yapın veya ortam değişkenini AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION 'ye falseayarlayın.
Önemli güvenlik ve gizlilik hususları:
- İz ID'leri: İz bağlam yayımı etkinleştirildiğinde, iz kimlikleri Azure OpenAI ve diğer harici servislere gönderilir.
- İstek korelasyonu: İz ID'leri, Azure servislerinin aynı oturum veya kullanıcıdan gelen istekleri birden fazla API çağrısı arasında ilişkilendirmesine olanak tanır; bu da kullanım durumunuza bağlı olarak gizlilik etkileri yaratabilir.
İz bağlam yayılımını yalnızca gözlemlenebilirlik, gizlilik ve güvenlik gereksinimlerinizi dikkatlice inceledikten sonra etkinleştirin.
Sorun giderme
İstisnalar
Hizmet çağrıları oluşturan istemci yöntemleri, hizmetten başarılı olmayan bir HTTP durum kodu yanıtı için RestError oluşturur. Özel durumun code HTTP yanıt durum kodunu barındıracaktır. Özel durumun error.message, sorunun tanılanmasında yardımcı olabilecek ayrıntılı bir ileti içerir:
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);
}
}
Örneğin, yanlış kimlik bilgileri sağladığınızda:
Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'
Raporlama sorunları
İstemci kütüphanesindeki sorunları bildirmek veya ek özellikler talep etmek için lütfen GitHub bir sorun açın burada
Sonraki Adımlar
Tam çalıştırılabilir kod içeren package samples klasörüne bir göz atın.
TypeSpec'ten yeniden oluşturulma (bakım sağlayıcılar)
Bu paket, Azure/azure-rest-api-specs içindeki TypeSpec spesifikasyonundan yeniden oluşturulur. Tam iş akışı .github/skills/ altında altı beceri olarak kodlanır ve GitHub Copilot kodlama ajanı görevi tarafından uçtan uca yönlendirilebilir.
Bir yenilemeyi bulut ajanı görevi olarak göndermek için şu dizinden çalıştırın:
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 olarak, betikin doğrudan çağrılması (örneğin
./scripts/start-cloud-regen.ps1) varsayılanRestrictedyürütme politikası tarafından engellenebilir. Yukarıdakipwsh -NoProfile -File ...form bunu atlatıyor. Alternatif olarak, yerel betiklere izin vermek için bir kez çalıştırınSet-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned.
Prerequisites:
-
ghCLI kuruldu ve hedef depoya karşı doğrulandı (gh auth login). Altagent-taskkomut önizleme aşamasında ve güncelghbir . - Hedef repo için GitHub Copilot kodlama ajanı etkinleştirilmiş bir organizasyona üyelik.
- Hedef depoya erişim için push yapın (bulut ajanı kendi GitHub App kimliğini kullanarak taslak PR'ı itip açıyor).
Uyarı: gönderilen prompt görevin başında çalıştırılır pnpm install --filter @azure/ai-projects... ve pnpm --filter @azure/ai-projects... build hata içinde kalır. Bulut ajanının kum kutusu bu ağ çağrılarını engellerse, görev kurulumda başarısız olur; bu durumda becerileri yerel olarak çalıştırabilir veya SDK geliştirme ekibiyle koordine ederek repo köküne merkezi olarak yönetilen copilot-setup-steps.yml bir iş akışı ekleyin.
Katkıda Bulunma
Bu proje katkıları ve önerileri memnuniyetle karşılar. Çoğu katkı, Katkıda Bulunan Lisans Sözleşmesi'ni (CLA) kabul ederek bize katkınızı kullanma hakları verme hakkına sahip olduğunuzu bildirmenizi gerektirir. Ayrıntılar için https://cla.microsoft.comadresini ziyaret edin.
Çekme isteği gönderdiğinizde, CLA botu otomatik olarak CLA sağlamanız gerekip gerekmediğini belirler ve çekme isteğini uygun şekilde süsler (örneğin, etiket, açıklama). Bot tarafından sağlanan yönergeleri izlemeniz yeterlidir. Cla'mızı kullanarak bunu tüm depolarda yalnızca bir kez yapmanız gerekir.
Bu proje, Microsoft Açık Kaynak Davranış Kuralları'ı benimsemiştir. Daha fazla bilgi için Kullanım Kuralları SSS bölümüne bakın veya ek sorularınız veya yorumlarınızla opencode@microsoft.com iletişime geçin.
Azure SDK for JavaScript