Community画像github.com

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET。Azure OpenAIおよびOpenAIサービスのクライアントライブラリ。チャット補完、埋め込み、画像生成、音声文字起こし、アシスタントに使用します。

azure-ai-openai-dotnet とは?

このスキルは、.NET アプリケーションから Azure OpenAI サービスにアクセスするための公式 SDK です。GPT-4、GPT-4o、埋め込み、DALL-E、Whisper などの高度な AI モデルを統合し、チャット補完、構造化出力、RAG(検索拡張生成)、関数呼び出し、画像生成、音声処理をサポートします。主に対応するプラットフォームは Azure OpenAI Service で、OpenAI との互換性も提供します。インストールは NuGet パッケージ `Azure.AI.OpenAI` を使用し、認証には API キーまたは Microsoft Entra ID(推奨)が使えます。この SKILL.md には、クライアント階層、認証方法、各機能の使用例、ベストプラクティスが詳述されており、開発者はこれを基に迅速に実装を開始できます。

対応~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-openai-dotnet

Installed? Explore more 画像 skills: steipete/songsee, affaan-m/frontend-design, mattpocock/improve-codebase-architecture · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Azure.AI.OpenAI (.NET)

Azure OpenAI サービス用のクライアントライブラリ。GPT-4、GPT-4o、埋め込み、DALL-E、Whisper などの OpenAI モデルにアクセスできます。

インストール

dotnet add package Azure.AI.OpenAI

# OpenAI (非Azure) との互換性のために
# dotnet add package OpenAI

現在のバージョン: 2.1.0 (安定版)

環境変数

AZURE_OPENAI_ENDPOINT=https://<リソース名>.openai.azure.com  # 必須: Azure OpenAI エンドポイント
AZURE_OPENAI_API_KEY=<api-key>  # AzureKeyCredential 認証の場合のみ必須
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini  # 必須: モデルデプロイ名
AZURE_TOKEN_CREDENTIALS=prod  # 本番環境で DefaultAzureCredential を使用する場合のみ必須

クライアント階層

AzureOpenAIClient (トップレベル)
├── GetChatClient(deploymentName)      → ChatClient
├── GetEmbeddingClient(deploymentName) → EmbeddingClient
├── GetImageClient(deploymentName)     → ImageClient
├── GetAudioClient(deploymentName)     → AudioClient
└── GetAssistantClient()               → AssistantClient

認証

API キー認証

using Azure;
using Azure.AI.OpenAI;

AzureOpenAIClient client = new(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
    new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!));

Microsoft Entra トークン資格情報

using Azure.Identity;
using Azure.AI.OpenAI;

// ローカル開発: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// または本番環境で特定の資格情報を直接使用:
// https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
AzureOpenAIClient client = new(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
    credential);

Azure で OpenAI SDK を直接使用

using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;

#pragma warning disable OPENAI001

BearerTokenPolicy tokenPolicy = new(
    new DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default");

ChatClient client = new(
    model: "gpt-4o-mini",
    authenticationPolicy: tokenPolicy,
    options: new OpenAIClientOptions()
    {
        Endpoint = new Uri("https://YOUR-RESOURCE.openai.azure.com/openai/v1")
    });

チャット補完

基本チャット

using Azure.AI.OpenAI;
using OpenAI.Chat;

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new DefaultAzureCredential());

ChatClient chatClient = azureClient.GetChatClient("gpt-4o-mini");

ChatCompletion completion = chatClient.CompleteChat(
[
    new SystemChatMessage("あなたは親切なアシスタントです。"),
    new UserChatMessage("Azure OpenAI とは何ですか?")
]);

Console.WriteLine(completion.Content[0].Text);

非同期チャット

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new SystemChatMessage("あなたは親切なアシスタントです。"),
    new UserChatMessage("クラウドコンピューティングを簡単な言葉で説明してください。")
]);

Console.WriteLine($"応答: {completion.Content[0].Text}");
Console.WriteLine($"使用トークン数: {completion.Usage.TotalTokenCount}");

ストリーミングチャット

