包名和命名空间已从 Betalgo.OpenAI 改为 Betalgo.Ranul.OpenAI,旧引用需迁移;9.0.0 起不再支持 .NET 6 和 .NET 7;Playground 示例会增删文件和模型,建议用独立账号而非主账号
openai
betalgoMIT更新放缓面向 .NET 开发者的 OpenAI API 封装库,可在 C# 项目里直接调用 ChatGPT、DALL·E、Whisper 和 Azure OpenAI 服务。
.NET library for the OpenAI service API by Betalgo Ranul
Install-Package Betalgo.Ranul.OpenAIREADME 未说明
社区维护的 .NET 库,让你在 C# 项目里直接调用 OpenAI API
面向 .NET 开发者的 OpenAI API 封装库,可在 C# 项目里直接调用 ChatGPT、DALL·E、Whisper 和 Azure OpenAI 服务。
核心能力
- 封装 ChatCompletion 等接口,用强类型请求对象调用
- 支持依赖注入,一行 AddOpenAIService 完成注册
- 可设置默认模型,如 SetDefaultModelId(Models.Gpt_4o)
- 提供 Realtime API 与实验性 Utilities 扩展包
- 函数工具参数自动生成 JSON Schema
容易踩的坑
- v9.1.0最新正式版2025-07-11 · 2025-07-11 19:24 UTC
What's Changed
- Update image generation parameters and usage tracking by @kayhantolga in https://github.com/betalgo/openai/pull/722
- Enhance MessageContent with file support and refactoring by @kayhantolga in https://github.com/betalgo/openai/pull/723
- Added parameters on RequestModels for using new OpenAI features by @OmarSilviniDocsMarshal in https://github.com/betalgo/openai/pull/721
- Add support for JSON Schema $defs, definitions, $ref, oneOf, anyOf and others in PropertyDefinition by @repko-artem in https://github.com/betalgo/openai/pull/726
- Added voice enums for the TTS and Realtime endpoints. by @sipsorcery in https://github.com/betalgo/openai/pull/714
- 9.1.0 by @kayhantolga in https://github.com/betalgo/openai/pull/728
New Contributors
- @OmarSilviniDocsMarshal made their first contribution in https://github.com/betalgo/openai/pull/721
- @repko-artem made their first contribution in https://github.com/betalgo/openai/pull/726
- @sipsorcery made their first contribution in https://github.com/betalgo/openai/pull/714
Full Changelog: https://github.com/betalgo/openai/compare/v9.0.4...v9.1.0
- v9.0.42025-07-11 · 2025-07-11 19:24 UTC
查看更新说明
What's Changed
- sync by @kayhantolga in https://github.com/betalgo/openai/pull/713
- Update to M.E.AI 9.4.3-preview.1.25230.7 by @jozkee in https://github.com/betalgo/openai/pull/715
- Apply OpenAI-compatible function schema transformations to the chat client by @eiriktsarpalis in https://github.com/betalgo/openai/pull/718
- 9.0.4 by @kayhantolga in https://github.com/betalgo/openai/pull/719
New Contributors
- @eiriktsarpalis made their first contribution in https://github.com/betalgo/openai/pull/718
Full Changelog: https://github.com/betalgo/openai/compare/v9.0.3...v9.0.4
- v9.0.32025-04-23 · 2025-04-23 23:58 UTC
查看更新说明
What's Changed
- Added the Gpt-4.1 series (base, mini, nano, and all snapshots) by @kinetiq in https://github.com/betalgo/openai/pull/711
- Update to M.E.AI 9.4.0-preview.1.25207.5 by @jozkee in https://github.com/betalgo/openai/pull/707
- 9.0.3 by @kayhantolga in https://github.com/betalgo/openai/pull/712
New Contributors
- @kinetiq made their first contribution in https://github.com/betalgo/openai/pull/711
- @jozkee made their first contribution in https://github.com/betalgo/openai/pull/707
Full Changelog: https://github.com/betalgo/openai/compare/v9.0.2...v9.0.3
- v9.0.22025-04-23 · 2025-04-23 23:58 UTC
查看更新说明
What's Changed
- feat: Add support for reasoning effort, o1 and o3-mini models by @RealWave-Skylar in https://github.com/betalgo/openai/pull/701
- Update to M.E.AI 9.3.0-preview.1.25161.3 by @stephentoub in https://github.com/betalgo/openai/pull/702
- Support
reasoning_contentby @MayDay-wpf in https://github.com/betalgo/openai/pull/700 - 9.0.2 by @kayhantolga in https://github.com/betalgo/openai/pull/705
New Contributors
- @RealWave-Skylar made their first contribution in https://github.com/betalgo/openai/pull/701
- @MayDay-wpf made their first contribution in https://github.com/betalgo/openai/pull/700
Full Changelog: https://github.com/betalgo/openai/compare/v9.0.1...v9.0.2
- v9.0.12024-12-04 · 2024-12-04 23:00 UTC
查看更新说明
9.0.1
- Message list now accept RunId
- Upgraded to Microsoft.Extensions.AI version 9.0.1, which resolves the "Method not found: '!!0" error when used alongside other SDKs with different versions.
What's Changed
- addresses #682, extends PaginationRequest as MessageListRequest adding run_id by @jmuller3 in https://github.com/betalgo/openai/pull/683
- Update M.E.AI to 9.0.1-preview.1.24570.5 by @stephentoub in https://github.com/betalgo/openai/pull/686
- 9.0.1 by @kayhantolga in https://github.com/betalgo/openai/pull/687
Full Changelog: https://github.com/betalgo/openai/compare/v9.0.0...v9.0.1
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
Overview
A .NET Library for accessing OpenAI's API, provided as a community library. This Library allows you to integrate OpenAI's capabilities into your .NET applications with ease.
⭐ We appreciate your star, it helps!
Community Links
Install Packages
Core Library
⚠️ We now have new PackageId and new Namespace. ⚠️
⚠️ Betalgo.OpenAI is now Betalgo.Ranul.OpenAI ⚠️
Install-Package Betalgo.Ranul.OpenAI
Experimental Utilities Library
Install-Package Betalgo.OpenAI.Utilities
Documentation and Links
- Realtime API ✨NEW
- Wiki Page
- Feature Availability Table
- Change Logs
- Migration Guide for Breaking Changes
- Contracts Upgrade Guide (9.2.0)
Acknowledgements
Maintenance of this project is made possible by all the bug reporters, contributors, and sponsors.
💖 Sponsors:
@betalgo, Laser Cat Eyes
@tylerje, @oferavnery, @MayDay-wpf, @AnukarOP, @Removable, @Scar11
Sample Usage
The repository contains a sample project named OpenAI.Playground to help you understand how the library works. However, please exercise caution while experimenting, as some test methods may result in unintended consequences such as file deletion or fine-tuning.
!! It is highly recommended that you use a separate account instead of your primary account while using the playground. Some test methods may add or delete your files and models, potentially causing unwanted issues. !!
Your API Key can be obtained from here: https://platform.openai.com/account/api-keys
Your Organization ID can be found here: https://platform.openai.com/account/org-settings
Without Using Dependency Injection
var openAIService = new OpenAIService(new OpenAIOptions()
{
ApiKey = Environment.GetEnvironmentVariable("MY_OPEN_AI_API_KEY")
});
Using Dependency Injection
secrets.json
"OpenAIServiceOptions": {
"ApiKey": "Your api key goes here",
"Organization": "Your Organization Id goes here (optional)",
"UseBeta": "true/false (optional)"
}
(To use user secrets: Right-click your project name in "Solution Explorer", then click "Manage User Secrets". This is a good way to keep your API keys secure.)
Program.cs
serviceCollection.AddOpenAIService();
OR
serviceCollection.AddOpenAIService(settings => { settings.ApiKey = Environment.GetEnvironmentVariable("MY_OPEN_AI_API_KEY"); });
After injecting your service, you can retrieve it from the service provider:
var openAiService = serviceProvider.GetRequiredService<IOpenAIService>();
You can set a default model (optional):
openAiService.SetDefaultModelId(Models.Gpt_4o);
Chat GPT Sample
var completionResult = await openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest
{
Messages = new List<ChatMessage>
{
ChatMessage.FromSystem("You are a helpful assistant."),
ChatMessage.FromUser("Who won the world series in 2020?"),
ChatMessage.FromAssistant("The Los Angeles Dodgers won the World Series in 2020."),
ChatMessage.FromUser("Where was it played?")
},
Model = Models.Gpt_4o,
});
if (completionResult.Successful)
{
Console.WriteLine(completionResult.Choices.First().Message.Content);
}
Notes
Due to time constraints, not all methods have been thoroughly tested or fully documented. If you encounter any issues, please report them or submit a pull request. Your contributions are always appreciated.
Needless to say, I cannot accept responsibility for any damage caused by using the library.
Changelog
9.2.4
- Fixed function tool schema generation so parameters always emit a JSON Schema
type: "object"and avoidinvalid_function_parameterserrors likeschema must be a JSON Schema of 'type: "object"', got 'type: "None"'.
9.2.0
- Introduced
Betalgo.Ranul.OpenAI.Contractsproject for centralized request/response models, enums/value types, and capability interfaces. - Replaced legacy image request models with Contracts equivalents:
CreateImageRequest,CreateImageEditRequest,CreateImageVariationRequest
- Reorganized image enums under
Betalgo.Ranul.OpenAI.Contracts.Enums.Image.*and added value types (ImageOutputFormat,ImageResponseFormat,ImageSize,ImageModeration). - Replaced
VoiceEnumwithVoice(value type). ReplacedMessageRolewithChatCompletionRoleand/orAssistantMessageRole. - Added new response base types:
ResponseBase,ResponseBaseHeaderValues, improved header parsing and usage exposure. - Updated
IImageServiceto consume Contracts request models and returnImageResponsefor image create. Edit/variation remain legacy responses for now. - This is the first step of a gradual migration; changes are kept minimal and may evolve after testing.
- See the detailed guide: Contracts Upgrade Guide (9.2.0)
9.1.0
Image Generation
- Added
UsageModelto include detailed token usage tracking for image generation responses.
JSON Schema Validation
- Enhanced
FunctionParameterswithMultipleOf,Minimum,Maximum, andPatternsupport. - Added
SingleOrArrayToListConverterto handle single values or arrays.
Code Improvements
- Refactored
MessageContentwith expression-bodied helpers and added binary file support. - Converted filter type definitions in
ToolDefinitionfromstatic stringtoconst stringfor clarity and performance. - Simplified filter creation methods.
Documentation and Formatting
- Improved comments and formatting in
ToolDefinition. - Fixed BOM character issue in
FunctionParameters.
9.0.4
- Updated
Microsoft.Extensions.AIto version9.5.0
9.0.3
- Updated
Microsoft.Extensions.AIto version9.4.0-preview.1.25207.5 - Added new models to the model list
9.0.2
- Updated
Microsoft.Extensions.AIto version9.3.0-preview.1.25114.11 - Added reasoning effort parameters
- Added
o1ando3-minimodels to the model list
9.0.1
- Message list now accept RunId
- Upgraded to Microsoft.Extensions.AI version 9.0.1, which resolves the "Method not found: '!!0" error when used alongside other SDKs with different versions.
9.0.0
- .NET 9 support added.
- ⚠️ Support for .NET 6 and .NET 7 has ended.
- Fixed utility library issues and synced with latest version.
More Change Logs
For any issues, contributions, or feedback, feel free to reach out or submit a pull request.
Betalgo X: Betalgo (@Betalgo) / X (twitter.com)
Betalgo Linkedin: Betalgo | LinkedIn
Tolga X: Tolga Kayhan (@kayhantolga) / X (twitter.com)
Tolga Linkedin: Tolga Kayhan | LinkedIn