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 Aracıları istemci kitaplığını kullanarak:
- OpenAI, Microsoft ve diğer LLM sağlayıcılarının geniş bir model, araç ve özellik ekosisteminden yararlanarak Azure AI Agent Servicekullanarak Aracı geliştirme. Azure AI Aracı Hizmeti, çok çeşitli üretken yapay zeka kullanım örnekleri için Aracılar oluşturulmasını sağlar.
- Not: Bu paket bağımsız olarak kullanılabilse de, gelişmiş bir deneyim için Azure Yapay Zeka Projeleri istemci kitaplığını kullanmanızı öneririz. Projeler kitaplığı, aracılar oluşturma ve yönetme, yapay zeka modellerini numaralandırma, veri kümeleriyle çalışma ve arama dizinlerini yönetme, üretken yapay zeka performansını değerlendirme ve OpenTelemetri izlemeyi etkinleştirme gibi gelişmiş işlevlere basitleştirilmiş erişim sağlar.
Ürün belgeleri | Örnekleri | Paket (npm) | API başvuru belgeleri
İçindekiler tablosu
-
Başlangıç
- Ön koşul
- Yetkilendirme
- Paket yükleme
-
Temel kavramlar
- İstemci oluşturma ve kimliğini doğrulama
-
Örnekler
-
Ajanslar
- aracı oluşturma
: - Dosya Arama
- Kod yorumlayıcı
- Bing topraklama
- Azure AI Arama Hizmeti
- İşlev çağrısı
- ile iş parçacığı oluşturma
- İleti oluşturma:
- Çalıştırmayı, İş Parçacığı Oluşturma ve Çalıştırmayı veya Akış
- İleti alma
- Dosya alma
- Kaynak silerek yırtın
- aracı oluşturma
-
Ajanslar
- Sorun giderme
- Katkıda Bulunma
Başlangıç Yapmak
Önkoşul
- Node.js LTS sürümleri
- Bir Azure aboneliği.
- Azure AI Foundry'de projesi.
İzin
- İstemcinin kimliğini doğrulamak için Entra Kimliği gereklidir. Uygulamanızın TokenCredential arabirimini uygulayan bir nesnesine ihtiyacı var. Buradaki kod örnekleri DefaultAzureCredential
kullanır. Bunun çalışması için şunları yapmanız gerekir: -
Contributorrolü. Atanan rol, Azure portalındaki Azure AI Projesi kaynağınızın "Erişim Denetimi (IAM)" sekmesi aracılığıyla gerçekleştirilebilir. Rol atamaları hakkında daha fazla bilgiyi burada bulabilirsiniz. - Azure CLI yüklendi.
-
az loginçalıştırarak Azure hesabınızda oturum açtınız. - Birden çok Azure aboneliğiniz varsa, Azure AI Project kaynağınızı içeren aboneliğin varsayılan aboneliğiniz olması gerektiğini unutmayın. 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.
-
Paketi yükle
npm install @azure/ai-agents @azure/identity
Temel kavramlar
İstemci oluşturma ve kimlik doğrulaması
İstemciyi AgentsClient oluşturmak için kullanılır. Şu anda, kullanarak Azure Yapay Zeka Projeleri İstemci Kitaplığıclient.agentsaracılığıyla AgentsClient'ı kullanmanızı öneririz.
Proje uç noktanızı almak için belgelere başvurabilirsiniz. Aşağıda ortam değişkeninin PROJECT_ENDPOINT bu değeri tuttuğunu varsayacağız.
import { AgentsClient } from "@azure/ai-agents";
import { DefaultAzureCredential } from "@azure/identity";
const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
Örnekler
Ajanlar
Azure AI Projeleri istemci kitaplığındaki aracılar, yapay zeka projelerinizde çeşitli etkileşimleri ve işlemleri kolaylaştırmak için tasarlanmıştır. Belirli hedeflere ulaşmak için farklı araçlardan ve kaynaklardan yararlanarak görevleri yöneten ve yürüten temel bileşenler olarak görev yaparlar. Aşağıdaki adımlarda Aracılarla etkileşime yönelik tipik sıra özetlenmiştir. Ek Ajan örnekleri için paket örneklerine bakın.
Aracı Oluşturma
Aracı oluşturma örneği aşağıda verilmiştir:
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful assistant",
});
Aracıların kaynaklarınıza veya özel işlevlerinize erişmesine izin vermek için araçlara ihtiyacınız vardır.
createAgent ve tools bağımsız değişkenleri aracılığıyla toolResources araçları geçirebilirsiniz.
Bunu yapmak için ToolSet kullanabilirsiniz:
import { ToolSet } from "@azure/ai-agents";
// Upload file for code interpreter tool
const filePath1 = "./data/syntheticCompanyQuarterlyResults.csv";
const fileStream1 = fs.createReadStream(filePath1);
const codeInterpreterFile = await client.files.upload(fileStream1, "assistants", {
fileName: "myLocalFile",
});
console.log(`Uploaded local file, file ID : ${codeInterpreterFile.id}`);
// Upload file for file search tool
const filePath2 = "./data/sampleFileForUpload.txt";
const fileStream2 = fs.createReadStream(filePath2);
const fileSearchFile = await client.files.upload(fileStream2, "assistants", {
fileName: "sampleFileForUpload.txt",
});
console.log(`Uploaded file, file ID: ${fileSearchFile.id}`);
// Create vector store for file search tool
const vectorStore = await client.vectorStores
.createAndPoll({
fileIds: [fileSearchFile.id],
})
.pollUntilDone();
// Create tool set
const toolSet = new ToolSet();
toolSet.addFileSearchTool([vectorStore.id]);
toolSet.addCodeInterpreterTool([codeInterpreterFile.id]);
// Create agent with tool set
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: toolSet.toolDefinitions,
toolResources: toolSet.toolResources,
});
console.log(`Created agent, agent ID: ${agent.id}`);
Çoklu Ajanlar
Farklı araçlarla birden fazla Ajan oluşturabilir ve ardından bunları birbirine bağlayabilirsiniz.
import { ToolUtility } from "@azure/ai-agents";
const connectedAgentName = "stock_price_bot";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
const stockAgent = await client.createAgent(modelDeploymentName, {
name: "stock-price-agent",
instructions:
"Your job is to get the stock price of a company. If you don't know the realtime stock price, return the last known stock price.",
});
// Initialize Connected Agent tool with the agent id, name, and description
const connectedAgentTool = ToolUtility.createConnectedAgentTool(
stockAgent.id,
connectedAgentName,
"Gets the stock price of a company",
);
// Create agent with the Connected Agent tool and process assistant run
const agent = await client.createAgent(modelDeploymentName, {
name: "my-agent",
instructions: "You are a helpful assistant, and use the connected agent to get stock prices.",
tools: [connectedAgentTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);
Dosya Arama ile Aracı Oluşturma
Bir Aracı tarafından dosya araması yapmak için öncelikle bir dosyayı karşıya yüklememiz, vektör deposu oluşturmamız ve dosyayı vektör deposuyla ilişkilendirmemiz gerekir. Aşağıda bir örnek verilmiştir:
import { ToolUtility } from "@azure/ai-agents";
const filePath = "./data/sampleFileForUpload.txt";
const localFileStream = fs.createReadStream(filePath);
const file = await client.files.upload(localFileStream, "assistants", {
fileName: "sampleFileForUpload.txt",
});
console.log(`Uploaded file, file ID: ${file.id}`);
const vectorStore = await client.vectorStores.create({
fileIds: [file.id],
name: "myVectorStore",
});
console.log(`Created vector store, vector store ID: ${vectorStore.id}`);
const fileSearchTool = ToolUtility.createFileSearchTool([vectorStore.id]);
const agent = await client.createAgent("gpt-4o", {
name: "File Search Agent",
instructions: "You are helpful agent that can help fetch data from files you know about.",
tools: [fileSearchTool.definition],
toolResources: fileSearchTool.resources,
});
console.log(`Created agent, agent ID : ${agent.id}`);
Kod Yorumlayıcı ile Aracı Oluşturma
Bir dosyayı karşıya yüklemek ve aracı tarafından kod yorumlayıcı için kullanmak için bir örnek aşağıda verilmiştir:
import { ToolUtility } from "@azure/ai-agents";
const filePath = "./data/syntheticCompanyQuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const localFile = await client.files.upload(localFileStream, "assistants", {
fileName: "localFile",
});
console.log(`Uploaded local file, file ID : ${localFile.id}`);
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);
// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [codeInterpreterTool.definition],
toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);
Bing Topraklama ile Aracı Oluşturma
Aracınızın Bing arama API'siyle arama yapmasını sağlamak için bağlantıyla birlikte ToolUtility.createBingGroundingTool() kullanırsınız. Bing Search ile Topraklama hakkında daha fazla bilgi edinmek için buraya bakın.
Aşağıda bir örnek verilmiştir:
import { ToolUtility } from "@azure/ai-agents";
const connectionId = process.env["AZURE_BING_CONNECTION_ID"] || "<connection-name>";
// Initialize agent bing tool with the connection id
const bingTool = ToolUtility.createBingGroundingTool([{ connectionId: connectionId }]);
// Create agent with the bing tool and process assistant run
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [bingTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);
Azure AI Search ile Aracı Oluşturma
Azure AI Search, yüksek performanslı uygulamalar için kurumsal bir arama sistemidir. Azure OpenAI Hizmeti ve Azure Machine Learning ile tümleştirilip vektör arama ve tam metin arama gibi gelişmiş arama teknolojileri sunar. Bilgi bankası içgörüleri, bilgi bulma ve otomasyon için idealdir
Azure AI Search'i tümleştirmeye yönelik bir örnek aşağıda verilmiştir:
import { ToolUtility } from "@azure/ai-agents";
const connectionName = process.env["AZURE_AI_SEARCH_CONNECTION_NAME"] || "<connection-name>";
// Initialize Azure AI Search tool
const azureAISearchTool = ToolUtility.createAzureAISearchTool(connectionName, "search-index", {
queryType: "simple",
topK: 3,
filter: "", // Add string here to filter results
indexConnectionId: connectionName,
indexName: "search-index",
});
// Create agent with the Azure AI search tool
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [azureAISearchTool.definition],
toolResources: azureAISearchTool.resources,
});
console.log(`Created agent, agent ID : ${agent.id}`);
İşlev Çağrısı ile Aracı Oluşturma
Geri çağırma işlevlerini işlev araçları olarak tanımlayarak Aracılarınızı geliştirebilirsiniz. Bunlar, createAgent ve toolsbirleşimi aracılığıyla toolResources için sağlanabilir. yalnızca işlev tanımları ve açıklamaları, uygulamaları olmadan createAgentsağlanır.
Run veya event handler of stream, işlev tanımlarına göre requires_action durumu oluşturur. Kodunuz bu durumu işlemeli ve uygun işlevleri çağırmalıdır.
Aşağıda bir örnek verilmiştir:
import {
FunctionToolDefinition,
ToolUtility,
RequiredToolCall,
ToolOutput,
} from "@azure/ai-agents";
class FunctionToolExecutor {
private functionTools: {
func: Function;
definition: FunctionToolDefinition;
}[];
constructor() {
this.functionTools = [
{
func: this.getUserFavoriteCity,
...ToolUtility.createFunctionTool({
name: "getUserFavoriteCity",
description: "Gets the user's favorite city.",
parameters: {},
}),
},
{
func: this.getCityNickname,
...ToolUtility.createFunctionTool({
name: "getCityNickname",
description: "Gets the nickname of a city, e.g. 'LA' for 'Los Angeles, CA'.",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "The city and state, e.g. Seattle, Wa" },
},
},
}),
},
{
func: this.getWeather,
...ToolUtility.createFunctionTool({
name: "getWeather",
description: "Gets the weather for a location.",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "The city and state, e.g. Seattle, Wa" },
unit: { type: "string", enum: ["c", "f"] },
},
},
}),
},
];
}
private getUserFavoriteCity(): {} {
return { location: "Seattle, WA" };
}
private getCityNickname(_location: string): {} {
return { nickname: "The Emerald City" };
}
private getWeather(_location: string, unit: string): {} {
return { weather: unit === "f" ? "72f" : "22c" };
}
public invokeTool(toolCall: RequiredToolCall & FunctionToolDefinition): ToolOutput | undefined {
console.log(`Function tool call - ${toolCall.function.name}`);
const args: any[] = [];
if (toolCall.function.parameters) {
try {
const params = JSON.parse(toolCall.function.parameters);
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
args.push(params[key]);
}
}
} catch (error) {
console.error(`Failed to parse parameters: ${toolCall.function.parameters}`, error);
return undefined;
}
}
// Create a mapping of function names to their implementations
const functionMap = new Map(
this.functionTools.map((tool) => [tool.definition.function.name, tool.func]),
);
const result = functionMap.get(toolCall.function.name)?.(...args);
return result
? {
toolCallId: toolCall.id,
output: JSON.stringify(result),
}
: {
toolCallId: toolCall.id,
output: JSON.stringify({
error: `No matching tool found for function: ${toolCall.function.name}`,
}),
};
}
public getFunctionDefinitions(): FunctionToolDefinition[] {
return this.functionTools.map((tool) => {
return tool.definition;
});
}
}
const functionToolExecutor = new FunctionToolExecutor();
const functionTools = functionToolExecutor.getFunctionDefinitions();
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions:
"You are a weather bot. Use the provided functions to help answer questions. Customize your responses to the user's preferences as much as possible and use friendly nicknames for cities whenever possible.",
tools: functionTools,
});
console.log(`Created agent, agent ID: ${agent.id}`);
OpenAPI ile Aracı Oluşturma
OpenAPI belirtimleri, belirli bir uç noktaya yönelik REST işlemlerini açıklar. Aracılar SDK'sı bir OpenAPI belirtimini okuyabilir, bu belirtimden bir işlev oluşturabilir ve bu işlevi ek istemci tarafı yürütmesi olmadan REST uç noktasına karşı çağırabilir. Aşağıda bir OpenAPI aracı oluşturma örneği verilmiştir (anonim kimlik doğrulaması kullanılarak):
import { ToolUtility } from "@azure/ai-agents";
// Read in OpenApi spec
const filePath = "./data/weatherOpenApi.json";
const openApiSpec = JSON.parse(fs.readFileSync(filePath, "utf-8"));
// Define OpenApi function
const openApiFunction = {
name: "getWeather",
spec: openApiSpec,
description: "Retrieve weather information for a location",
auth: {
type: "anonymous",
},
default_params: ["format"], // optional
};
// Create OpenApi tool
const openApiTool = ToolUtility.createOpenApiTool(openApiFunction);
// Create agent with OpenApi tool
const agent = await client.createAgent("gpt-4o", {
name: "myAgent",
instructions: "You are a helpful agent",
tools: [openApiTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);
İş Parçacığı Oluştur
Her oturum veya konuşma için bir iş parçacığı gereklidir. Aşağıda bir örnek verilmiştir:
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
Araç Kaynağı ile İş Parçacığı Oluşturma
Bazı senaryolarda, belirli kaynakları tek tek iş parçacıklarına atamanız gerekebilir. Bunu başarmak için toolResourcesiçin threads.create bağımsız değişkenini sağlarsınız. Aşağıdaki örnekte bir vektör deposu oluşturup bir dosyayı karşıya yüklersiniz, tools bağımsız değişkenini kullanarak dosya araması için aracıyı etkinleştirir ve ardından toolResources bağımsız değişkenini kullanarak dosyayı iş parçacığıyla ilişkilendirirsiniz.
import { ToolUtility } from "@azure/ai-agents";
const filePath = "./data/syntheticCompanyQuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const file = await client.files.upload(localFileStream, "assistants", {
fileName: "sample_file_for_upload.csv",
});
console.log(`Uploaded file, ID: ${file.id}`);
const vectorStore = await client.agents.vectorStores.create()({
fileIds: [file.id],
});
console.log(`Created vector store, ID: ${vectorStore.id}`);
const fileSearchTool = ToolUtility.createFileSearchTool([vectorStore.id]);
const agent = await client.agents.createAgent("gpt-4o", {
name: "myAgent",
instructions: "You are helpful agent that can help fetch data from files you know about.",
tools: [fileSearchTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);
// Create thread with file resources.
// If the agent has multiple threads, only this thread can search this file.
const thread = await client.threads.create({ toolResources: fileSearchTool.resources });
İş Parçacıklarını Listele
Belirli bir aracıya bağlı tüm iş parçacıklarını listelemek için şunu kullanın threads.list:
const threads = client.threads.list();
console.log(`Threads for agent ${agent.id}:`);
for await (const t of threads) {
console.log(`Thread ID: ${t.id}`);
console.log(`Created at: ${t.createdAt}`);
console.log(`Metadata: ${t.metadata}`);
console.log(`---- `);
}
İleti Oluştur
Yardımcının işlemesi için bir ileti oluşturmak için, userrole ve bir soruyu contentolarak geçirirsiniz:
const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);
Dosya Arama Eki ile İleti Oluşturma
İçerik arama için bir iletiye dosya eklemek için ToolUtility.createFileSearchTool() ve attachments bağımsız değişkenini kullanırsınız:
import { ToolUtility } from "@azure/ai-agents";
const fileSearchTool = ToolUtility.createFileSearchTool();
const message = await client.messages.create(
thread.id,
"user",
"What feature does Smart Eyewear offer?",
{
attachments: [
{
fileId: file.id,
tools: [fileSearchTool.definition],
},
],
},
);
Kod Yorumlayıcı Eki ile İleti Oluşturma
Veri çözümlemesi için bir iletiye dosya eklemek için ToolUtility.createCodeInterpreterTool() ve attachment bağımsız değişkenini kullanırsınız.
Aşağıda bir örnek verilmiştir:
import { ToolUtility } from "@azure/ai-agents";
// notice that CodeInterpreter must be enabled in the agent creation,
// otherwise the agent will not be able to see the file attachment for code interpretation
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool();
const agent = await client.agents.createAgent("gpt-4o", {
name: "my-assistant",
instructions: "You are helpful assistant",
tools: [codeInterpreterTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
const message = await client.messages.create(
thread.id,
"user",
"Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
{
attachments: [
{
fileId: file.id,
tools: [codeInterpreterTool.definition],
},
],
},
);
console.log(`Created message, message ID: ${message.id}`);
Görüntü Girişleriyle İleti Oluşturma
Görüntü girişleri ile Azure aracılarına aşağıdaki yollarla ileti gönderebilirsiniz:
- Karşıya yüklenen dosya olarak depolanan bir görüntüyü kullanma
- URL aracılığıyla erişilebilen bir genel görüntü kullanma
- Base64 kodlanmış görüntü dizesi kullanma
Aşağıdaki örnekte base64 yöntemi gösterilmektedir:
base64 kodlanmış görüntü girişiyle ileti oluşturma
function imageToBase64DataUrl(imagePath: string, mimeType: string): string {
try {
// Read the image file as binary
const imageBuffer = fs.readFileSync(imagePath);
// Convert to base64
const base64Data = imageBuffer.toString("base64");
// Format as a data URL
return `data:${mimeType};base64,${base64Data}`;
} catch (error) {
console.error(`Error reading image file at ${imagePath}:`, error);
throw error;
}
}
// Convert your image file to base64 format
const filePath = "./data/image_file.png";
const imageDataUrl = imageToBase64DataUrl(filePath, "image/png");
// Create a message with both text and image content
console.log("Creating message with image content...");
const inputMessage = "Hello, what is in the image?";
const content = [
{
type: "text",
text: inputMessage,
},
{
type: "image_url",
imageUrl: {
url: imageDataUrl,
detail: "high",
},
},
];
const message = await client.messages.create(thread.id, "user", content);
console.log(`Created message, message ID: ${message.id}`);
Çalıştırma, Run_and_Process veya Akış Oluşturma
Çalıştırma tamamlanana kadar runs.create ve yoklama örneği aşağıda verilmiştir:
// Create and poll a run
console.log("Creating run...");
const run = await client.runs.createAndPoll(thread.id, agent.id, {
pollingOptions: {
intervalInMs: 2000,
},
onResponse: (response): void => {
console.log(`Received response with status: ${response.parsedBody.status}`);
},
});
console.log(`Run finished with status: ${run.status}`);
SDK'nın sizin yerinize yoklamasını sağlamak için createThreadAndRun yöntemini kullanın.
Aşağıda bir örnek verilmiştir:
const run = await client.runs.createThreadAndRun(agent.id, {
thread: {
messages: [
{
role: "user",
content: "hello, world!",
},
],
},
});
Akışla, yoklamanın da dikkate alınması gerekmez.
Aşağıda bir örnek verilmiştir:
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
Olay işleme aşağıdaki gibi yapılabilir:
import { RunStreamEvent, MessageStreamEvent, ErrorEvent, DoneEvent } from "@azure/ai-agents";
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
console.log(`ThreadRun status: ${eventMessage.data.status}`);
break;
case MessageStreamEvent.ThreadMessageDelta:
{
const messageDelta = eventMessage.data;
messageDelta.delta.content.forEach((contentPart) => {
if (contentPart.type === "text") {
const textContent = contentPart;
const textValue = textContent.text?.value || "No text";
console.log(`Text delta received:: ${textValue}`);
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
console.log("Thread Run Completed");
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
console.log("Stream completed.");
break;
}
}
İletiYi Al
Aracılardan ileti almak için aşağıdaki örneği kullanın:
const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
allMessages.push(m);
}
console.log("Messages:", allMessages);
// The messages are following in the reverse order,
// we will iterate them and output only text contents.
const messages = await client.messages.list(thread.id, {
order: "asc",
});
for await (const dataPoint of messages) {
const textContent = dataPoint.content.find((item) => item.type === "text");
if (textContent && "text" in textContent) {
console.log(`${dataPoint.role}: ${textContent.text.value}`);
}
}
Dosya Al
Aracılar tarafından karşıya yüklenen dosyalar geri alınamaz. Kullanım örneğinizin Aracılar tarafından karşıya yüklenen dosya içeriğine erişmesi gerekiyorsa, uygulamanız tarafından erişilebilen ek bir kopya tutmanız önerilir. Ancak Aracılar tarafından oluşturulan dosyalar files.getContenttarafından alınabilir.
İletilerden dosya kimliklerini alma örneği aşağıda verilmiştir:
import { isOutputOfType, MessageTextContent, MessageImageFileContent } from "@azure/ai-agents";
const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
allMessages.push(m);
}
console.log("Messages:", allMessages);
// Get most recent message from the assistant
const assistantMessage = allMessages.find((msg) => msg.role === "assistant");
if (assistantMessage) {
const textContent = assistantMessage.content.find((content) =>
isOutputOfType<MessageTextContent>(content, "text"),
) as MessageTextContent;
if (textContent) {
console.log(`Last message: ${textContent.text.value}`);
}
}
const imageFile = (allMessages[0].content[0] as MessageImageFileContent).imageFile;
const imageFileName = (await client.agents.files.get(imageFile.fileId)).filename;
const fileContent = await (await client.files.getContent(imageFile.fileId).asNodeStream()).body;
if (fileContent) {
const chunks: Buffer[] = [];
for await (const chunk of fileContent) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const buffer = Buffer.concat(chunks);
fs.writeFileSync(imageFileName, buffer);
} else {
console.error("Failed to retrieve file content: fileContent is undefined");
}
console.log(`Saved image file to: ${imageFileName}`);
Teardown
Görevleri tamamladıktan sonra kaynakları kaldırmak için aşağıdaki işlevleri kullanın:
await client.vectorStores.delete(vectorStore.id);
console.log(`Deleted vector store, vector store ID: ${vectorStore.id}`);
await client.files.delete(file.id);
console.log(`Deleted file, file ID : ${file.id}`);
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);
Sorun giderme
Özel durumlar
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 { RestError } from "@azure/core-rest-pipeline";
try {
const thread = await client.threads.create();
} catch (e) {
if (e instanceof RestError) {
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 kitaplığıyla ilgili sorunları bildirmek veya ek özellikler istemek için lütfen burada bir GitHub sorunu açın
Sonraki Adımlar
Tam olarak çalıştırılabilir kod içeren paket örnekleri klasörüne göz atın.
Katkıda Bulunmak
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 projede Microsoft Açık Kaynak Kullanım Şartları kabul edilmiş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