await foreach (StreamingChatCompletionUpdate update 
    in chatClient.CompleteChatStreamingAsync(messages))
{
    if (update.ContentUpdate.Count > 0)
    {
        Console.Write(update.ContentUpdate[0].Text);
    }
}

オプション付きチャット

ChatCompletionOptions options = new()
{
    MaxOutputTokenCount = 1000,
    Temperature = 0.7f,
    TopP = 0.95f,
    FrequencyPenalty = 0,
    PresencePenalty = 0
};

ChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);

マルチターン会話

List<ChatMessage> messages = new()
{
    new SystemChatMessage("あなたは親切なアシスタントです。"),
    new UserChatMessage("こんにちは、手伝ってくれますか?"),
    new AssistantChatMessage("もちろんです!何をお手伝いしましょうか?"),
    new UserChatMessage("フランスの首都はどこですか?")
};

ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
messages.Add(new AssistantChatMessage(completion.Content[0].Text));

構造化出力 (JSON スキーマ)

using System.Text.Json;

ChatCompletionOptions options = new()
{
    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
        jsonSchemaFormatName: "math_reasoning",
        jsonSchema: BinaryData.FromBytes("""
            {
                "type": "object",
                "properties": {
                    "steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "explanation": { "type": "string" },
                                "output": { "type": "string" }
                            },
                            "required": ["explanation", "output"],
                            "additionalProperties": false
                        }
                    },
                    "final_answer": { "type": "string" }
                },
                "required": ["steps", "final_answer"],
                "additionalProperties": false
            }
            """u8.ToArray()),
        jsonSchemaIsStrict: true)
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("8x + 7 = -23 をどうやって解きますか?")],
    options);

using JsonDocument json = JsonDocument.Parse(completion.Content[0].Text);
Console.WriteLine($"答え: {json.RootElement.GetProperty("final_answer")}");

推論モデル (o1, o4-mini)

ChatCompletionOptions options = new()
{
    ReasoningEffortLevel = ChatReasoningEffortLevel.Low,
    MaxOutputTokenCount = 100000
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new DeveloperChatMessage("あなたは親切なアシスタントです"),
    new UserChatMessage("相対性理論について説明してください")
], options);

Azure AI Search 統合 (RAG)

using Azure.AI.OpenAI.Chat;

#pragma warning disable AOAI001

ChatCompletionOptions options = new();
options.AddDataSource(new AzureSearchChatDataSource()
{
    Endpoint = new Uri(searchEndpoint),
    IndexName = searchIndex,
    Authentication = DataSourceAuthentication.FromApiKey(searchKey)
});

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("利用可能な健康保険プランは何ですか?")],
    options);

ChatMessageContext context = completion.GetMessageContext();
if (context?.Intent is not null)
{
    Console.WriteLine($"意図: {context.Intent}");
}
foreach (ChatCitation citation in context?.Citations ?? [])
{
    Console.WriteLine($"引用: {citation.Content}");
}

埋め込み

using OpenAI.Embeddings;

EmbeddingClient embeddingClient = azureClient.GetEmbeddingClient("text-embedding-ada-002");

OpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync("Hello, world!");
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"埋め込み次元数: {vector.Length}");

バッチ埋め込み

List<string> inputs = new()
{
    "最初のドキュメントテキスト",
    "2番目のドキュメントテキスト",
    "3番目のドキュメントテキスト"
};

OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);

foreach (OpenAIEmbedding emb in embeddings)
{
    Console.WriteLine($"インデックス {emb.Index}: {emb.ToFloats().Length} 次元");
}

画像生成 (DALL-E)

using OpenAI.Images;

ImageClient imageClient = azureClient.GetImageClient("dall-e-3");

GeneratedImage image = await imageClient.GenerateImageAsync(
    "夕暮れの未来的な都市のスカイライン",
    new ImageGenerationOptions
    {
        Size = GeneratedImageSize.W1024xH1024,
        Quality = GeneratedImageQuality.High,
        Style = GeneratedImageStyle.Vivid
    });

