次の方法で共有


JavaScript 用 Azure AI Agents クライアント ライブラリ - バージョン 1.0.0-beta.4

AI Agents クライアント ライブラリを使用して、次のことを行います。

  • Azure AI Agent Serviceを使用してエージェントを開発し、OpenAI、Microsoft、およびその他の LLM プロバイダーからのモデル、ツール、機能の広範なエコシステムを活用します。 Azure AI エージェント サービスを使用すると、さまざまな生成 AI ユース ケースに対してエージェントを構築できます。
  • 手記: このパッケージは単独で使用できますが、エクスペリエンスを向上させるために Azure AI Projects クライアント ライブラリ を使用することをお勧めします。 Projects ライブラリを使用すると、エージェントの作成と管理、AI モデルの列挙、データセットの操作と検索インデックスの管理、生成 AI パフォーマンスの評価、OpenTelemetry トレースの有効化などの高度な機能に簡単にアクセスできます。

製品ドキュメント | サンプル | パッケージ(npm) | API リファレンス ドキュメント

目次

作業の開始

前提条件

認証

  • Entra ID は、クライアントを認証するために必要です。 アプリケーションには、TokenCredential インターフェイスを実装するオブジェクトが必要です。 ここでのコード サンプルでは、DefaultAzureCredential使用します。 この作業を行うには、次のものが必要です。
    • Contributor ロール。 割り当てられたロールは、Azure portal の Azure AI プロジェクト リソースの [アクセス制御 (IAM)]タブを使用して実行できます。 ロールの割り当ての詳細については 、こちらをご覧ください
    • Azure CLI インストール
    • az loginを実行して、Azure アカウントにログインします。
    • 複数の Azure サブスクリプションがある場合は、Azure AI Project リソースを含むサブスクリプションが既定のサブスクリプションである必要があることに注意してください。 az account list --output table 実行して、すべてのサブスクリプションを一覧表示し、既定のサブスクリプションを確認します。 az account set --subscription "Your Subscription ID or Name" を実行して、既定のサブスクリプションを変更します。

パッケージをインストールする

npm install @azure/ai-agents @azure/identity

重要な概念

クライアントを作成して認証する

AgentsClientは、クライアントの構築に使用されます。 現時点では、 を使用して client.agentsを通じて AgentsClient を使用することをお勧めします。

プロジェクトのエンドポイントを取得するには、次のドキュメントを参照してください: azure_foundry_service_endpoint. 以下では、環境変数 PROJECT_ENDPOINT がこの値を保持するように定義されていると仮定します。

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());

例示

エージェント

Azure AI Projects クライアント ライブラリのエージェントは、AI プロジェクト内のさまざまな対話と操作を容易にするように設計されています。 タスクを管理および実行するコア コンポーネントとして機能し、さまざまなツールとリソースを活用して特定の目標を達成します。 次の手順では、エージェントと対話するための一般的なシーケンスについて説明します。 その他のエージェント・サンプルについては、 パッケージ・サンプル を参照してください。

エージェントの作成

エージェントを作成する方法の例を次に示します。

const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful assistant",
});

エージェントがリソースまたはカスタム関数にアクセスできるようにするには、ツールが必要です。 createAgent 引数と tools 引数を使用して toolResources するツールを渡すことができます。

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}`);

エージェントによるファイル検索を実行するには、まずファイルをアップロードし、ベクター ストアを作成し、そのファイルをベクター ストアに関連付ける必要があります。 次に例を示します。

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}`);

コード インタープリターを使用してエージェントを作成する

ファイルをアップロードし、エージェントによるコード インタープリターに使用する例を次に示します。

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 Grounding を使用してエージェントを作成する

エージェントが検索 API を使用して検索Bing実行できるようにするには、接続と共に ToolUtility.createBingGroundingTool() を使用します。 Bing Search を使用した接地の詳細については、 こちら を参照してください。

次に例を示します。

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 は、高パフォーマンス アプリケーション用のエンタープライズ検索システムです。 Azure OpenAI Service および Azure Machine Learning と統合され、ベクター検索やフルテキスト検索などの高度な検索テクノロジが提供されます。 ナレッジ ベースの分析情報、情報の検出、自動化に最適

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}`);

関数呼び出しを使用してエージェントを作成する

コールバック関数を関数ツールとして定義することで、エージェントを拡張できます。 これらは、createAgenttoolsの組み合わせを介して toolResources に提供することができます. createAgentには、実装なしで関数の定義と説明のみが提供されます。 Run または event handler of stream では、関数定義に基づいて requires_action 状態が発生します。 コードでこの状態を処理し、適切な関数を呼び出す必要があります。

次に例を示します。

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 を使用してエージェントを作成する

OpenAPI 仕様では、特定のエンドポイントに対する REST 操作について説明します。 Agents SDK は、OpenAPI 仕様を読み取り、そこから関数を作成し、追加のクライアント側実行なしで REST エンドポイントに対してその関数を呼び出すことができます。 OpenAPI ツールを作成する例を次に示します (匿名認証を使用)。

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}`);

