Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Utilizza la libreria client di AI Agents per:
- Sviluppare agenti usando il servizio Azure AI Agent, sfruttando un ampio ecosistema di modelli, strumenti e funzionalità di OpenAI, Microsoft e altri provider LLM. Il servizio Agente di intelligenza artificiale di Azure consente la creazione di agenti per un'ampia gamma di casi d'uso generativi di intelligenza artificiale.
- Nota: Anche se questo pacchetto può essere usato in modo indipendente, è consigliabile usare la libreria client di Progetti di intelligenza artificiale di Azure per un'esperienza migliorata. La libreria Progetti offre un accesso semplificato a funzionalità avanzate, come la creazione e la gestione di agenti, l'enumerazione di modelli di intelligenza artificiale, l'uso di set di dati e la gestione degli indici di ricerca, la valutazione delle prestazioni dell'intelligenza artificiale generativa e l'abilitazione della traccia OpenTelemetry.
Documentazione del | prodottoCampioni | Pacchetto (npm) | Documentazione di riferimento API
Sommario
- Introduzione
- Concetti principali
-
Esempi
-
Agenti
- Creare un agente con:
-
Creare thread con
- risorsa strumento di
- risorsa strumento di
- Creare messaggi con:
- esegui esecuzione, creazione di thread ed esecuzione o di flusso
- Recuperare messaggio
- Recuperare file
- Eliminare l'eliminazione di di risorse
-
Agenti
- Risoluzione dei problemi
- contributi
Come iniziare
Prerequisito
- Versioni LTS di Node.js
- Una sottoscrizione di Azure.
- Un progetto di in Azure AI Foundry.
Autorizzazione
-
L'ID Entra è necessario per autenticare il client. L'applicazione necessita di un oggetto che implementa l'interfaccia token
. Gli esempi di codice qui usano DefaultAzureCredential. Per ottenere questo lavoro, è necessario: - Ruolo
Contributor. Il ruolo assegnato può essere eseguito tramite la scheda "Controllo di accesso (IAM)" della risorsa progetto di Intelligenza artificiale di Azure nel portale di Azure. Scopri di più sulle assegnazioni di ruolo qui. - installato dell'interfaccia della riga di comando di Azure.
- Si è connessi all'account Azure eseguendo
az login. - Si noti che se si dispone di più sottoscrizioni di Azure, la sottoscrizione che contiene la risorsa del progetto di intelligenza artificiale di Azure deve essere la sottoscrizione predefinita. Eseguire
az account list --output tableper elencare tutte le sottoscrizioni e vedere quale è l'impostazione predefinita. Eseguireaz account set --subscription "Your Subscription ID or Name"per modificare la sottoscrizione predefinita.
- Ruolo
Installare il pacchetto
npm install @azure/ai-agents @azure/identity
Concetti chiave
Creare ed autenticare il client
Viene AgentsClient utilizzato per costruire il client. Attualmente, è consigliabile usare AgentsClient tramite la libreria client di Azure AI Projects usando client.agents.
Per ottenere l'endpoint del progetto, è possibile fare riferimento alla documentazione. Di seguito assumeremo che la variabile PROJECT_ENDPOINT d'ambiente mantenga questo valore.
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());
Esempi
Agenti
Gli agenti nella libreria client di Azure AI Projects sono progettati per facilitare varie interazioni e operazioni all'interno dei progetti di intelligenza artificiale. Fungono da componenti di base che gestiscono ed eseguono attività, sfruttando diversi strumenti e risorse per raggiungere obiettivi specifici. I passaggi seguenti descrivono la sequenza tipica per l'interazione con gli agenti. Per altri esempi di agente, vedere gli esempi di pacchetto .
Creare un agente
Ecco un esempio di come creare un agente:
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful assistant",
});
Per consentire agli agenti di accedere alle risorse o alle funzioni personalizzate, sono necessari strumenti. È possibile passare strumenti a createAgent tramite gli argomenti tools e toolResources.
A tale scopo, è possibile usare ToolSet:
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}`);
Agenti multipli
Puoi creare più agenti con strumenti diversi e poi collegarli insieme.
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}`);
Creare un agente con Ricerca file
Per eseguire la ricerca di file da un agente, è prima necessario caricare un file, creare un archivio vettoriale e associare il file all'archivio vettoriale. Ecco un esempio:
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}`);
Creare un agente con interprete del codice
Di seguito è riportato un esempio per caricare un file e usarlo per l'interprete di codice da un agente:
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}`);
Creare un agente con Bing Grounding
Per consentire all'agente di eseguire la ricerca tramite l'API di ricerca Bing, usare ToolUtility.createBingGroundingTool() insieme a una connessione. Per altre informazioni sulla messa a terra con Bing Search, vedere qui .
Ecco un esempio:
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}`);
Creare un agente con Ricerca intelligenza artificiale di Azure
Ricerca di intelligenza artificiale di Azure è un sistema di ricerca aziendale per applicazioni ad alte prestazioni. Si integra con il servizio Azure OpenAI e Azure Machine Learning, offrendo tecnologie di ricerca avanzate come la ricerca vettoriale e la ricerca full-text. Ideale per informazioni dettagliate, individuazione delle informazioni e automazione delle informazioni
Di seguito è riportato un esempio per integrare Ricerca intelligenza artificiale di Azure:
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}`);
Creare un agente con chiamata di funzione
È possibile migliorare gli agenti definendo le funzioni di callback come strumenti per le funzioni. Questi elementi possono essere forniti per createAgent tramite la combinazione di tools e toolResources. Solo le definizioni e le descrizioni delle funzioni vengono fornite per createAgent, senza le implementazioni. Il Run o event handler of stream genererà uno stato requires_action in base alle definizioni di funzione. Il codice deve gestire questo stato e chiamare le funzioni appropriate.
Ecco un esempio:
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}`);
Creare un agente con OpenAPI
Le specifiche OpenAPI descrivono le operazioni REST su un endpoint specifico. Agents SDK può leggere una specifica OpenAPI, creare una funzione da essa e chiamare tale funzione sull'endpoint REST senza eseguire aggiuntive sul lato client. Di seguito è riportato un esempio di creazione di uno strumento OpenAPI (usando l'autenticazione anonima):
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}`);
Crea thread
Per ogni sessione o conversazione, è necessario un thread. Ecco un esempio:
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
Creare un thread con una risorsa strumento
In alcuni scenari potrebbe essere necessario assegnare risorse specifiche a singoli thread. A tale scopo, specificare l'argomento toolResources per threads.create. Nell'esempio seguente si crea un archivio vettoriale e si carica un file, si abilita un agente per la ricerca di file usando l'argomento tools e quindi si associa il file al thread usando l'argomento 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 });
Elencare i thread
Per elencare tutti i thread collegati a un determinato agente, utilizzare 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(`---- `);
}
Crea messaggio
Per creare un messaggio per l'assistente da elaborare, passare user come role e una domanda come content:
const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);
Creare un messaggio con l'allegato di ricerca file
Per allegare un file a un messaggio per la ricerca di contenuto, usare ToolUtility.createFileSearchTool() e l'argomento 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],
},
],
},
);
Creare un messaggio con allegato dell'interprete del codice
Per allegare un file a un messaggio per l'analisi dei dati, usare ToolUtility.createCodeInterpreterTool() e l'argomento attachment.
Ecco un esempio:
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}`);
Creare un messaggio con input immagine
È possibile inviare messaggi agli agenti di Azure con input di immagine nei modi seguenti:
- Uso di un'immagine archiviata come file caricato
- Uso di un'immagine pubblica accessibile tramite URL
- Uso di una stringa di immagine con codifica Base64
Nell'esempio seguente viene illustrato il metodo base64:
Creare un messaggio con input immagine con codifica 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}`);
Creare run, Run_and_Process o stream
Di seguito è riportato un esempio di runs.create e polling fino al completamento dell'esecuzione:
// 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}`);
Per fare in modo che l'SDK esegua il polling per conto dell'SDK, usare il metodo createThreadAndRun.
Ecco un esempio:
const run = await client.runs.createThreadAndRun(agent.id, {
thread: {
messages: [
{
role: "user",
content: "hello, world!",
},
],
},
});
Con lo streaming, non è necessario considerare anche il polling.
Ecco un esempio:
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
La gestione degli eventi può essere eseguita nel modo seguente:
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;
}
}
Recupera messaggio
Per recuperare i messaggi dagli agenti, usare l'esempio seguente:
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}`);
}
}
Recupera file
Impossibile recuperare i file caricati dagli agenti. Se il caso d'uso deve accedere al contenuto del file caricato dagli agenti, è consigliabile mantenere una copia aggiuntiva accessibile dall'applicazione. Tuttavia, i file generati dagli agenti sono recuperabili da files.getContent.
Di seguito è riportato un esempio di recupero di ID file dai messaggi:
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
Per rimuovere le risorse dopo il completamento delle attività, usare le funzioni seguenti:
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}`);
Risoluzione dei problemi
Eccezioni
I metodi client che effettuano chiamate al servizio generano un RestError per una risposta di codice di stato HTTP non riuscita dal servizio. Il code dell'eccezione conterrà il codice di stato della risposta HTTP. L'error.message dell'eccezione contiene un messaggio dettagliato che può essere utile per diagnosticare il problema:
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);
}
}
Ad esempio, quando si specificano credenziali errate:
Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'
Segnalazione di problemi
Per segnalare problemi con la libreria client o richiedere funzionalità aggiuntive, aprire un problema di GitHub qui
Passaggi successivi
Esaminare la cartella degli esempi di pacchetti contenente codice completamente eseguibile.
Contribuire
Questo progetto accoglie contributi e suggerimenti. La maggior parte dei contributi richiede l'accettazione di un Contratto di licenza collaboratore (CLA) che dichiara di avere il diritto e, in realtà, concedere a Microsoft i diritti per l'uso del contributo. Per informazioni dettagliate, visitare https://cla.microsoft.com.
Quando si invia una richiesta pull, un bot CLA determinerà automaticamente se è necessario fornire un cla e decorare la richiesta pull in modo appropriato (ad esempio, etichetta, commento). Seguire semplicemente le istruzioni fornite dal bot. Dovrai eseguire questa operazione una sola volta in tutti i repository usando la nostra cla.
Questo progetto ha adottato il codice di comportamento open source Microsoft. Per altre informazioni, vedere domande frequenti sul codice di condotta o contattare opencode@microsoft.com con eventuali domande o commenti aggiuntivi.
Azure SDK for JavaScript