Console.WriteLine($"画像 URL: {image.ImageUri}");

音声 (Whisper)

文字起こし

using OpenAI.Audio;

AudioClient audioClient = azureClient.GetAudioClient("whisper");

AudioTranscription transcription = await audioClient.TranscribeAudioAsync(
    "audio.mp3",
    new AudioTranscriptionOptions
    {
        ResponseFormat = AudioTranscriptionFormat.Verbose,
        Language = "en"
    });

Console.WriteLine(transcription.Text);

テキスト読み上げ

BinaryData speech = await audioClient.GenerateSpeechAsync(
    "Azure OpenAI へようこそ!",
    GeneratedSpeechVoice.Alloy,
    new SpeechGenerationOptions
    {
        SpeedRatio = 1.0f,
        ResponseFormat = GeneratedSpeechFormat.Mp3
    });

await File.WriteAllBytesAsync("output.mp3", speech.ToArray());

関数呼び出し (ツール)

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "get_current_weather",
    functionDescription: "指定された場所の現在の天気を取得します",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "市町村と州、例: サンフランシスコ、CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
        """));

ChatCompletionOptions options = new()
{
    Tools = { getCurrentWeatherTool }
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("シアトルの天気はどうですか?")],
    options);

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    foreach (ChatToolCall toolCall in completion.ToolCalls)
    {
        Console.WriteLine($"関数: {toolCall.FunctionName}");
        Console.WriteLine($"引数: {toolCall.FunctionArguments}");
    }
}

主要な型リファレンス

型目的
AzureOpenAIClientAzure OpenAI のトップレベルクライアント
ChatClientチャット補完
EmbeddingClientテキスト埋め込み
ImageClient画像生成 (DALL-E)
AudioClient音声文字起こし/TTS
ChatCompletionチャット応答
ChatCompletionOptionsリクエスト設定
StreamingChatCompletionUpdateストリーミング応答チャンク
ChatMessageベースメッセージ型
SystemChatMessageシステムプロンプト
UserChatMessageユーザー入力
AssistantChatMessageアシスタント応答
DeveloperChatMessage開発者メッセージ (推論モデル)
ChatTool関数/ツールの定義
ChatToolCallツール呼び出し要求

ベストプラクティス

  1. 本番環境では Entra ID を使用 — API キーを避け、DefaultAzureCredential を使用する
  2. クライアントインスタンスを再利用 — 一度作成し、リクエスト間で共有する
  3. レート制限に対処 — 429 エラーに指数バックオフを実装する
  4. 長い応答にはストリーミング — より良い UX のために CompleteChatStreamingAsync を使用する
  5. 適切なタイムアウトを設定 — 長い補完には拡張タイムアウトが必要な場合がある
  6. 構造化出力を使用 — JSON スキーマで応答形式を一貫させる
  7. トークン使用量を監視 — completion.Usage を追跡してコスト管理を行う
  8. ツール呼び出しを検証 — 関数の引数を実行前に必ず検証する

エラー処理

using Azure;

try
{
    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
    Console.WriteLine("レート制限に達しました。遅延後に再試行します。");
    await Task.Delay(TimeSpan.FromSeconds(10));
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"無効なリクエスト: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Azure OpenAI エラー: {ex.Status} - {ex.Message}");
}

関連 SDK

SDK目的インストール
Azure.AI.OpenAIAzure OpenAI クライアント (このSDK)dotnet add package Azure.AI.OpenAI
OpenAIOpenAI 互換性dotnet add package OpenAI
Azure.Identity認証dotnet add package Azure.Identity
Azure.Search.DocumentsRAG 用 AI Searchdotnet add package Azure.Search.Documents

参考リンク

リソースURL
NuGet パッケージhttps://www.nuget.org/packages/Azure.AI.OpenAI
API リファレンスhttps://learn.microsoft.com/dotnet/api/azure.ai.openai
移行ガイド (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migration
クイックスタートhttps://learn.microsoft.com/azure/ai-services/openai/quickstart
GitHub ソースhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/openai/Azure.AI.OpenAI

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

関連スキル