Azure AI OpenAI .NET SDK
Azure.AI.OpenAI (.NET)
Azure OpenAI 服务的客户端库,提供对 GPT-4、GPT-4o、embeddings、DALL-E 和 Whisper 等 OpenAI 模型的访问。
安装
dotnet add package Azure.AI.OpenAI
用于 OpenAI(非 Azure)兼容性
dotnet add package OpenAI当前版本: 2.1.0 (stable)
环境变量
AZURE_OPENAI_ENDPOINT=https://<resource-name>.openai.azure.com
AZURE_OPENAI_API_KEY=<api-key> # 用于密钥认证
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini # 您的部署名称客户端层级结构
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 ID (生产环境推荐)
using Azure.Identity;
using Azure.AI.OpenAI;
AzureOpenAIClient client = new(
new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
new DefaultAzureCredential());
在 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")
});
聊天补全 (Chat Completions)
基础聊天
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("You are a helpful assistant."),
new UserChatMessage("What is Azure OpenAI?")
]);
Console.WriteLine(completion.Content[0].Text);
异步聊天
ChatCompletion completion = await chatClient.CompleteChatAsync(
[
new SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("Explain cloud computing in simple terms.")
]);
Console.WriteLine($"Response: {completion.Content[0].Text}");
Console.WriteLine($"Tokens used: {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 = 0ChatCompletion 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 Schema)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($"Answer: {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($"Intent: {context.Intent}");
}
foreach (ChatCitation citation in context?.Citations ?? [])
{
Console.WriteLine($"Citation: {citation.Content}");
}
## 嵌入 (Embeddings)using OpenAI.Embeddings;
EmbeddingClient embeddingClient = azureClient.GetEmbeddingClient("text-embedding-ada-002");
OpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync("Hello, world!");
ReadOnlyMemory<float> vector = embedding.ToFloats();
Console.Write
Line($"Embedding dimensions: {vector.Length}");批量 Embedding
List<string> inputs = new()
{
"第一篇文档文本",
"第二篇文档文本",
"第三篇文档文本"
};
OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);
foreach (OpenAIEmbedding emb in embeddings)
{
Console.WriteLine($"Index {emb.Index}: {emb.ToFloats().Length} dimensions");
}
图像生成 (DALL-E)
using OpenAI.Images;
ImageClient imageClient = azureClient.GetImageClient("dall-e-3");
GeneratedImage image = await imageClient.GenerateImageAsync(
"A futuristic city skyline at sunset",
new ImageGenerationOptions
{
Size = GeneratedImageSize.W1024xH1024,
Quality = GeneratedImageQuality.High,
Style = GeneratedImageStyle.Vivid
});
Console.WriteLine($"Image URL: {image.ImageUri}");
音频 (Whisper)
语音转文字 (Transcription)
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);
文字转语音 (TTS)
BinaryData speech = await audioClient.GenerateSpeechAsync(
"Hello, welcome to Azure OpenAI!",
GeneratedSpeechVoice.Alloy,
new SpeechGenerationOptions
{
SpeedRatio = 1.0f,
ResponseFormat = GeneratedSpeechFormat.Mp3
});
await File.WriteAllBytesAsync("output.mp3", speech.ToArray());
函数调用 (Tools)
ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
functionName: "get_current_weather",
functionDescription: "Get the current weather in a given location",
functionParameters: BinaryData.FromString("""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
}
"""));
ChatCompletionOptions options = new()
{
Tools = { getCurrentWeatherTool }
};
ChatCompletion completion = await chatClient.CompleteChatAsync(
[new UserChatMessage("What's the weather in Seattle?")],
options);
if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
foreach (ChatToolCall toolCall in completion.ToolCalls)
{
Console.WriteLine($"Function: {toolCall.FunctionName}");
Console.WriteLine($"Arguments: {toolCall.FunctionArguments}");
}
}
核心类型参考
| 类型 | 用途 |
|------|---------|
| AzureOpenAIClient | Azure OpenAI 的顶层客户端 |
| ChatClient | 聊天补全 |
| EmbeddingClient | 文本 Embedding |
| ImageClient | 图像生成 (DALL-E) |
| AudioClient | 音频转录/TTS |
| ChatCompletion | 聊天响应 |
| ChatCompletionOptions | 请求配置 |
| StreamingChatCompletionUpdate | 流式响应分片 |
| ChatMessage | 消息基类 |
| SystemChatMessage | 系统提示词 |
| UserChatMessage | 用户输入 |
| AssistantChatMessage | 助手响应 |
| DeveloperChatMessage | 开发人员消息 |
oper 消息(推理模型) |
| ChatTool | 函数/工具定义 |
| ChatToolCall | 工具调用请求 |
最佳实践
1. 生产环境使用 Entra ID — 避免使用 API 密钥,建议使用 DefaultAzureCredential
2. 复用客户端实例 — 创建一次,在多个请求间共享
3. 处理速率限制 — 针对 429 错误实现指数退避机制
4. 长响应使用流式传输 — 使用 CompleteChatStreamingAsync 以提升用户体验
5. 设置合理的超时时间 — 较长的生成内容可能需要延长超时时间
6. 使用结构化输出 — 通过 JSON schema 确保响应格式的一致性
7. 监控 Token 使用量 — 跟踪 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.OpenAI | Azure OpenAI 客户端(本 SDK) | dotnet add package Azure.AI.OpenAI |
| OpenAI | OpenAI 兼容性 | dotnet add package OpenAI |
| Azure.Identity | 身份验证 | dotnet add package Azure.Identity |
| Azure.Search.Documents | 用于 RAG 的 AI Search | dotnet 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 |
适用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务明确符合上述范围时使用此技能。
- 不要将输出结果视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止操作并请求澄清。