Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Use a biblioteca de cliente do AI Agents para:
- Desenvolva agentes usando o Azure AI Agent Service, aproveitando um extenso ecossistema de modelos, ferramentas e recursos da OpenAI, Microsoft e outros provedores de LLM. O Serviço de Agente de IA do Azure permite a criação de Agentes para uma ampla gama de casos de uso de IA generativa.
- Observação: Embora este pacote possa ser usado independentemente, recomendamos usar a biblioteca de cliente do Azure AI Projects para uma experiência aprimorada. A biblioteca de projetos fornece acesso simplificado a funcionalidades avançadas, como criar e gerenciar agentes, enumerar modelos de IA, trabalhar com conjuntos de dados e gerenciar índices de pesquisa, avaliar o desempenho de IA generativa e habilitar o rastreamento OpenTelemetria.
Documentação | do produtoAmostras | Pacote (npm) | Documentação de referência da API
Índice
- Primeiros passos
- Conceitos-chave
-
Exemplos
-
Agentes
-
Criar um agente com:
- Pesquisa de Ficheiros
- Interpretador de código
- Aterramento do Bing
- Azure AI Search
- de chamada de função
-
Criar thread com
- de recursos da ferramenta
- de recursos da ferramenta
-
Criar mensagem com:
- de anexos de pesquisa de ficheiros
- de anexo do interpretador de código
- Entrada de imagem
- executar executar, criar thread e executar ou transmitir
- Recuperar mensagem
- Recuperar arquivo
- Derrubar excluindo de recursos
-
Criar um agente com:
-
Agentes
- Resolução de problemas
- Contribuindo
Como Começar
Pré-requisito
- Versões LTS do Node.js
- Uma assinatura do Azure.
- Um projeto no Azure AI Foundry.
Autorização
-
O Entra ID é necessário para autenticar o cliente. Seu aplicativo precisa de um objeto que implemente o TokenCredential interface. Os exemplos de código aqui usam DefaultAzureCredential. Para que isso funcione, você precisará de:
- O
Contributorpapel. A função atribuída pode ser feita por meio da guia "Controle de Acesso (IAM)" do seu recurso do Projeto Azure AI no portal do Azure. Saiba mais sobre as atribuições de função aqui. - CLI do Azure instalada.
- Você está conectado à sua conta do Azure executando
az login. - Observe que, se você tiver várias assinaturas do Azure, a assinatura que contém seu recurso do Azure AI Project deve ser sua assinatura padrão. Execute
az account list --output tablepara listar todas as suas assinaturas e ver qual é a padrão. Executeaz account set --subscription "Your Subscription ID or Name"para alterar sua assinatura padrão.
- O
Instale o pacote
npm install @azure/ai-agents @azure/identity
Conceitos-chave
Criar e autenticar o cliente
O AgentsClient é usado para construir o cliente. Atualmente, recomendamos que você use o AgentsClient por meio da Biblioteca de Cliente de Projetos de IA do Azure usando client.agentso .
Para obter o ponto final do seu projeto, você pode consultar a documentação. Abaixo, assumiremos que a variável PROJECT_ENDPOINT de ambiente detém esse valor.
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());
Exemplos
Agentes
Os agentes na biblioteca de cliente de Projetos de IA do Azure são projetados para facilitar várias interações e operações em seus projetos de IA. Eles servem como os principais componentes que gerenciam e executam tarefas, alavancando diferentes ferramentas e recursos para atingir objetivos específicos. As etapas a seguir descrevem a sequência típica para interagir com agentes. Consulte os exemplos de pacote para obter amostras adicionais do Agente.
Criar agente
Aqui está um exemplo de como criar um agente:
const agent = await client.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful assistant",
});
Para permitir que os agentes acessem seus recursos ou funções personalizadas, você precisa de ferramentas. Você pode passar ferramentas para createAgent através do tools e toolResources argumentos.
Você pode usar ToolSet para fazer isso:
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}`);
Vários agentes
Você pode criar vários agentes com ferramentas diferentes e, em seguida, conectá-los juntos.
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}`);
Criar agente com pesquisa de arquivo
Para realizar a pesquisa de arquivos por um Agente, primeiro precisamos carregar um arquivo, criar um repositório vetorial e associar o arquivo ao repositório vetorial. Aqui está um exemplo:
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}`);
Criar agente com o interpretador de código
Aqui está um exemplo para carregar um arquivo e usá-lo para interpretador de código por um 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}`);
Criar agente com o Bing Grounding
Para permitir que seu Agente realize pesquisas por meio da API de pesquisa do Bing, use ToolUtility.createBingGroundingTool() juntamente com uma conexão. Veja aqui para saber mais sobre o Aterramento com a Pesquisa do Bing.
Aqui está um exemplo:
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}`);
Criar agente com o Azure AI Search
O Azure AI Search é um sistema de pesquisa empresarial para aplicações de alto desempenho. Integra-se com o Serviço OpenAI do Azure e o Azure Machine Learning, oferecendo tecnologias de pesquisa avançadas, como pesquisa vetorial e pesquisa de texto completo. Ideal para insights da base de conhecimento, descoberta de informações e automação
Aqui está um exemplo para integrar o 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}`);
Criar agente com chamada de função
Você pode aprimorar seus agentes definindo funções de retorno de chamada como ferramentas de função. Estes podem ser fornecidos aos createAgent através da combinação de tools e toolResources. Apenas as definições de função e descrições são fornecidas para createAgent, sem as implementações. O Run ou event handler of stream elevará um status de requires_action com base nas definições de função. Seu código deve lidar com esse status e chamar as funções apropriadas.
Aqui está um exemplo:
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}`);
Criar agente com OpenAPI
As especificações OpenAPI descrevem operações REST em relação a um ponto de extremidade específico. O SDK dos agentes pode ler uma especificação OpenAPI, criar uma função a partir dela e chamar essa função no ponto de extremidade REST sem execução adicional do lado do cliente. Aqui está um exemplo de criação de uma ferramenta OpenAPI (usando autenticação anônima):
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}`);
Criar thread
Para cada sessão ou conversa, é necessário um tópico. Aqui está um exemplo:
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
Criar thread com recurso de ferramenta
Em alguns cenários, talvez seja necessário atribuir recursos específicos a threads individuais. Para conseguir isso, você fornece o argumento toolResources para threads.create. No exemplo a seguir, você cria um armazenamento de vetores e carrega um arquivo, habilita um Agent para pesquisa de arquivos usando o argumento tools e, em seguida, associa o arquivo ao thread usando o argumento 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 });
Listar tópicos
Para listar todos os threads anexados a um determinado agente, use 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(`---- `);
}
Criar mensagem
Para criar uma mensagem para o assistente processar, passe user como role e uma pergunta como content:
const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);
Criar mensagem com anexo de pesquisa de arquivo
Para anexar um arquivo a uma mensagem para pesquisa de conteúdo, use ToolUtility.createFileSearchTool() e o attachments argumento:
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],
},
],
},
);
Criar mensagem com anexo do interpretador de código
Para anexar um arquivo a uma mensagem para análise de dados, use ToolUtility.createCodeInterpreterTool() e o argumento attachment.
Aqui está um exemplo:
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}`);
Criar mensagem com entradas de imagem
Você pode enviar mensagens para agentes do Azure com entradas de imagem das seguintes maneiras:
- Usando uma imagem armazenada como um arquivo carregado
- Utilizar uma imagem pública acessível através de URL
- Usando uma cadeia de caracteres de imagem codificada em base64
O exemplo a seguir demonstra o método base64:
Criar mensagem com entrada de imagem codificada em 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}`);
Criar Run, Run_and_Process ou Stream
Aqui está um exemplo de runs.create e sondagem até que a execução seja concluída:
// 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}`);
Para ter a pesquisa SDK em seu nome, use o método createThreadAndRun.
Aqui está um exemplo:
const run = await client.runs.createThreadAndRun(agent.id, {
thread: {
messages: [
{
role: "user",
content: "hello, world!",
},
],
},
});
Com o streaming, as sondagens também não precisam de ser consideradas.
Aqui está um exemplo:
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
A manipulação de eventos pode ser feita da seguinte forma:
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;
}
}
Recuperar mensagem
Para recuperar mensagens de agentes, use o seguinte exemplo:
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}`);
}
}
Recuperar arquivo
Os ficheiros carregados pelos agentes não podem ser recuperados. Se o seu caso de uso precisar acessar o conteúdo do arquivo carregado pelos agentes, você é aconselhado a manter uma cópia adicional acessível pelo seu aplicativo. No entanto, os arquivos gerados pelos agentes podem ser recuperados pelo files.getContent.
Aqui está um exemplo de recuperação de ids de arquivo de mensagens:
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}`);
Demolição
Para remover recursos depois de concluir tarefas, use as seguintes funções:
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}`);
Solução de problemas
Exceções
Os métodos de cliente que fazem chamadas de serviço geram um RestError code da exceção manterá o código de status da resposta HTTP. O error.message da exceção contém uma mensagem detalhada que pode ser útil no diagnóstico do 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);
}
}
Por exemplo, quando você fornece credenciais erradas:
Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'
Comunicar problemas
Para relatar problemas com a biblioteca do cliente ou solicitar recursos adicionais, abra um problema do GitHub aqui
Próximos passos
Dê uma olhada nos exemplos de pacote pasta, contendo código totalmente executável.
Contribuir
Este projeto acolhe contribuições e sugestões. A maioria das contribuições exige que você concorde com um Contrato de Licença de Colaborador (CLA) declarando que você tem o direito de, e realmente concede, os direitos de usar sua contribuição. Para mais detalhes, visite https://cla.microsoft.com.
Quando você envia uma solicitação pull, um CLA-bot determinará automaticamente se você precisa fornecer um CLA e decorar o PR adequadamente (por exemplo, rótulo, comentário). Basta seguir as instruções fornecidas pelo bot. Você só precisará fazer isso uma vez em todos os repositórios usando nosso CLA.
Este projeto adotou o Código de Conduta Open Source da Microsoft. Para obter mais informações, consulte as Perguntas frequentes sobre o Código de Conduta ou entre em contato com opencode@microsoft.com com quaisquer perguntas ou comentários adicionais.
Azure SDK for JavaScript