Azure OpenAI操作_azure-ai-openai-dotnet
以下为本文档的中文说明该技能用于操作Azure OpenAI服务的.NET SDK。Azure OpenAI是微软Azure云平台上托管的OpenAI服务提供GPT系列模型、Embedding模型和DALL-E图像生成等AI能力。此客户端库支持聊天补全、文本补全、嵌入向量生成和图像生成等核心功能。适用于需要在.NET应用中集成大语言模型能力的开发者可用于构建智能客服、内容生成助手、代码辅助工具和AI驱动的自动化工作流。该技能提供了与Azure OpenAI服务交互的完整SDK接口支持安全认证和模型部署管理。该技能提供了详细的操作指南和最佳实践帮助用户快速上手并深入掌握。通过系统的功能模块划分和丰富的应用场景说明用户可以在实际项目中有效运用该技能提升工作效率。该技能注重实用性和可操作性涵盖从基础配置到高级功能的完整知识体系满足不同层次用户的学习需求。持续更新和优化的内容确保用户始终能够接触到最新的技术发展和行业实践。通过此技能的学习和应用用户可以减少摸索时间快速获得可用的解决方案将精力集中在核心业务逻辑和创新工作上从而在技术快速迭代的环境中保持竞争力。该技能的模块化设计使其易于扩展和定制用户可以根据自身需求灵活调整应用方式实现最大化的价值产出。该技能整合了常见的设计模式和最佳实践提供了清晰的学习路径和参考资料帮助用户在短时间内建立起完整的知识框架并有能力在实际项目中灵活运用所学内容解决问题。Azure.AI.OpenAI (.NET)Client library for Azure OpenAI Service providing access to OpenAI models including GPT-4, GPT-4o, embeddings, DALL-E, and Whisper.Installationdotnetaddpackage Azure.AI.OpenAI# For OpenAI (non-Azure) compatibilitydotnetaddpackage OpenAICurrent Version: 2.1.0 (stable)Environment VariablesAZURE_OPENAI_ENDPOINThttps://resource-name.openai.azure.com# Required: Azure OpenAI endpointAZURE_OPENAI_API_KEYapi-key# Only required for AzureKeyCredential authAZURE_OPENAI_DEPLOYMENT_NAMEgpt-4o-mini# Required: model deployment nameAZURE_TOKEN_CREDENTIALSprod# Required only if DefaultAzureCredential is used in productionClient HierarchyAzureOpenAIClient (top-level) ├── GetChatClient(deploymentName) → ChatClient ├── GetEmbeddingClient(deploymentName) → EmbeddingClient ├── GetImageClient(deploymentName) → ImageClient ├── GetAudioClient(deploymentName) → AudioClient └── GetAssistantClient() → AssistantClientAuthenticationAPI Key AuthenticationusingAzure;usingAzure.AI.OpenAI;AzureOpenAIClientclientnew(newUri(Environment.GetEnvironmentVariable(AZURE_OPENAI_ENDPOINT)!),newAzureKeyCredential(Environment.GetEnvironmentVariable(AZURE_OPENAI_API_KEY)!));Microsoft Entra Token CredentialusingAzure.Identity;usingAzure.AI.OpenAI;// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALSprod or AZURE_TOKEN_CREDENTIALSspecific_credentialvarcredentialnewDefaultAzureCredential(DefaultAzureCredential.DefaultEnvironmentVariableName);// Or use a specific credential directly in production:// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?viewazure-dotnet#credential-classes// var credential new ManagedIdentityCredential();AzureOpenAIClientclientnew(newUri(Environment.GetEnvironmentVariable(AZURE_OPENAI_ENDPOINT)!),credential);Using OpenAI SDK Directly with AzureusingAzure.Identity;usingOpenAI;usingOpenAI.Chat;usingSystem.ClientModel.Primitives;#pragmawarning disable OPENAI001BearerTokenPolicytokenPolicynew(newDefaultAzureCredential(),https://cognitiveservices.azure.com/.default);ChatClientclientnew(model:gpt-4o-mini,authenticationPolicy:tokenPolicy,options:newOpenAIClientOptions(){EndpointnewUri(https://YOUR-RESOURCE.openai.azure.com/openai/v1)});Chat CompletionsBasic ChatusingAzure.AI.OpenAI;usingOpenAI.Chat;AzureOpenAIClientazureClientnew(newUri(endpoint),newDefaultAzureCredential());ChatClientchatClientazureClient.GetChatClient(gpt-4o-mini);ChatCompletioncompletionchatClient.CompleteChat([newSystemChatMessage(You are a helpful assistant.),newUserChatMessage(What is Azure OpenAI?)]);Console.WriteLine(completion.Content[0].Text);Async ChatChatCompletioncompletionawaitchatClient.CompleteChatAsync([newSystemChatMessage(You are a helpful assistant.),newUserChatMessage(Explain cloud computing in simple terms.)]);Console.WriteLine($Response:{completion.Content[0].Text});Console.WriteLine($Tokens used:{completion.Usage.TotalTokenCount});Streaming Chatawaitforeach(StreamingChatCompletionUpdateupdateinchatClient.CompleteChatStreamingAsync(messages)){if(update.ContentUpdate.Count0){Console.Write(update.ContentUpdate[0].Text);}}Chat with OptionsChatCompletionOptionsoptionsnew(){MaxOutputTokenCount1000,Temperature0.7f,TopP0.95f,FrequencyPenalty0,PresencePenalty0};ChatCompletioncompletionawaitchatClient.CompleteChatAsync(messages,options);Multi-turn ConversationListChatMessagemessagesnew(){newSystemChatMessage(You are a helpful ass istant.),newUserChatMessage(Hi, can you help me?),newAssistantChatMessage(Of course! What do you need help with?),newUserChatMessage(Whats the capital of France?)};ChatCompletioncompletionawaitchatClient.CompleteChatAsync(messages);messages.Add(newAssistantChatMessage(completion.Content[0].Text));Structured Outputs (JSON Schema)usingSystem.Text.Json;ChatCompletionOptionsoptionsnew(){ResponseFormatChatResponseFormat.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)};ChatCompletioncompletionawaitchatClient.CompleteChatAsync([newUserChatMessage(How can I solve 8x 7 -23?)],options);usingJsonDocumentjsonJsonDocument.Parse(completion.Content[0].Text);Console.WriteLine($Answer:{json.RootElement.GetProperty(final_answer)});Reasoning Models (o1, o4-mini)ChatCompletionOptionsoptionsnew(){ReasoningEffortLevelChatReasoningEffortLevel.Low,MaxOutputTokenCount100000};ChatCompletioncompletionawaitchatClient.CompleteChatAsync([newDeveloperChatMessage(You are a helpful assistant),newUserChatMessage(Explain the theory of relativity)],options);Azure AI Search Integration (RAG)usingAzure.AI.OpenAI.Chat;#pragmawarning disable AOAI001ChatCompletionOptionsoptionsnew();options.AddDataSource(newAzureSearchChatDataSource(){EndpointnewUri(searchEndpoint),IndexNamesearchIndex,AuthenticationDataSourceAuthentication.FromApiKey(searchKey)});ChatCompletioncompletionawaitchatClient.CompleteChatAsync([newUserChatMessage(What health plans are available?)],options);ChatMessageContextcontextcompletion.GetMessageContext();if(context?.Intentisnotnull){Console.WriteLine($Intent:{context.Intent});}foreach(ChatCitationcitationincontext?.Citations??[]){Console.WriteLine($Citation:{citation.Content});}EmbeddingsusingOpenAI.Embeddings;EmbeddingClientembeddingClientazureClient.GetEmbeddingClient(text-embedding-ada-002);OpenAIEmbeddingembeddingawaitembeddingClient.GenerateEmbeddingAsync(Hello, world!);ReadOnlyMemoryfloatvectorembedding.ToFloats();Console.WriteLine($Embedding dimensions:{vector.Length});Batch EmbeddingsListstringinputsnew(){First document text,Second document text,Third document text};OpenAIEmbeddingCollectionembeddingsawaitembeddingClient.GenerateEmbeddingsAsync(inputs);foreach(OpenAIEmbeddingembinembeddings){Console.WriteLine($Index{emb.Index}:{emb.ToFloats().Length}dimensions);}Image Generation (DALL-E)usingOpenAI.Images;ImageClientimageClientazureClient.GetImageClient(dall-e-3);GeneratedImageimageawaitimageClient.GenerateImageAsync(A futuristic city skyline at sunset,newImageGenerationOptions{SizeGeneratedImageSize.W1024xH1024,QualityGeneratedImageQuality.High,StyleGeneratedImageStyle.Vivid});Console.WriteLine($Image URL:{image.ImageUri});Audio (Whisper)TranscriptionusingOpenAI.Audio;AudioClientaudioClientazureClient.GetAudioClient(whisper);AudioTranscriptiontranscriptionawaitaudioClient.TranscribeAudioAsync(audio.mp3,newAudioTranscriptionOptions{ResponseFormatAudioTranscriptionFormat.Verbose,Languageen});Console.WriteLine(transcription.Text);Text-to-SpeechBinaryDataspeechawaitaudioClient.GenerateSpeechAsync(Hello, welcome to Azure OpenAI!,GeneratedSpeechVoice.Alloy,newSpeechGenerationOptions{SpeedRatio1.0f,ResponseFormatGeneratedSpeechFormat.Mp3});awaitFile.WriteAllBytesAsync(output.mp3,speech.ToArray());Function Calling (Tools)ChatToolgetCurrentWeatherToolChatTool.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]}));ChatCompletionOptionsoptionsnew(){Tools{getCurrentWeatherTool}};ChatCompletioncompletionawaitchatClient.CompleteChatAsync([newUserChatMessage(Whats the weather in Seattle?)],options);if(completion.FinishReasonChatFinishReason.ToolCalls){foreach(ChatToolCalltoolCallincompletion.ToolCalls){Console.WriteLine($Function:{toolCall.FunctionName});Console.WriteLine($Arguments:{toolCall.FunctionArguments});}}Key Types ReferenceTypePurposeAzureOpenAIClientTop-level client for Azure OpenAIChatClientChat completionsEmbeddingClientText embeddingsImageClientImage generation (DALL-E)AudioClientAudio transcription/TTSChatCompletionChat responseChatCompletionOptionsRequest configurationStreamingChatCompletionUpdateStreaming response chunkChatMessageBase message typeSystemChatMessageSystem promptUserChatMessageUser inputAssistantChatMessageAssistant responseDeveloperChatMessageDeveloper message (reasoning models)ChatToolFunction/tool definitionChatToolCallTool invocation requestBest PracticesUse Entra ID in production— Avoid API keys; useDefaultAzureCredentialReuse client instances— Create once, share across requestsHandle rate limits— Implement exponential backoff for 429 errorsStream for long responses— UseCompleteChatStreamingAsyncfor better UXSet appropriate timeouts— Long completions may need extended timeoutsUse structured outputs— JSON schema ensures consistent response formatMonitor token usage— Trackcompletion.Usagefor cost managementValidate tool calls— Always validate function arguments before executionError HandlingusingAzure;try{ChatCompletioncompletionawaitchatClient.CompleteChatAsync(messages);}catch(RequestFailedExceptionex)when(ex.Status429){Console.WriteLine(Rate limited. Retry after delay.);awaitTask.Delay(TimeSpan.FromSeconds(10));}catch(RequestFailedExceptionex)when(ex.Status400){Console.WriteLine($Bad request:{ex.Message});}catch(RequestFailedExceptionex){Console.WriteLine($Azure OpenAI error:{ex.Status}-{ex.Message});}Related SDKsSDKPurposeInstallAzure.AI.OpenAIAzure OpenAI client (this SDK)dotnet add package Azure.AI.OpenAIOpenAIOpenAI compatibilitydotnet add package OpenAIAzure.IdentityAuthenticationdotnet add package Azure.IdentityAzure.Search.DocumentsAI Search for RAGdotnet add package Azure.Search.DocumentsReference LinksResourceURLNuGet Packagehttps://www.nuget.org/packages/Azure.AI.OpenAIAPI Referencehttps://learn.microsoft.com/dotnet/api/azure.ai.openaiMigration Guide (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migrationQuickstarthttps://learn.microsoft.com/azure/ai-services/openai/quickstartGitHub Sourcehttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/openai/Azure.AI.OpenAI