Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Gunakan pustaka klien AI Agents untuk:
- Mengembangkan Agen menggunakan Azure AI Agent Service, memanfaatkan ekosistem model, alat, dan kemampuan yang luas dari OpenAI, Microsoft, dan penyedia LLM lainnya. Azure AI Agent Service memungkinkan pembuatan Agen untuk berbagai kasus penggunaan AI generatif.
- Nota: Meskipun paket ini dapat digunakan secara independen, sebaiknya gunakan pustaka klien Azure AI Projects untuk pengalaman yang ditingkatkan. Pustaka Proyek menyediakan akses yang disederhanakan ke fungsionalitas lanjutan, seperti membuat dan mengelola agen, menghitung model AI, bekerja dengan himpunan data dan mengelola indeks pencarian, mengevaluasi performa AI generatif, dan mengaktifkan pelacakan OpenTelemetry.
Dokumentasi | produkSampel | Paket (npm) | Dokumentasi referensi API
Daftar isi
- Panduan Memulai
- Konsep Utama
-
Contoh
-
Agen
-
Membuat Agen dengan:
- Pencarian File
- Penerjemah kode
- grounding
Bing - Pencarian AI Azure
- panggilan Fungsi
-
Membuat utas dengan
- sumber daya Alat
- sumber daya Alat
-
Buat pesan dengan:
- lampiran pencarian file
- lampiran penerjemah kode
- Input gambar
- lampiran pencarian file
- Jalankan, Buat Utas dan Jalankan, atau Streaming
- Mengambil pesan
- Mengambil file
- Tear down dengan menghapus sumber daya
-
Membuat Agen dengan:
-
Agen
-
Pemecahan masalah
- Pengecualian
- masalah Pelaporan
- Langkah berikutnya
- Berkontribusi
Memulai Langkah Pertama
Prasyarat
- Versi LTS dari Node.js
- Sebuah langganan Azure.
- Proyek di Azure AI Foundry.
Otorisasi
-
Entra ID diperlukan untuk mengautentikasi klien. Aplikasi Anda memerlukan objek yang mengimplementasikan antarmuka TokenCredential
. Sampel kode di sini menggunakan DefaultAzureCredential. Untuk mendapatkan pekerjaan itu, Anda akan membutuhkan: - Peran
Contributor. Peran yang ditetapkan dapat dilakukan melalui tab "Kontrol Akses (IAM)" sumber daya Proyek Azure AI Anda di portal Microsoft Azure. Pelajari lebih lanjut tentang penetapan peran di sini. - Azure CLI terinstal.
- Anda masuk ke akun Azure Anda dengan menjalankan
az login. - Perhatikan bahwa jika Anda memiliki beberapa langganan Azure, langganan yang berisi sumber daya Proyek Azure AI Anda harus menjadi langganan default Anda. Jalankan
az account list --output tableuntuk mencantumkan semua langganan Anda dan melihat langganan mana yang merupakan default. Jalankanaz account set --subscription "Your Subscription ID or Name"untuk mengubah langganan default Anda.
- Peran
Pasang paketnya
npm install @azure/ai-agents @azure/identity
Konsep utama
Membuat dan mengautentikasi klien
Ini AgentsClient digunakan untuk membangun klien. Saat ini, kami menyarankan Anda menggunakan AgentsClient melalui Pustaka Klien Proyek Azure AI menggunakan client.agents.
Untuk mendapatkan titik akhir proyek Anda, Anda dapat merujuk ke dokumentasi. Di bawah ini kita akan mengasumsikan variabel PROJECT_ENDPOINT lingkungan memegang nilai ini.
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());
Contoh
Agen
Agen di pustaka klien Azure AI Projects dirancang untuk memfasilitasi berbagai interaksi dan operasi dalam proyek AI Anda. Mereka berfungsi sebagai komponen inti yang mengelola dan menjalankan tugas, memanfaatkan alat dan sumber daya yang berbeda untuk mencapai tujuan tertentu. Langkah-langkah berikut menguraikan urutan umum untuk berinteraksi dengan Agen. Lihat sampel paket untuk sampel Agen tambahan.
Buat Agen
Berikut adalah contoh cara membuat Agen:
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful assistant",
});
Untuk mengizinkan Agen mengakses sumber daya atau fungsi kustom, Anda memerlukan alat. Anda dapat meneruskan alat untuk createAgent melalui argumen tools dan toolResources.
Anda dapat menggunakan ToolSet untuk melakukan ini:
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}`);
Beberapa Agen
Anda dapat membuat beberapa Agen dengan alat yang berbeda dan kemudian menghubungkannya bersama-sama.
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}`);
Buat Agen dengan Pencarian File
Untuk melakukan pencarian file oleh Agen, pertama-tama kita perlu mengunggah file, membuat penyimpanan vektor, dan mengaitkan file ke penyimpanan vektor. Berikut adalah contohnya:
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}`);
Buat Agen dengan Penerjemah Kode
Berikut adalah contoh untuk mengunggah file dan menggunakannya untuk penerjemah kode oleh Agen:
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}`);
Buat Agen dengan Bing Grounding
Untuk memungkinkan Agen Anda melakukan pencarian melalui API pencarian Bing, Anda menggunakan ToolUtility.createBingGroundingTool() bersama dengan koneksi. Lihat di sini untuk mempelajari selengkapnya tentang Grounding dengan Pencarian Bing.
Berikut adalah contohnya:
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}`);
Membuat Agen dengan Azure AI Search
Azure AI Search adalah sistem pencarian perusahaan untuk aplikasi berkinerja tinggi. Ini terintegrasi dengan Azure OpenAI Service dan Azure Machine Learning, menawarkan teknologi pencarian canggih seperti pencarian vektor dan pencarian teks lengkap. Ideal untuk wawasan pangkalan pengetahuan, penemuan informasi, dan otomatisasi
Berikut adalah contoh untuk mengintegrasikan Azure AI Search:
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}`);
Buat Agen dengan Panggilan Fungsi
Anda dapat meningkatkan Agen Anda dengan menentukan fungsi panggilan balik sebagai alat fungsi. Ini dapat disediakan untuk createAgent melalui kombinasi tools dan toolResources. Hanya definisi dan deskripsi fungsi yang disediakan untuk createAgent, tanpa implementasi.
Run atau event handler of stream akan menaikkan status requires_action berdasarkan definisi fungsi. Kode Anda harus menangani status ini dan memanggil fungsi yang sesuai.
Berikut adalah contohnya:
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}`);
Buat Agen dengan OpenAPI
Spesifikasi OpenAPI menjelaskan operasi REST terhadap titik akhir tertentu. Agen SDK dapat membaca spesifikasi OpenAPI, membuat fungsi darinya, dan memanggil fungsi tersebut terhadap titik akhir REST tanpa eksekusi sisi klien tambahan. Berikut adalah contoh pembuatan alat OpenAPI (menggunakan autentikasi anonim):
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}`);
Buat Utas
Untuk setiap sesi atau percakapan, utas diperlukan. Berikut adalah contohnya:
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
Buat Utas dengan Sumber Daya Alat
Dalam beberapa skenario, Anda mungkin perlu menetapkan sumber daya tertentu ke utas individual. Untuk mencapai hal ini, Anda memberikan argumen toolResources ke threads.create. Dalam contoh berikut, Anda membuat penyimpanan vektor dan mengunggah file, mengaktifkan Agen untuk pencarian file menggunakan argumen tools, lalu mengaitkan file dengan utas menggunakan argumen toolResources.
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 });
Utas Daftar
Untuk mencantumkan semua utas yang dilampirkan ke agen tertentu, gunakan 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(`---- `);
}
Buat Pesan
Untuk membuat pesan bagi asisten untuk diproses, Anda meneruskan user sebagai role dan pertanyaan sebagai content:
const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);
Buat Pesan dengan Lampiran Pencarian File
Untuk melampirkan file ke pesan untuk pencarian konten, Anda menggunakan ToolUtility.createFileSearchTool() dan argumen attachments:
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],
},
],
},
);
Membuat Pesan dengan Lampiran Penerjemah Kode
Untuk melampirkan file ke pesan untuk analisis data, Anda menggunakan ToolUtility.createCodeInterpreterTool() dan argumen attachment.
Berikut adalah contohnya:
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}`);
Membuat Pesan dengan Input Gambar
Anda dapat mengirim pesan ke agen Azure dengan input gambar dengan cara berikut:
- Menggunakan gambar yang disimpan sebagai file yang diunggah
- Menggunakan gambar publik yang dapat diakses melalui URL
- Menggunakan string gambar yang dikodekan base64
Contoh berikut menunjukkan metode base64:
Membuat pesan dengan input gambar yang dikodekan base64
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}`);
Membuat Jalankan, Run_and_Process, atau Streaming
Berikut adalah contoh runs.create dan polling hingga proses selesai:
// 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}`);
Untuk memiliki polling SDK atas nama Anda, gunakan metode createThreadAndRun.
Berikut adalah contohnya:
const run = await client.runs.createThreadAndRun(agent.id, {
thread: {
messages: [
{
role: "user",
content: "hello, world!",
},
],
},
});
Dengan streaming, polling juga tidak perlu dipertimbangkan.
Berikut adalah contohnya:
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
Penanganan peristiwa dapat dilakukan sebagai berikut:
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;
}
}
Ambil Pesan
Untuk mengambil pesan dari agen, gunakan contoh berikut:
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}`);
}
}
Ambil File
File yang diunggah oleh Agen tidak dapat diambil kembali. Jika kasus penggunaan Anda perlu mengakses konten file yang diunggah oleh Agen, Anda disarankan untuk menjaga salinan tambahan dapat diakses oleh aplikasi Anda. Namun, file yang dihasilkan oleh Agen dapat diambil oleh files.getContent.
Berikut adalah contoh pengambilan id file dari pesan:
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}`);
Pembongkaran
Untuk menghapus sumber daya setelah menyelesaikan tugas, gunakan fungsi berikut:
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}`);
Penyelesaian Masalah
Pengecualian
Metode klien yang melakukan panggilan layanan meningkatkan RestError code pengecualian akan menyimpan kode status respons HTTP.
error.message pengecualian berisi pesan terperinci yang mungkin berguna dalam mendiagnosis masalah:
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);
}
}
Misalnya, saat Anda memberikan kredensial yang salah:
Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'
Melaporkan masalah
Untuk melaporkan masalah dengan pustaka klien, atau meminta fitur tambahan, buka masalah GitHub di sini
Langkah selanjutnya
Lihat folder sampel paket , yang berisi kode yang dapat dijalankan sepenuhnya.
Berpartisipasi
Proyek ini menyambut kontribusi dan saran. Sebagian besar kontribusi mengharuskan Anda menyetujui Perjanjian Lisensi Kontributor (CLA) yang menyatakan bahwa Anda memiliki hak untuk, dan benar-benar melakukannya, memberi kami hak untuk menggunakan kontribusi Anda. Untuk detailnya, kunjungi https://cla.microsoft.com.
Saat Anda mengirimkan permintaan pull, cla-bot akan secara otomatis menentukan apakah Anda perlu memberikan CLA dan menghias PR dengan tepat (misalnya, label, komentar). Cukup ikuti instruksi yang diberikan oleh bot. Anda hanya perlu melakukan ini sekali di semua repositori menggunakan CLA kami.
Proyek ini telah mengadopsi Kode Etik Sumber Terbuka Microsoft. Untuk informasi selengkapnya, lihat Tanya Jawab Umum Kode Etik atau hubungi opencode@microsoft.com dengan pertanyaan atau komentar tambahan.
Azure SDK for JavaScript