[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-e82f3a23-db80-4871-824e-eff825821c07":3,"$f9OjL0afxaDxt-8rVuCeo-3PXAiaMoyfn7K5zJg6VRDI":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"e82f3a23-db80-4871-824e-eff825821c07","azure-ai-openai-dotnet","Azure OpenAI SDK for .NET。用于Azure OpenAI和OpenAI服务的客户端库。用于聊天完成、嵌入、图像生成、音频转录和助手。","cat_coding_devops","mod_coding","sickn33,coding","---\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\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,73,1063,"2026-05-16 13:05:17",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"DevOps","devops","mdi-cog-outline","CI\u002FCD、容器化、部署运维",3,162,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"cab36fae-7185-4bd7-98e5-2ebb90b5aaac","1.0.0","azure-ai-openai-dotnet.zip",4376,"uploads\u002Fskills\u002Fe82f3a23-db80-4871-824e-eff825821c07\u002Fazure-ai-openai-dotnet.zip","77a1edd8ad033a88f3023e0f99c9521d7f4686e5431eda5a8991902324bad655","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":13161}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]