[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6XEFQ0YXST2K449PSC1VS1F":3,"skill-same:01M6XEFQ0YXST2K449PSC1VS1F":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":45,"linkOnly":46,"markdownContent":47,"markdownBody":48,"frontMatter":49,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":14,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":56,"install":57,"resources":70},"01M6XEFQ0YXST2K449PSC1VS1F","azure-ai-openai-dotnet",null,"Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants.","sapsapshen\u002Fai-memory-router","sapsapshen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F20347959?v=4","01M6XDQEF1DP50DKF37H81J3J5","shenmian","01M6XDQEJPE41Y3DT2763X8ZJN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcopilot\u002Fazure-ai-openai-dotnet\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],"dotnet","azure ai","azure","azure ai openai dotnet","openai","services","2026","unknown","for","openai sdk","generation","chat","community","use","Audio","Image Generation","image","library","embeddings","azure openai","sdk","2026-11-10 10:12:30",false,"---\nname: azure-ai-openai-dotnet\ndescription: Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants.\nrisk: unknown\nsource: community\ndate_added: '2026-02-27'\n---\n\n# Azure.AI.OpenAI (.NET)\n\nClient library for Azure OpenAI Service providing access to OpenAI models including GPT-4, GPT-4o, embeddings, DALL-E, and Whisper.\n\n## Installation\n\n```bash\ndotnet add package Azure.AI.OpenAI\n\n# For OpenAI (non-Azure) compatibility\ndotnet add package OpenAI\n```\n\n**Current Version**: 2.1.0 (stable)\n\n## Environment Variables\n\n```bash\nAZURE_OPENAI_ENDPOINT=https:\u002F\u002F\u003Cresource-name>.openai.azure.com\nAZURE_OPENAI_API_KEY=\u003Capi-key>                    # For key-based auth\nAZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini          # Your deployment name\n```\n\n## Client Hierarchy\n\n```\nAzureOpenAIClient (top-level)\n├── GetChatClient(deploymentName)      → ChatClient\n├── GetEmbeddingClient(deploymentName) → EmbeddingClient\n├── GetImageClient(deploymentName)     → ImageClient\n├── GetAudioClient(deploymentName)     → AudioClient\n└── GetAssistantClient()               → AssistantClient\n```\n\n## Authentication\n\n### API Key Authentication\n\n```csharp\nusing Azure;\nusing Azure.AI.OpenAI;\n\nAzureOpenAIClient client = new(\n    new Uri(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\")!),\n    new AzureKeyCredential(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\")!));\n```\n\n### Microsoft Entra ID (Recommended for Production)\n\n```csharp\nusing Azure.Identity;\nusing Azure.AI.OpenAI;\n\nAzureOpenAIClient client = new(\n    new Uri(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\")!),\n    new DefaultAzureCredential());\n```\n\n### Using OpenAI SDK Directly with Azure\n\n```csharp\nusing Azure.Identity;\nusing OpenAI;\nusing OpenAI.Chat;\nusing System.ClientModel.Primitives;\n\n#pragma warning disable OPENAI001\n\nBearerTokenPolicy tokenPolicy = new(\n    new DefaultAzureCredential(),\n    \"https:\u002F\u002Fcognitiveservices.azure.com\u002F.default\");\n\nChatClient client = new(\n    model: \"gpt-4o-mini\",\n    authenticationPolicy: tokenPolicy,\n    options: new OpenAIClientOptions()\n    {\n        Endpoint = new Uri(\"https:\u002F\u002FYOUR-RESOURCE.openai.azure.com\u002Fopenai\u002Fv1\")\n    });\n```\n\n## Chat Completions\n\n### Basic Chat\n\n```csharp\nusing Azure.AI.OpenAI;\nusing OpenAI.Chat;\n\nAzureOpenAIClient azureClient = new(\n    new Uri(endpoint),\n    new DefaultAzureCredential());\n\nChatClient chatClient = azureClient.GetChatClient(\"gpt-4o-mini\");\n\nChatCompletion completion = chatClient.CompleteChat(\n[\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"What is Azure OpenAI?\")\n]);\n\nConsole.WriteLine(completion.Content[0].Text);\n```\n\n### Async Chat\n\n```csharp\nChatCompletion completion = await chatClient.CompleteChatAsync(\n[\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"Explain cloud computing in simple terms.\")\n]);\n\nConsole.WriteLine($\"Response: {completion.Content[0].Text}\");\nConsole.WriteLine($\"Tokens used: {completion.Usage.TotalTokenCount}\");\n```\n\n### Streaming Chat\n\n```csharp\nawait foreach (StreamingChatCompletionUpdate update \n    in chatClient.CompleteChatStreamingAsync(messages))\n{\n    if (update.ContentUpdate.Count > 0)\n    {\n        Console.Write(update.ContentUpdate[0].Text);\n    }\n}\n```\n\n### Chat with Options\n\n```csharp\nChatCompletionOptions options = new()\n{\n    MaxOutputTokenCount = 1000,\n    Temperature = 0.7f,\n    TopP = 0.95f,\n    FrequencyPenalty = 0,\n    PresencePenalty = 0\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);\n```\n\n### Multi-turn Conversation\n\n```csharp\nList\u003CChatMessage> messages = new()\n{\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"Hi, can you help me?\"),\n    new AssistantChatMessage(\"Of course! What do you need help with?\"),\n    new UserChatMessage(\"What's the capital of France?\")\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(messages);\nmessages.Add(new AssistantChatMessage(completion.Content[0].Text));\n```\n\n## Structured Outputs (JSON Schema)\n\n```csharp\nusing System.Text.Json;\n\nChatCompletionOptions options = new()\n{\n    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(\n        jsonSchemaFormatName: \"math_reasoning\",\n        jsonSchema: BinaryData.FromBytes(\"\"\"\n            {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"steps\": {\n                        \"type\": \"array\",\n                        \"items\": {\n                            \"type\": \"object\",\n                            \"properties\": {\n                                \"explanation\": { \"type\": \"string\" },\n                                \"output\": { \"type\": \"string\" }\n                            },\n                            \"required\": [\"explanation\", \"output\"],\n                            \"additionalProperties\": false\n                        }\n                    },\n                    \"final_answer\": { \"type\": \"string\" }\n                },\n                \"required\": [\"steps\", \"final_answer\"],\n                \"additionalProperties\": false\n            }\n            \"\"\"u8.ToArray()),\n        jsonSchemaIsStrict: true)\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"How can I solve 8x + 7 = -23?\")],\n    options);\n\nusing JsonDocument json = JsonDocument.Parse(completion.Content[0].Text);\nConsole.WriteLine($\"Answer: {json.RootElement.GetProperty(\"final_answer\")}\");\n```\n\n## Reasoning Models (o1, o4-mini)\n\n```csharp\nChatCompletionOptions options = new()\n{\n    ReasoningEffortLevel = ChatReasoningEffortLevel.Low,\n    MaxOutputTokenCount = 100000\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n[\n    new DeveloperChatMessage(\"You are a helpful assistant\"),\n    new UserChatMessage(\"Explain the theory of relativity\")\n], options);\n```\n\n## Azure AI Search Integration (RAG)\n\n```csharp\nusing Azure.AI.OpenAI.Chat;\n\n#pragma warning disable AOAI001\n\nChatCompletionOptions options = new();\noptions.AddDataSource(new AzureSearchChatDataSource()\n{\n    Endpoint = new Uri(searchEndpoint),\n    IndexName = searchIndex,\n    Authentication = DataSourceAuthentication.FromApiKey(searchKey)\n});\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"What health plans are available?\")],\n    options);\n\nChatMessageContext context = completion.GetMessageContext();\nif (context?.Intent is not null)\n{\n    Console.WriteLine($\"Intent: {context.Intent}\");\n}\nforeach (ChatCitation citation in context?.Citations ?? [])\n{\n    Console.WriteLine($\"Citation: {citation.Content}\");\n}\n```\n\n## Embeddings\n\n```csharp\nusing OpenAI.Embeddings;\n\nEmbeddingClient embeddingClient = azureClient.GetEmbeddingClient(\"text-embedding-ada-002\");\n\nOpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync(\"Hello, world!\");\nReadOnlyMemory\u003Cfloat> vector = embedding.ToFloats();\n\nConsole.WriteLine($\"Embedding dimensions: {vector.Length}\");\n```\n\n### Batch Embeddings\n\n```csharp\nList\u003Cstring> inputs = new()\n{\n    \"First document text\",\n    \"Second document text\",\n    \"Third document text\"\n};\n\nOpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);\n\nforeach (OpenAIEmbedding emb in embeddings)\n{\n    Console.WriteLine($\"Index {emb.Index}: {emb.ToFloats().Length} dimensions\");\n}\n```\n\n## Image Generation (DALL-E)\n\n```csharp\nusing OpenAI.Images;\n\nImageClient imageClient = azureClient.GetImageClient(\"dall-e-3\");\n\nGeneratedImage image = await imageClient.GenerateImageAsync(\n    \"A futuristic city skyline at sunset\",\n    new ImageGenerationOptions\n    {\n        Size = GeneratedImageSize.W1024xH1024,\n        Quality = GeneratedImageQuality.High,\n        Style = GeneratedImageStyle.Vivid\n    });\n\nConsole.WriteLine($\"Image URL: {image.ImageUri}\");\n```\n\n## Audio (Whisper)\n\n### Transcription\n\n```csharp\nusing OpenAI.Audio;\n\nAudioClient audioClient = azureClient.GetAudioClient(\"whisper\");\n\nAudioTranscription transcription = await audioClient.TranscribeAudioAsync(\n    \"audio.mp3\",\n    new AudioTranscriptionOptions\n    {\n        ResponseFormat = AudioTranscriptionFormat.Verbose,\n        Language = \"en\"\n    });\n\nConsole.WriteLine(transcription.Text);\n```\n\n### Text-to-Speech\n\n```csharp\nBinaryData speech = await audioClient.GenerateSpeechAsync(\n    \"Hello, welcome to Azure OpenAI!\",\n    GeneratedSpeechVoice.Alloy,\n    new SpeechGenerationOptions\n    {\n        SpeedRatio = 1.0f,\n        ResponseFormat = GeneratedSpeechFormat.Mp3\n    });\n\nawait File.WriteAllBytesAsync(\"output.mp3\", speech.ToArray());\n```\n\n## Function Calling (Tools)\n\n```csharp\nChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(\n    functionName: \"get_current_weather\",\n    functionDescription: \"Get the current weather in a given location\",\n    functionParameters: BinaryData.FromString(\"\"\"\n        {\n            \"type\": \"object\",\n            \"properties\": {\n                \"location\": {\n                    \"type\": \"string\",\n                    \"description\": \"The city and state, e.g. San Francisco, CA\"\n                },\n                \"unit\": {\n                    \"type\": \"string\",\n                    \"enum\": [\"celsius\", \"fahrenheit\"]\n                }\n            },\n            \"required\": [\"location\"]\n        }\n        \"\"\"));\n\nChatCompletionOptions options = new()\n{\n    Tools = { getCurrentWeatherTool }\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"What's the weather in Seattle?\")],\n    options);\n\nif (completion.FinishReason == ChatFinishReason.ToolCalls)\n{\n    foreach (ChatToolCall toolCall in completion.ToolCalls)\n    {\n        Console.WriteLine($\"Function: {toolCall.FunctionName}\");\n        Console.WriteLine($\"Arguments: {toolCall.FunctionArguments}\");\n    }\n}\n```\n\n## Key Types Reference\n\n| Type | Purpose |\n|------|---------|\n| `AzureOpenAIClient` | Top-level client for Azure OpenAI |\n| `ChatClient` | Chat completions |\n| `EmbeddingClient` | Text embeddings |\n| `ImageClient` | Image generation (DALL-E) |\n| `AudioClient` | Audio transcription\u002FTTS |\n| `ChatCompletion` | Chat response |\n| `ChatCompletionOptions` | Request configuration |\n| `StreamingChatCompletionUpdate` | Streaming response chunk |\n| `ChatMessage` | Base message type |\n| `SystemChatMessage` | System prompt |\n| `UserChatMessage` | User input |\n| `AssistantChatMessage` | Assistant response |\n| `DeveloperChatMessage` | Developer message (reasoning models) |\n| `ChatTool` | Function\u002Ftool definition |\n| `ChatToolCall` | Tool invocation request |\n\n## Best Practices\n\n1. **Use Entra ID in production** — Avoid API keys; use `DefaultAzureCredential`\n2. **Reuse client instances** — Create once, share across requests\n3. **Handle rate limits** — Implement exponential backoff for 429 errors\n4. **Stream for long responses** — Use `CompleteChatStreamingAsync` for better UX\n5. **Set appropriate timeouts** — Long completions may need extended timeouts\n6. **Use structured outputs** — JSON schema ensures consistent response format\n7. **Monitor token usage** — Track `completion.Usage` for cost management\n8. **Validate tool calls** — Always validate function arguments before execution\n\n## Error Handling\n\n```csharp\nusing Azure;\n\ntry\n{\n    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);\n}\ncatch (RequestFailedException ex) when (ex.Status == 429)\n{\n    Console.WriteLine(\"Rate limited. Retry after delay.\");\n    await Task.Delay(TimeSpan.FromSeconds(10));\n}\ncatch (RequestFailedException ex) when (ex.Status == 400)\n{\n    Console.WriteLine($\"Bad request: {ex.Message}\");\n}\ncatch (RequestFailedException ex)\n{\n    Console.WriteLine($\"Azure OpenAI error: {ex.Status} - {ex.Message}\");\n}\n```\n\n## Related SDKs\n\n| SDK | Purpose | Install |\n|-----|---------|---------|\n| `Azure.AI.OpenAI` | Azure OpenAI client (this SDK) | `dotnet add package Azure.AI.OpenAI` |\n| `OpenAI` | OpenAI compatibility | `dotnet add package OpenAI` |\n| `Azure.Identity` | Authentication | `dotnet add package Azure.Identity` |\n| `Azure.Search.Documents` | AI Search for RAG | `dotnet add package Azure.Search.Documents` |\n\n## Reference Links\n\n| Resource | URL |\n|----------|-----|\n| NuGet Package | https:\u002F\u002Fwww.nuget.org\u002Fpackages\u002FAzure.AI.OpenAI |\n| API Reference | https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fazure.ai.openai |\n| Migration Guide (1.0→2.0) | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Fhow-to\u002Fdotnet-migration |\n| Quickstart | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Fquickstart |\n| GitHub Source | https:\u002F\u002Fgithub.com\u002FAzure\u002Fazure-sdk-for-net\u002Ftree\u002Fmain\u002Fsdk\u002Fopenai\u002FAzure.AI.OpenAI |\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n","# Azure.AI.OpenAI (.NET)\n\nClient library for Azure OpenAI Service providing access to OpenAI models including GPT-4, GPT-4o, embeddings, DALL-E, and Whisper.\n\n## Installation\n\n```bash\ndotnet add package Azure.AI.OpenAI\n\n# For OpenAI (non-Azure) compatibility\ndotnet add package OpenAI\n```\n\n**Current Version**: 2.1.0 (stable)\n\n## Environment Variables\n\n```bash\nAZURE_OPENAI_ENDPOINT=https:\u002F\u002F\u003Cresource-name>.openai.azure.com\nAZURE_OPENAI_API_KEY=\u003Capi-key>                    # For key-based auth\nAZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini          # Your deployment name\n```\n\n## Client Hierarchy\n\n```\nAzureOpenAIClient (top-level)\n├── GetChatClient(deploymentName)      → ChatClient\n├── GetEmbeddingClient(deploymentName) → EmbeddingClient\n├── GetImageClient(deploymentName)     → ImageClient\n├── GetAudioClient(deploymentName)     → AudioClient\n└── GetAssistantClient()               → AssistantClient\n```\n\n## Authentication\n\n### API Key Authentication\n\n```csharp\nusing Azure;\nusing Azure.AI.OpenAI;\n\nAzureOpenAIClient client = new(\n    new Uri(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\")!),\n    new AzureKeyCredential(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\")!));\n```\n\n### Microsoft Entra ID (Recommended for Production)\n\n```csharp\nusing Azure.Identity;\nusing Azure.AI.OpenAI;\n\nAzureOpenAIClient client = new(\n    new Uri(Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\")!),\n    new DefaultAzureCredential());\n```\n\n### Using OpenAI SDK Directly with Azure\n\n```csharp\nusing Azure.Identity;\nusing OpenAI;\nusing OpenAI.Chat;\nusing System.ClientModel.Primitives;\n\n#pragma warning disable OPENAI001\n\nBearerTokenPolicy tokenPolicy = new(\n    new DefaultAzureCredential(),\n    \"https:\u002F\u002Fcognitiveservices.azure.com\u002F.default\");\n\nChatClient client = new(\n    model: \"gpt-4o-mini\",\n    authenticationPolicy: tokenPolicy,\n    options: new OpenAIClientOptions()\n    {\n        Endpoint = new Uri(\"https:\u002F\u002FYOUR-RESOURCE.openai.azure.com\u002Fopenai\u002Fv1\")\n    });\n```\n\n## Chat Completions\n\n### Basic Chat\n\n```csharp\nusing Azure.AI.OpenAI;\nusing OpenAI.Chat;\n\nAzureOpenAIClient azureClient = new(\n    new Uri(endpoint),\n    new DefaultAzureCredential());\n\nChatClient chatClient = azureClient.GetChatClient(\"gpt-4o-mini\");\n\nChatCompletion completion = chatClient.CompleteChat(\n[\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"What is Azure OpenAI?\")\n]);\n\nConsole.WriteLine(completion.Content[0].Text);\n```\n\n### Async Chat\n\n```csharp\nChatCompletion completion = await chatClient.CompleteChatAsync(\n[\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"Explain cloud computing in simple terms.\")\n]);\n\nConsole.WriteLine($\"Response: {completion.Content[0].Text}\");\nConsole.WriteLine($\"Tokens used: {completion.Usage.TotalTokenCount}\");\n```\n\n### Streaming Chat\n\n```csharp\nawait foreach (StreamingChatCompletionUpdate update \n    in chatClient.CompleteChatStreamingAsync(messages))\n{\n    if (update.ContentUpdate.Count > 0)\n    {\n        Console.Write(update.ContentUpdate[0].Text);\n    }\n}\n```\n\n### Chat with Options\n\n```csharp\nChatCompletionOptions options = new()\n{\n    MaxOutputTokenCount = 1000,\n    Temperature = 0.7f,\n    TopP = 0.95f,\n    FrequencyPenalty = 0,\n    PresencePenalty = 0\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);\n```\n\n### Multi-turn Conversation\n\n```csharp\nList\u003CChatMessage> messages = new()\n{\n    new SystemChatMessage(\"You are a helpful assistant.\"),\n    new UserChatMessage(\"Hi, can you help me?\"),\n    new AssistantChatMessage(\"Of course! What do you need help with?\"),\n    new UserChatMessage(\"What's the capital of France?\")\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(messages);\nmessages.Add(new AssistantChatMessage(completion.Content[0].Text));\n```\n\n## Structured Outputs (JSON Schema)\n\n```csharp\nusing System.Text.Json;\n\nChatCompletionOptions options = new()\n{\n    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(\n        jsonSchemaFormatName: \"math_reasoning\",\n        jsonSchema: BinaryData.FromBytes(\"\"\"\n            {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"steps\": {\n                        \"type\": \"array\",\n                        \"items\": {\n                            \"type\": \"object\",\n                            \"properties\": {\n                                \"explanation\": { \"type\": \"string\" },\n                                \"output\": { \"type\": \"string\" }\n                            },\n                            \"required\": [\"explanation\", \"output\"],\n                            \"additionalProperties\": false\n                        }\n                    },\n                    \"final_answer\": { \"type\": \"string\" }\n                },\n                \"required\": [\"steps\", \"final_answer\"],\n                \"additionalProperties\": false\n            }\n            \"\"\"u8.ToArray()),\n        jsonSchemaIsStrict: true)\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"How can I solve 8x + 7 = -23?\")],\n    options);\n\nusing JsonDocument json = JsonDocument.Parse(completion.Content[0].Text);\nConsole.WriteLine($\"Answer: {json.RootElement.GetProperty(\"final_answer\")}\");\n```\n\n## Reasoning Models (o1, o4-mini)\n\n```csharp\nChatCompletionOptions options = new()\n{\n    ReasoningEffortLevel = ChatReasoningEffortLevel.Low,\n    MaxOutputTokenCount = 100000\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n[\n    new DeveloperChatMessage(\"You are a helpful assistant\"),\n    new UserChatMessage(\"Explain the theory of relativity\")\n], options);\n```\n\n## Azure AI Search Integration (RAG)\n\n```csharp\nusing Azure.AI.OpenAI.Chat;\n\n#pragma warning disable AOAI001\n\nChatCompletionOptions options = new();\noptions.AddDataSource(new AzureSearchChatDataSource()\n{\n    Endpoint = new Uri(searchEndpoint),\n    IndexName = searchIndex,\n    Authentication = DataSourceAuthentication.FromApiKey(searchKey)\n});\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"What health plans are available?\")],\n    options);\n\nChatMessageContext context = completion.GetMessageContext();\nif (context?.Intent is not null)\n{\n    Console.WriteLine($\"Intent: {context.Intent}\");\n}\nforeach (ChatCitation citation in context?.Citations ?? [])\n{\n    Console.WriteLine($\"Citation: {citation.Content}\");\n}\n```\n\n## Embeddings\n\n```csharp\nusing OpenAI.Embeddings;\n\nEmbeddingClient embeddingClient = azureClient.GetEmbeddingClient(\"text-embedding-ada-002\");\n\nOpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync(\"Hello, world!\");\nReadOnlyMemory\u003Cfloat> vector = embedding.ToFloats();\n\nConsole.WriteLine($\"Embedding dimensions: {vector.Length}\");\n```\n\n### Batch Embeddings\n\n```csharp\nList\u003Cstring> inputs = new()\n{\n    \"First document text\",\n    \"Second document text\",\n    \"Third document text\"\n};\n\nOpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);\n\nforeach (OpenAIEmbedding emb in embeddings)\n{\n    Console.WriteLine($\"Index {emb.Index}: {emb.ToFloats().Length} dimensions\");\n}\n```\n\n## Image Generation (DALL-E)\n\n```csharp\nusing OpenAI.Images;\n\nImageClient imageClient = azureClient.GetImageClient(\"dall-e-3\");\n\nGeneratedImage image = await imageClient.GenerateImageAsync(\n    \"A futuristic city skyline at sunset\",\n    new ImageGenerationOptions\n    {\n        Size = GeneratedImageSize.W1024xH1024,\n        Quality = GeneratedImageQuality.High,\n        Style = GeneratedImageStyle.Vivid\n    });\n\nConsole.WriteLine($\"Image URL: {image.ImageUri}\");\n```\n\n## Audio (Whisper)\n\n### Transcription\n\n```csharp\nusing OpenAI.Audio;\n\nAudioClient audioClient = azureClient.GetAudioClient(\"whisper\");\n\nAudioTranscription transcription = await audioClient.TranscribeAudioAsync(\n    \"audio.mp3\",\n    new AudioTranscriptionOptions\n    {\n        ResponseFormat = AudioTranscriptionFormat.Verbose,\n        Language = \"en\"\n    });\n\nConsole.WriteLine(transcription.Text);\n```\n\n### Text-to-Speech\n\n```csharp\nBinaryData speech = await audioClient.GenerateSpeechAsync(\n    \"Hello, welcome to Azure OpenAI!\",\n    GeneratedSpeechVoice.Alloy,\n    new SpeechGenerationOptions\n    {\n        SpeedRatio = 1.0f,\n        ResponseFormat = GeneratedSpeechFormat.Mp3\n    });\n\nawait File.WriteAllBytesAsync(\"output.mp3\", speech.ToArray());\n```\n\n## Function Calling (Tools)\n\n```csharp\nChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(\n    functionName: \"get_current_weather\",\n    functionDescription: \"Get the current weather in a given location\",\n    functionParameters: BinaryData.FromString(\"\"\"\n        {\n            \"type\": \"object\",\n            \"properties\": {\n                \"location\": {\n                    \"type\": \"string\",\n                    \"description\": \"The city and state, e.g. San Francisco, CA\"\n                },\n                \"unit\": {\n                    \"type\": \"string\",\n                    \"enum\": [\"celsius\", \"fahrenheit\"]\n                }\n            },\n            \"required\": [\"location\"]\n        }\n        \"\"\"));\n\nChatCompletionOptions options = new()\n{\n    Tools = { getCurrentWeatherTool }\n};\n\nChatCompletion completion = await chatClient.CompleteChatAsync(\n    [new UserChatMessage(\"What's the weather in Seattle?\")],\n    options);\n\nif (completion.FinishReason == ChatFinishReason.ToolCalls)\n{\n    foreach (ChatToolCall toolCall in completion.ToolCalls)\n    {\n        Console.WriteLine($\"Function: {toolCall.FunctionName}\");\n        Console.WriteLine($\"Arguments: {toolCall.FunctionArguments}\");\n    }\n}\n```\n\n## Key Types Reference\n\n| Type | Purpose |\n|------|---------|\n| `AzureOpenAIClient` | Top-level client for Azure OpenAI |\n| `ChatClient` | Chat completions |\n| `EmbeddingClient` | Text embeddings |\n| `ImageClient` | Image generation (DALL-E) |\n| `AudioClient` | Audio transcription\u002FTTS |\n| `ChatCompletion` | Chat response |\n| `ChatCompletionOptions` | Request configuration |\n| `StreamingChatCompletionUpdate` | Streaming response chunk |\n| `ChatMessage` | Base message type |\n| `SystemChatMessage` | System prompt |\n| `UserChatMessage` | User input |\n| `AssistantChatMessage` | Assistant response |\n| `DeveloperChatMessage` | Developer message (reasoning models) |\n| `ChatTool` | Function\u002Ftool definition |\n| `ChatToolCall` | Tool invocation request |\n\n## Best Practices\n\n1. **Use Entra ID in production** — Avoid API keys; use `DefaultAzureCredential`\n2. **Reuse client instances** — Create once, share across requests\n3. **Handle rate limits** — Implement exponential backoff for 429 errors\n4. **Stream for long responses** — Use `CompleteChatStreamingAsync` for better UX\n5. **Set appropriate timeouts** — Long completions may need extended timeouts\n6. **Use structured outputs** — JSON schema ensures consistent response format\n7. **Monitor token usage** — Track `completion.Usage` for cost management\n8. **Validate tool calls** — Always validate function arguments before execution\n\n## Error Handling\n\n```csharp\nusing Azure;\n\ntry\n{\n    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);\n}\ncatch (RequestFailedException ex) when (ex.Status == 429)\n{\n    Console.WriteLine(\"Rate limited. Retry after delay.\");\n    await Task.Delay(TimeSpan.FromSeconds(10));\n}\ncatch (RequestFailedException ex) when (ex.Status == 400)\n{\n    Console.WriteLine($\"Bad request: {ex.Message}\");\n}\ncatch (RequestFailedException ex)\n{\n    Console.WriteLine($\"Azure OpenAI error: {ex.Status} - {ex.Message}\");\n}\n```\n\n## Related SDKs\n\n| SDK | Purpose | Install |\n|-----|---------|---------|\n| `Azure.AI.OpenAI` | Azure OpenAI client (this SDK) | `dotnet add package Azure.AI.OpenAI` |\n| `OpenAI` | OpenAI compatibility | `dotnet add package OpenAI` |\n| `Azure.Identity` | Authentication | `dotnet add package Azure.Identity` |\n| `Azure.Search.Documents` | AI Search for RAG | `dotnet add package Azure.Search.Documents` |\n\n## Reference Links\n\n| Resource | URL |\n|----------|-----|\n| NuGet Package | https:\u002F\u002Fwww.nuget.org\u002Fpackages\u002FAzure.AI.OpenAI |\n| API Reference | https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fazure.ai.openai |\n| Migration Guide (1.0→2.0) | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Fhow-to\u002Fdotnet-migration |\n| Quickstart | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Fquickstart |\n| GitHub Source | https:\u002F\u002Fgithub.com\u002FAzure\u002Fazure-sdk-for-net\u002Ftree\u002Fmain\u002Fsdk\u002Fopenai\u002FAzure.AI.OpenAI |\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n",{"name":5,"risk":31,"source":36,"date_added":50,"description":7},"2026-02-27","main","7a38d8e7073e61c16eda85681cb32fb68a8657a5","skills-store\u002Fcopilot\u002Fazure-ai-openai-dotnet","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router","https:\u002F\u002Fgithub.com\u002Fsapsapshen","2026-04-14 21:12:12",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add sapsapshen\u002Fai-memory-router --skill azure-ai-openai-dotnet",{"tool":63,"command":64},"bunx","bunx skills add sapsapshen\u002Fai-memory-router --skill azure-ai-openai-dotnet",{"tool":66,"command":67},"pnpm","pnpm dlx skills add sapsapshen\u002Fai-memory-router --skill azure-ai-openai-dotnet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fcopilot\u002Fazure-ai-openai-dotnet\u002FSKILL.md",true,[],[72,96,122,132,145,161],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":83,"publishedAt":45},"01M71ATQRKG48SH06FQ697T5G9","wechat-search","Search WeChat Official Account articles using OpenClaw's web search and fetch capabilities with compliance-focused design.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fwechat-search-release\u002FSKILL.md",[78],{"categoryNo":79,"categoryName":80,"taxonomyType":81,"taxonomyTypeDesc":82},"01JBSEEDCAT000000000000037","律师与法务","PROFESSION","适用职业",[84,85,86,87,88,89,90,91,92,93,94,95],"wechat search","wechat","search","capabilities","openclaw","design","web search","compliance","web","official","fetch","with",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":45},"01M71ATNAVGZB35PFYM2GC5N00","trend-tap","Real-time trending topics aggregator across 7 platforms (X\u002FTwitter, Reddit, Google Trends, Hacker News, Zhihu, Bilibili, Weibo). Trigger: when user says 'trend', 'trends', 'trend tap', '热点', '热搜', or asks what is trending\u002Fhot. Do NOT use web_search — this skill already fetches live data from all platforms with zero API keys.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftrend-tap\u002FSKILL.md",[],[103,104,105,106,107,108,86,109,110,111,112,113,114,115,116,117,118,119,120,121],"trend","trend tap","tap","api keys","Bash","time","trending","hacker","aggregator","do","when","brew","live","data","google","install","read","across","api",{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":45},"01M71ATJ9AM5KM15AA8PS302EB","trend-radar","Real-time trending topics aggregator across 7 platforms (X\u002FTwitter, Reddit, Google Trends, Hacker News, Zhihu, Bilibili, Weibo). Trigger: when user says 'trend', 'trends', 'trend pulse', '热点', '热搜', or asks what is trending\u002Fhot. Do NOT use web_search — this skill already fetches live data from all platforms with zero API keys.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftrend-radar\u002FSKILL.md",[],[129,130,103,114,115,116,117,107,86,119,131,120,121,113,111,110,109,118,108,106],"trend radar","radar","pulse",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":45},"01M71ATGF095N3EJM9G8SD0BB5","tech-news-daily","每日科技新闻汇——从全球多个 RSS 源抓取最新科技新闻，翻译（英→中）、去重、排版成每日简报。当用户询问科技新闻、科技新鲜事、每日科技、技术动态、Daily Tech News 或类似表达时触发此技能。","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftech-news-daily\u002FSKILL.md",[],[139,140,141,142,143,144],"news","tech","tech news daily","daily","rss","翻译",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":154,"publishedAt":45},"01M71ATFAEAMQ17M70NQNY7SR8","summarize","Summarize URLs or files with the summarize CLI (web, PDFs, images, audio, YouTube).","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fsummarize\u002FSKILL.md",[151],{"categoryNo":152,"categoryName":153,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000021","资料检索与研究",[147,92,38,155,156,95,114,157,158,159,105,160,118],"cli","youtube","images","https","files","pdfs",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":45},"01M71ATDNS3R0M4H936PACQAWZ","sonoscli","Control Sonos speakers (discover\u002Fstatus\u002Fplay\u002Fvolume\u002Fgroup).","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fsonoscli\u002FSKILL.md",[],[163,168,169,170,118,171,158,172,173,174,175,176],"status","play","go","latest","github","discover","control","cmd","volume"]