Fabric を使用してエージェントを作成する

エージェントが Fabric データを使用してクエリに応答できるようにするには、FabricTool と Fabric リソースへの接続を使用します。

次に例を示します。

import { ToolUtility } from "@azure/ai-agents";

const connectionId = process.env["FABRIC_CONNECTION_ID"] || "<connection-name>";

// Initialize agent Microsoft Fabric tool with the connection id
const fabricTool = ToolUtility.createFabricTool(connectionId);

// Create agent with the Microsoft Fabric tool and process assistant run
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [fabricTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);

スレッドの作成

セッションまたは会話ごとに、スレッドが必要です。 次に例を示します。

const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);

ツール リソースを使用してスレッドを作成する

シナリオによっては、個々のスレッドに特定のリソースを割り当てる必要がある場合があります。 これを実現するには、toolResourcesthreads.create 引数を指定します。 次の例では、ベクター ストアを作成してファイルをアップロードし、tools 引数を使用してエージェントでファイル検索を有効にしてから、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 });

スレッドの一覧表示

特定のエージェントに接続されているすべてのスレッドを一覧表示するには、次の 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(`---- `);
}

メッセージの作成

アシスタントが処理するメッセージを作成するには、userrole として渡し、質問を contentとして渡します。

const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);

ファイル検索添付ファイルを含むメッセージを作成する

コンテンツ検索用のメッセージにファイルを添付するには、ToolUtility.createFileSearchTool() 引数と 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],
      },
    ],
  },
);

コード インタープリター添付ファイルを含むメッセージを作成する

データ分析のためにファイルをメッセージに添付するには、ToolUtility.createCodeInterpreterTool()attachment 引数を使用します。

次に例を示します。

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}`);

イメージ入力を含むメッセージを作成する

イメージ入力を使用して Azure エージェントにメッセージを送信するには、次の方法があります。

  • アップロードされたファイルとして保存されたイメージの使用
  • URL 経由でアクセス可能なパブリック イメージの使用
  • base64 でエンコードされたイメージ文字列の使用

次の例は、base64 メソッドを示しています。

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",
    image_url: {
      url: imageDataUrl,
      detail: "high",
    },
  },
];

const message = await client.messages.create(thread.id, "user", content);
console.log(`Created message, message ID: ${message.id}`);

実行、Run_and_Process、またはストリームの作成

実行が完了するまでの runs.create とポーリングの例を次に示します。

// 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 をポーリングするには、createThreadAndRun メソッドを使用します。

次に例を示します。

const run = await client.runs.createThreadAndRun(agent.id, {
  thread: {
    messages: [
      {
        role: "user",
        content: "hello, world!",
      },
    ],
  },
});

ストリーミングでは、ポーリングも考慮する必要はありません。

次に例を示します。

const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();

イベント処理は次のように実行できます。

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;
  }
}

メッセージの取得

エージェントからメッセージを取得するには、次の例を使用します。

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}`);
  }
}

ファイルの取得

エージェントによってアップロードされたファイルを取得することはできません。 ユース ケースがエージェントによってアップロードされたファイル コンテンツにアクセスする必要がある場合は、アプリケーションからアクセス可能な追加のコピーを保持することをお勧めします。 ただし、エージェントによって生成されたファイルは、files.getContentで取得できます。

メッセージからファイル ID を取得する例を次に示します。

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}`);

分解

タスクの完了後にリソースを削除するには、次の関数を使用します。

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}`);

トラブルシューティング

例外

サービス呼び出しを行うクライアント メソッドは、サービスからの成功しない HTTP 状態コード応答に対して、RestError を発生させます。 例外の code は、HTTP 応答状態コードを保持します。 例外の error.message には、問題の診断に役立つ詳細なメッセージが含まれています。

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);
  }
}

たとえば、間違った資格情報を指定した場合は、次のようになります。

Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'

問題の報告

クライアント ライブラリに関する問題を報告したり、追加機能を要求したりするには、 で GitHub の問題 開いてください

次のステップ

完全に実行可能なコードを含むフォルダー パッケージのサンプルを確認してください。

投稿

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの投稿では、お客様が投稿を使用する権利を当社に付与する権利を有し、実際に行うことを宣言する共同作成者ライセンス契約 (CLA) に同意する必要があります。 詳細については、https://cla.microsoft.comを参照してください。

プル要求を送信すると、CLA ボットは、CLA を提供し、PR を適切に装飾する必要があるかどうかを自動的に判断します (ラベル、コメントなど)。 ボットによって提供される手順にそのまま従ってください。 これは、CLA を使用するすべてのリポジトリで 1 回だけ行う必要があります。

このプロジェクトは、「Microsoft のオープン ソースの倫理規定」を採用しています。 詳細については、行動規範に関する FAQ を参照するか、その他の質問やコメントを opencode@microsoft.com にお問い合わせください。