{"id":22065436,"url":"https://github.com/tryagi/openai","last_synced_at":"2025-05-13T01:17:08.514Z","repository":{"id":177284000,"uuid":"657653236","full_name":"tryAGI/OpenAI","owner":"tryAGI","description":"C# SDK based on official OpenAI OpenAPI specification","archived":false,"fork":false,"pushed_at":"2025-05-12T07:35:24.000Z","size":14588,"stargazers_count":25,"open_issues_count":2,"forks_count":6,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-05-13T01:16:53.955Z","etag":null,"topics":["ai","api","autosdk","client","csharp","dotnet","generated","langchain","langchain-dotnet","nswag","openai","openapi","sdk","specification","swagger"],"latest_commit_sha":null,"homepage":"https://tryagi.github.io/OpenAI/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tryAGI.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"HavenDV","patreon":"havendv","ko_fi":"havendv","custom":["https://www.paypal.me/havendv","https://www.buymeacoffee.com/havendv","https://donate.stripe.com/00gfZ19zkeKLh1eaEE","https://www.upwork.com/freelancers/~017b1ad6f6af9cc189"]}},"created_at":"2023-06-23T14:28:48.000Z","updated_at":"2025-05-12T07:35:27.000Z","dependencies_parsed_at":null,"dependency_job_id":"b9d2c886-398b-4347-8228-e68f761decf5","html_url":"https://github.com/tryAGI/OpenAI","commit_stats":null,"previous_names":["tryagi/openai"],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryAGI%2FOpenAI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryAGI%2FOpenAI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryAGI%2FOpenAI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tryAGI%2FOpenAI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tryAGI","download_url":"https://codeload.github.com/tryAGI/OpenAI/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253851079,"owners_count":21973674,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","api","autosdk","client","csharp","dotnet","generated","langchain","langchain-dotnet","nswag","openai","openapi","sdk","specification","swagger"],"created_at":"2024-11-30T19:18:11.110Z","updated_at":"2025-05-13T01:17:08.445Z","avatar_url":"https://github.com/tryAGI.png","language":"C#","funding_links":["https://github.com/sponsors/HavenDV","https://patreon.com/havendv","https://ko-fi.com/havendv","https://www.paypal.me/havendv","https://www.buymeacoffee.com/havendv","https://donate.stripe.com/00gfZ19zkeKLh1eaEE","https://www.upwork.com/freelancers/~017b1ad6f6af9cc189"],"categories":[],"sub_categories":[],"readme":"# OpenAI\n\n[![Nuget package](https://img.shields.io/nuget/vpre/tryAGI.OpenAI)](https://www.nuget.org/packages/tryAGI.OpenAI/)\n[![dotnet](https://github.com/tryAGI/OpenAI/actions/workflows/dotnet.yml/badge.svg?branch=main)](https://github.com/tryAGI/OpenAI/actions/workflows/dotnet.yml)\n[![License: MIT](https://img.shields.io/github/license/tryAGI/OpenAI)](https://github.com/tryAGI/OpenAI/blob/main/LICENSE.txt)\n[![Discord](https://img.shields.io/discord/1115206893015662663?label=Discord\u0026logo=discord\u0026logoColor=white\u0026color=d82679)](https://discord.gg/Ca2xhfBf3v)\n![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/tryAGI/OpenAI)\n\n## Features 🔥\n- Fully generated C# SDK based on [official OpenAI OpenAPI specification](https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml) using [AutoSDK](https://github.com/tryAGI/AutoSDK)\n- Same day update to support new features\n- Updated and supported automatically if there are no breaking changes\n- Contains a supported list of constants such as current prices, models, and other\n- Source generator to define functions natively through C# interfaces\n- All modern .NET features - nullability, trimming, NativeAOT, etc.\n- Support .Net Framework/.Net Standard 2.0\n- Support all OpenAI API endpoints including completions, chat, embeddings, images, assistants and more.\n- Regularly tested for compatibility with popular custom providers like OpenRouter/DeepSeek/Ollama/LM Studio and many others\n\n## Documentation\nExamples and documentation can be found here: https://tryagi.github.io/OpenAI/\n\n## Usage\n```csharp\nusing var api = new OpenAiApi(\"API_KEY\");\nstring response = await api.Chat.CreateChatCompletionAsync(\n    messages: [\"Generate five random words.\"],\n    model: CreateChatCompletionRequestModel.Gpt4oMini);\nConsole.WriteLine(response); // \"apple, banana, cherry, date, elderberry\"\n\nvar enumerable = api.Chat.CreateChatCompletionAsStreamAsync(\n    messages: [\"Generate five random words.\"],\n    model: CreateChatCompletionRequestModel.Gpt4oMini);\n\nawait foreach (string response in enumerable)\n{\n    Console.WriteLine(response);\n}\n```\nIt uses three implicit conversions:\n- from `string` to `ChatCompletionRequestUserMessage`. It will always be converted to the user message.\n- from `ChatCompletionResponseMessage` to `string` . It will always contain the first choice message content.\n- from `CreateChatCompletionStreamResponse` to `string` . It will always contain the first delta content.\n\nYou still can use the full response objects if you need more information, just replace `string response` to `var response`.\n\n### Tools\n```csharp\nusing OpenAI;\nusing CSharpToJsonSchema;\n\npublic enum Unit\n{\n    Celsius,\n    Fahrenheit,\n}\n\npublic class Weather\n{\n    public string Location { get; set; } = string.Empty;\n    public double Temperature { get; set; }\n    public Unit Unit { get; set; }\n    public string Description { get; set; } = string.Empty;\n}\n\n[GenerateJsonSchema(Strict = true)] // false by default. You can't use parameters with default values in Strict mode.\npublic interface IWeatherFunctions\n{\n    [Description(\"Get the current weather in a given location\")]\n    public Task\u003cWeather\u003e GetCurrentWeatherAsync(\n        [Description(\"The city and state, e.g. San Francisco, CA\")] string location,\n        Unit unit,\n        CancellationToken cancellationToken = default);\n}\n\npublic class WeatherService : IWeatherFunctions\n{\n    public Task\u003cWeather\u003e GetCurrentWeatherAsync(string location, Unit unit = Unit.Celsius, CancellationToken cancellationToken = default)\n    {\n        return Task.FromResult(new Weather\n        {\n            Location = location,\n            Temperature = 22.0,\n            Unit = unit,\n            Description = \"Sunny\",\n        });\n    }\n}\n\nusing var api = new OpenAiApi(\"API_KEY\");\n\nvar service = new WeatherService();\nvar tools = service.AsTools().AsOpenAiTools();\n\nvar messages = new List\u003cChatCompletionRequestMessage\u003e\n{\n    \"You are a helpful weather assistant.\".AsSystemMessage(),\n    \"What is the current temperature in Dubai, UAE in Celsius?\".AsUserMessage(),\n};\nvar model = CreateChatCompletionRequestModel.Gpt4oMini;\nvar result = await api.Chat.CreateChatCompletionAsync(\n    messages,\n    model: model,\n    tools: tools);\nvar resultMessage = result.Choices.First().Message;\nmessages.Add(resultMessage.AsRequestMessage());\n\nforeach (var call in resultMessage.ToolCalls)\n{\n    var json = await service.CallAsync(\n        functionName: call.Function.Name,\n        argumentsAsJson: call.Function.Arguments);\n    messages.Add(json.AsToolMessage(call.Id));\n}\n\nvar result = await api.Chat.CreateChatCompletionAsync(\n    messages,\n    model: model,\n    tools: tools);\nvar resultMessage = result.Choices.First().Message;\nmessages.Add(resultMessage.AsRequestMessage());\n```\n```\n\u003e System: \nYou are a helpful weather assistant.\n\u003e User: \nWhat is the current temperature in Dubai, UAE in Celsius?\n\u003e Assistant: \ncall_3sptsiHzKnaxF8bs8BWxPo0B:\nGetCurrentWeather({\"location\":\"Dubai, UAE\",\"unit\":\"celsius\"})\n\u003e Tool(call_3sptsiHzKnaxF8bs8BWxPo0B):\n{\"location\":\"Dubai, UAE\",\"temperature\":22,\"unit\":\"celsius\",\"description\":\"Sunny\"}\n\u003e Assistant: \nThe current temperature in Dubai, UAE is 22°C with sunny weather.\n```\n\n### Structured Outputs\n```csharp\nusing OpenAI;\n\nusing var api = new OpenAiApi(\"API_KEY\");\n\nvar response = await api.Chat.CreateChatCompletionAsAsync\u003cWeather\u003e(\n    messages: [\"Generate random weather.\"],\n    model: CreateChatCompletionRequestModel.Gpt4oMini,\n    jsonSerializerOptions: new JsonSerializerOptions\n    {\n        Converters = {new JsonStringEnumConverter()},\n    });\n// or (if you need trimmable/NativeAOT version)\nvar response = await api.Chat.CreateChatCompletionAsAsync(\n    jsonTypeInfo: SourceGeneratedContext.Default.Weather,\n    messages: [\"Generate random weather.\"],\n    model: CreateChatCompletionRequestModel.Gpt4oMini);\n\n// response.Value1 contains the structured output\n// response.Value2 contains the CreateChatCompletionResponse object\n```\n```\nWeather:\nLocation: San Francisco, CA\nTemperature: 65\nUnit: Fahrenheit\nDescription: Partly cloudy with a light breeze and occasional sunshine.\nRaw Response:\n{\"Location\":\"San Francisco, CA\",\"Temperature\":65,\"Unit\":\"Fahrenheit\",\"Description\":\"Partly cloudy with a light breeze and occasional sunshine.\"}\n```\nAdditional code for trimmable/NativeAOT version:\n```csharp\n[JsonSourceGenerationOptions(Converters = [typeof(JsonStringEnumConverter\u003cUnit\u003e)])]\n[JsonSerializable(typeof(Weather))]\npublic partial class SourceGeneratedContext : JsonSerializerContext;\n```\n\n### Custom providers\n```csharp\nusing OpenAI;\n\nusing var api = CustomProviders.GitHubModels(\"GITHUB_TOKEN\");\nusing var api = CustomProviders.Azure(\"API_KEY\", \"ENDPOINT\");\nusing var api = CustomProviders.DeepInfra(\"API_KEY\");\nusing var api = CustomProviders.Groq(\"API_KEY\");\nusing var api = CustomProviders.XAi(\"API_KEY\");\nusing var api = CustomProviders.DeepSeek(\"API_KEY\");\nusing var api = CustomProviders.Fireworks(\"API_KEY\");\nusing var api = CustomProviders.OpenRouter(\"API_KEY\");\nusing var api = CustomProviders.Together(\"API_KEY\");\nusing var api = CustomProviders.Perplexity(\"API_KEY\");\nusing var api = CustomProviders.SambaNova(\"API_KEY\");\nusing var api = CustomProviders.Mistral(\"API_KEY\");\nusing var api = CustomProviders.Codestral(\"API_KEY\");\nusing var api = CustomProviders.Cerebras(\"API_KEY\");\nusing var api = CustomProviders.Cohere(\"API_KEY\");\nusing var api = CustomProviders.Ollama();\nusing var api = CustomProviders.LmStudio();\n```\n\n### Constants\nAll `tryGetXXX` methods return `null` if the value is not found.  \nThere also non-try methods that throw an exception if the value is not found.\n```cs\nusing OpenAI;\n\n// You can try to get the enum from string using:\nvar model = CreateChatCompletionRequestModelExtensions.ToEnum(\"gpt-4o\") ?? throw new Exception(\"Invalid model\");\n\n// Chat\nvar model = CreateChatCompletionRequestModel.Gpt4oMini;\ndouble? priceInUsd = model.TryGetPriceInUsd(\n    inputTokens: 500,\n    outputTokens: 500)\ndouble? priceInUsd = model.TryGetFineTunePriceInUsd(\n    trainingTokens: 500,\n    inputTokens: 500,\n    outputTokens: 500)\nint contextLength = model.TryGetContextLength() // 128_000\nint outputLength = model.TryGetOutputLength() // 16_000\n\n// Embeddings\nvar model = CreateEmbeddingRequestModel.TextEmbedding3Small;\nint? maxInputTokens = model.TryGetMaxInputTokens() // 8191\ndouble? priceInUsd = model.TryGetPriceInUsd(tokens: 500)\n\n// Images\ndouble? priceInUsd = CreateImageRequestModel.DallE3.TryGetPriceInUsd(\n    size: CreateImageRequestSize.x1024x1024,\n    quality: CreateImageRequestQuality.Hd)\n\n// Speech to Text\ndouble? priceInUsd = CreateTranscriptionRequestModel.Whisper1.TryGetPriceInUsd(\n    seconds: 60)\n\n// Text to Speech\ndouble? priceInUsd = CreateSpeechRequestModel.Tts1Hd.TryGetPriceInUsd(\n    characters: 1000)\n```\n\n## Support\n\nPriority place for bugs: https://github.com/tryAGI/OpenAI/issues  \nPriority place for ideas and general questions: https://github.com/tryAGI/OpenAI/discussions  \nDiscord: https://discord.gg/Ca2xhfBf3v\n\n## Acknowledgments\n\n![JetBrains logo](https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.png)\n\nThis project is supported by JetBrains through the [Open Source Support Program](https://jb.gg/OpenSourceSupport).\n\n![CodeRabbit logo](https://opengraph.githubassets.com/1c51002d7d0bbe0c4fd72ff8f2e58192702f73a7037102f77e4dbb98ac00ea8f/marketplace/coderabbitai)\n\nThis project is supported by CodeRabbit through the [Open Source Support Program](https://github.com/marketplace/coderabbitai).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftryagi%2Fopenai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftryagi%2Fopenai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftryagi%2Fopenai/lists"}