{"id":36419372,"url":"https://github.com/tddworks/openai-kotlin","last_synced_at":"2026-01-11T17:03:34.610Z","repository":{"id":221687771,"uuid":"755029221","full_name":"tddworks/openai-kotlin","owner":"tddworks","description":"OpenAI clients for kotlin multiplatform SDK, supports OpenAI, Anthropic, Azure, Gemini, Ollama with TDD","archived":false,"fork":false,"pushed_at":"2025-12-18T08:53:25.000Z","size":855,"stargazers_count":46,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-12-20T18:46:01.198Z","etag":null,"topics":["anthropic-claude","anthropic-kotlin","azureai","chatgpt","claude","claude-ai","claude-api","gemini-api","kmp","koin","kotlin","ollama-api","openai-api","openai-gateway","openai-kotlin"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tddworks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["hanrw"]}},"created_at":"2024-02-09T09:37:29.000Z","updated_at":"2025-12-18T08:53:28.000Z","dependencies_parsed_at":"2025-08-20T15:18:53.162Z","dependency_job_id":"15b8fbf9-b5f1-442d-add5-62f325f32466","html_url":"https://github.com/tddworks/openai-kotlin","commit_stats":null,"previous_names":["tddworks/openai-kotlin"],"tags_count":14,"template":false,"template_full_name":null,"purl":"pkg:github/tddworks/openai-kotlin","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tddworks%2Fopenai-kotlin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tddworks%2Fopenai-kotlin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tddworks%2Fopenai-kotlin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tddworks%2Fopenai-kotlin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tddworks","download_url":"https://codeload.github.com/tddworks/openai-kotlin/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tddworks%2Fopenai-kotlin/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28314262,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-11T14:58:17.114Z","status":"ssl_error","status_checked_at":"2026-01-11T14:55:53.580Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["anthropic-claude","anthropic-kotlin","azureai","chatgpt","claude","claude-ai","claude-api","gemini-api","kmp","koin","kotlin","ollama-api","openai-api","openai-gateway","openai-kotlin"],"created_at":"2026-01-11T17:03:34.534Z","updated_at":"2026-01-11T17:03:34.595Z","avatar_url":"https://github.com/tddworks.png","language":"Kotlin","funding_links":["https://github.com/sponsors/hanrw"],"categories":["人工智能"],"sub_categories":["LLM客户端"],"readme":"# OpenAI Kotlin\n\n![CI](https://github.com/tddworks/openai-kotlin/actions/workflows/main.yml/badge.svg)\n[![codecov](https://codecov.io/gh/tddworks/openai-kotlin/graph/badge.svg?token=ZHqC4RjnCf)](https://codecov.io/gh/tddworks/openai-kotlin)\n[![Maven Central](https://img.shields.io/maven-central/v/com.tddworks/openai-client-core?label=Maven%20Central)](https://central.sonatype.com/artifact/com.tddworks/openai-client-core)\n[![Kotlin](https://img.shields.io/badge/kotlin-2.2.21-blue.svg?logo=kotlin)](http://kotlinlang.org)\n[![KMP](https://img.shields.io/badge/Kotlin-Multiplatform-blue.svg?logo=kotlin)](https://kotlinlang.org/docs/multiplatform.html)\n[![Ktor](https://img.shields.io/badge/ktor-3.3.3-blue.svg?logo=ktor)](https://ktor.io)\n[![License](https://img.shields.io/github/license/tddworks/openai-kotlin?color=blue)](LICENSE)\n[![GitHub Release](https://img.shields.io/github/v/release/tddworks/openai-kotlin?include_prereleases\u0026label=Latest%20Release)](https://github.com/tddworks/openai-kotlin/releases)\n[![Issues](https://img.shields.io/github/issues/tddworks/openai-kotlin?color=blue)](https://github.com/tddworks/openai-kotlin/issues)\n[![Stars](https://img.shields.io/github/stars/tddworks/openai-kotlin?style=social)](https://github.com/tddworks/openai-kotlin/stargazers)\n\nA comprehensive Kotlin Multiplatform library providing unified access to multiple AI/LLM providers including OpenAI, Anthropic Claude, Google Gemini, and Ollama. Built with modern Kotlin practices and designed for seamless integration across JVM, Android, iOS, and native platforms.\n\n## ✨ Features\n\n- 🔗 **Multi-Provider Support**: OpenAI, Anthropic Claude, Google Gemini, Ollama, and custom providers\n- 🌐 **Kotlin Multiplatform**: JVM, Android, iOS, macOS, and other Kotlin/Native targets\n- 🚀 **Streaming Support**: Real-time chat completions with Flow-based streaming\n- 🔄 **Unified Gateway**: Switch between providers seamlessly with a single interface\n- 📱 **Platform-Optimized**: Native HTTP clients for each platform (Ktor CIO, NSURLSession)\n- 🎯 **Type-Safe**: Fully typed APIs with comprehensive data classes\n- 📦 **Modular Design**: Use only what you need with granular dependencies\n- 🧪 **Well-Tested**: Comprehensive test coverage with integration tests\n\n## 🚀 Quick Start\n\n### Basic OpenAI Client\n\nAdd the dependency:\n```kotlin\nimplementation(\"com.tddworks:openai-client-jvm:0.2.3\")\n```\n\n```kotlin\nimport com.tddworks.openai.api.OpenAI\nimport com.tddworks.openai.api.chat.api.*\n\n// Simple - just provide your API key\nval openAI = OpenAI.create(apiKey = \"your-api-key\")\n\n// Or with custom base URL\nval openAI = OpenAI.create(apiKey = \"your-api-key\", baseUrl = \"https://custom.api.com\")\n\n// Dynamic configuration (values that may change at runtime)\nval openAI = OpenAI.create(\n    apiKey = { settings.apiKey },\n    baseUrl = { settings.baseUrl }\n)\n\n// Chat completion\nval response = openAI.chatCompletions(\n    ChatCompletionRequest(\n        messages = listOf(ChatMessage.UserMessage(\"Hello, world!\")),\n        model = Model.GPT_4O,\n        maxTokens = 1000\n    )\n)\n\n// Streaming chat completion\nopenAI.streamChatCompletions(\n    ChatCompletionRequest(\n        messages = listOf(ChatMessage.UserMessage(\"Tell me a story\")),\n        model = Model.GPT_4O\n    )\n).collect { chunk -\u003e\n    print(chunk.choices?.firstOrNull()?.delta?.content ?: \"\")\n}\n```\n\n### Multi-Provider Gateway\n\nFor applications requiring multiple AI providers:\n\n```kotlin\nimplementation(\"com.tddworks:openai-gateway-jvm:0.2.3\")\n```\n\n```kotlin\nimport com.tddworks.openai.gateway.api.OpenAIGateway\n\n// Simple - just provide your API keys\nval gateway = OpenAIGateway.create(\n    openAIKey = \"openai-api-key\",\n    anthropicKey = \"anthropic-api-key\",\n    geminiKey = \"gemini-api-key\"\n)\n\n// Dynamic configuration\nval gateway = OpenAIGateway.create(\n    openAIKey = { settings.openAIKey },\n    anthropicKey = { settings.anthropicKey },\n    geminiKey = { settings.geminiKey }\n)\n\n// Use any provider with the same interface\nval response = gateway.chatCompletions(\n    ChatCompletionRequest(\n        messages = listOf(ChatMessage.UserMessage(\"Compare AI models\")),\n        model = Model(\"claude-3-sonnet\") // or \"llama2\", \"gpt-4\", etc.\n    )\n)\n```\n\n## 🍎 Swift / iOS / macOS\n\n### Installation via Swift Package Manager\n\nAdd the package to your `Package.swift` or via Xcode:\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/tddworks/openai-kotlin.git\", from: \"0.2.3\")\n]\n```\n\nOr add via Xcode: File → Add Package Dependencies → Enter the repository URL.\n\n### Available Frameworks\n\n| Framework | Description |\n|-----------|-------------|\n| `OpenAIClient` | OpenAI API client |\n| `AnthropicClient` | Anthropic Claude API client |\n| `GeminiClient` | Google Gemini API client |\n| `OllamaClient` | Ollama local LLM client |\n| `OpenAIGateway` | Multi-provider unified gateway |\n\n### Swift Usage Examples\n\n#### OpenAI\n\n```swift\nimport OpenAIClient\n\n// Simple configuration\nlet client = OpenAICompanion.shared.create(apiKey: \"your-api-key\")\n\n// With custom base URL\nlet client = OpenAICompanion.shared.create(apiKey: \"your-api-key\", baseUrl: \"https://custom.api.com\")\n\n// Dynamic configuration (values that may change at runtime)\nlet client = OpenAICompanion.shared.create(\n    apiKey: { Settings.shared.apiKey },\n    baseUrl: { Settings.shared.baseUrl }\n)\n```\n\n#### Anthropic Claude\n\n```swift\nimport AnthropicClient\n\nlet client = AnthropicCompanion.shared.create(apiKey: \"your-api-key\")\n\n// With custom configuration\nlet client = AnthropicCompanion.shared.create(\n    apiKey: \"your-api-key\",\n    baseUrl: \"https://api.anthropic.com\",\n    anthropicVersion: \"2023-06-01\"\n)\n```\n\n#### Google Gemini\n\n```swift\nimport GeminiClient\n\nlet client = GeminiCompanion.shared.create(apiKey: \"your-api-key\")\n```\n\n#### Ollama (Local)\n\n```swift\nimport OllamaClient\n\n// Default localhost:11434\nlet client = OllamaCompanion.shared.create()\n\n// Custom host\nlet client = OllamaCompanion.shared.create(baseUrl: \"192.168.1.100\", port: 11434)\n```\n\n#### Multi-Provider Gateway\n\n```swift\nimport OpenAIGateway\n\nlet gateway = OpenAIGatewayCompanion.shared.create(\n    openAIKey: \"your-openai-key\",\n    anthropicKey: \"your-anthropic-key\",\n    geminiKey: \"your-gemini-key\"\n)\n\n// Dynamic configuration\nlet gateway = OpenAIGatewayCompanion.shared.create(\n    openAIKey: { Settings.shared.openAIKey },\n    anthropicKey: { Settings.shared.anthropicKey },\n    geminiKey: { Settings.shared.geminiKey }\n)\n```\n\n### Swift Chat Example\n\n```swift\nimport OpenAIClient\n\nlet openAI = OpenAI.shared.create(apiKey: \"your-api-key\")\n\n// Chat completion\nTask {\n    let response = try await openAI.chatCompletions(\n        request: ChatCompletionRequest(\n            messages: [ChatMessage.UserMessage(content: \"Hello!\")],\n            model: Model.gpt4o\n        )\n    )\n    print(response.choices?.first?.message?.content ?? \"\")\n}\n\n// Streaming\nfor try await chunk in openAI.streamChatCompletions(request: request) {\n    print(chunk.choices?.first?.delta?.content ?? \"\", terminator: \"\")\n}\n```\n\n## 📦 Installation\n\n### Gradle (Kotlin DSL)\n\nFor multiplatform projects:\n```kotlin\nkotlin {\n    sourceSets {\n        commonMain.dependencies {\n            implementation(\"com.tddworks:openai-client-core:0.2.3\")\n            implementation(\"com.tddworks:openai-gateway-core:0.2.3\")\n        }\n    }\n}\n```\n\nFor JVM/Android projects:\n```kotlin\ndependencies {\n    implementation(\"com.tddworks:openai-client-jvm:0.2.3\")\n    implementation(\"com.tddworks:anthropic-client-jvm:0.2.3\")\n    implementation(\"com.tddworks:ollama-client-jvm:0.2.3\")\n    implementation(\"com.tddworks:gemini-client-jvm:0.2.3\")\n    implementation(\"com.tddworks:openai-gateway-jvm:0.2.3\")\n}\n```\n\n### Maven\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.tddworks\u003c/groupId\u003e\n    \u003cartifactId\u003eopenai-client-jvm\u003c/artifactId\u003e\n    \u003cversion\u003e0.2.3\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### Available Modules\n\n| Module | Description | Platforms |\n|--------|-------------|-----------|\n| `openai-client-*` | OpenAI API client (chat, images, completions) | JVM, iOS, macOS |\n| `anthropic-client-*` | Anthropic Claude API client | JVM, iOS, macOS |\n| `ollama-client-*` | Ollama local LLM client | JVM, iOS, macOS |\n| `gemini-client-*` | Google Gemini API client | JVM, iOS, macOS |\n| `openai-gateway-*` | Multi-provider gateway | JVM, iOS, macOS |\n| `common` | Shared networking utilities | All platforms |\n\n## 💡 Usage Examples\n\n### Image Generation\n\n```kotlin\nval images = openAI.images(\n    ImageCreate(\n        prompt = \"A beautiful sunset over mountains\",\n        size = Size.SIZE_1024x1024,\n        quality = Quality.HD,\n        n = 1\n    )\n)\n```\n\n### Vision (Image Analysis)\n\n```kotlin\nval response = openAI.chatCompletions(\n    ChatCompletionRequest(\n        messages = listOf(\n            ChatMessage.UserMessage(\n                content = listOf(\n                    VisionMessageContent.TextContent(\"What's in this image?\"),\n                    VisionMessageContent.ImageContent(\n                        imageUrl = ImageUrl(\"data:image/jpeg;base64,${base64Image}\")\n                    )\n                )\n            )\n        ),\n        model = Model.GPT_4_VISION,\n        maxTokens = 1000\n    )\n)\n```\n\n### Anthropic Claude\n\n```kotlin\nimport com.tddworks.anthropic.api.Anthropic\n\nval claude = Anthropic.create(apiKey = \"your-anthropic-key\")\n\nval message = claude.messages(\n    CreateMessageRequest(\n        messages = listOf(\n            Message(\n                role = Role.USER,\n                content = listOf(ContentMessage.TextContent(\"Explain quantum computing\"))\n            )\n        ),\n        model = AnthropicModel.CLAUDE_3_SONNET,\n        maxTokens = 1000\n    )\n)\n```\n\n### Local Ollama\n\n```kotlin\nimport com.tddworks.ollama.api.Ollama\n\n// Default localhost:11434\nval ollama = Ollama.create()\n\n// Or custom host\nval ollama = Ollama.create(baseUrl = \"192.168.1.100\", port = 11434)\n\nval response = ollama.chat(\n    OllamaChatRequest(\n        model = OllamaModel.LLAMA2.value,\n        messages = listOf(\n            OllamaChatMessage(\n                role = \"user\",\n                content = \"What is the capital of France?\"\n            )\n        )\n    )\n)\n```\n\n## 🏗️ Architecture\n\nThis library follows a clean, modular architecture:\n\n```\n┌─────────────────────┐\n│   Applications      │ (Your Kotlin/Java/Swift apps)\n├─────────────────────┤\n│   OpenAI Gateway    │ (Unified interface for all providers)\n├─────────────────────┤\n│   Provider Clients  │ (OpenAI, Anthropic, Ollama, Gemini)\n├─────────────────────┤\n│   Common Networking │ (HTTP abstraction, serialization)\n└─────────────────────┘\n```\n\n### Core Components\n\n- **HttpRequester**: Cross-platform HTTP client abstraction using Ktor\n- **Provider Configs**: Type-safe configuration for each AI provider\n- **Streaming Support**: Flow-based streaming for real-time responses\n- **Error Handling**: Comprehensive exception hierarchy with detailed error information\n- **Dependency Injection**: Koin-based DI for clean separation of concerns\n\n## 🌍 Platform Support\n\n### Supported Platforms\n\n- ✅ **JVM** (Java 8+, Android API 21+)\n- ✅ **iOS** (iOS 14+)\n- ✅ **macOS** (macOS 11+)\n- 🚧 **watchOS** (planned)\n- 🚧 **tvOS** (planned)\n- 🚧 **Linux** (planned)\n- 🚧 **Windows** (planned)\n\n### Platform-Specific Features\n\n| Platform | HTTP Client | Streaming | Local Storage |\n|----------|-------------|-----------|---------------|\n| JVM      | Ktor CIO    | ✅        | File System  |\n| Android  | Ktor CIO    | ✅        | File System  |\n| iOS      | NSURLSession| ✅        | UserDefaults |\n| macOS    | NSURLSession| ✅        | UserDefaults |\n\n## 🔧 Configuration\n\n### Environment Variables\n\nSet these environment variables or provide them programmatically:\n\n```bash\nOPENAI_API_KEY=your-openai-key\nANTHROPIC_API_KEY=your-anthropic-key\nGEMINI_API_KEY=your-gemini-key\n```\n\n### Configuration Examples\n\n#### OpenAI with Custom Base URL\n\n```kotlin\nval openAI = OpenAI.create(\n    apiKey = System.getenv(\"OPENAI_API_KEY\"),\n    baseUrl = \"https://api.openai.com/v1\"\n)\n\n// Or with dynamic configuration\nval openAI = OpenAI.create(\n    apiKey = { System.getenv(\"OPENAI_API_KEY\") },\n    baseUrl = { settings.baseUrl }\n)\n```\n\n#### Anthropic with Custom Version\n\n```kotlin\nval anthropic = Anthropic.create(\n    apiKey = System.getenv(\"ANTHROPIC_API_KEY\"),\n    baseUrl = \"https://api.anthropic.com\",\n    anthropicVersion = \"2023-06-01\"\n)\n```\n\n## 🧪 Testing\n\n### Unit Tests\n```bash\n./gradlew test\n```\n\n### Integration Tests\n```bash\n./gradlew integrationTest\n```\n\n### Code Coverage\n```bash\n./gradlew koverHtmlReport\nopen build/reports/kover/html/index.html\n```\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n1. **Clone the repository**:\n   ```bash\n   git clone https://github.com/tddworks/openai-kotlin.git\n   cd openai-kotlin\n   ```\n\n2. **Build the project**:\n   ```bash\n   ./gradlew build\n   ```\n\n3. **Run tests**:\n   ```bash\n   ./gradlew allTests\n   ```\n\n4. **Format code**:\n   ```bash\n   ./gradlew spotlessApply\n   ```\n\n### Code Style\n\nThis project uses [Spotless](https://github.com/diffplug/spotless) for code formatting. Please run `./gradlew spotlessApply` before submitting PRs.\n\n## 📄 License\n\n```\nCopyright 2024 TDD Works\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n\n## 🙋 Support\n\n- 📖 [Documentation](https://tddworks.github.io/openai-kotlin)\n- 💬 [GitHub Discussions](https://github.com/tddworks/openai-kotlin/discussions)\n- 🐛 [Issue Tracker](https://github.com/tddworks/openai-kotlin/issues)\n- 📧 Email: support@tddworks.com\n\n## 🌟 Acknowledgments\n\n- [OpenAI](https://openai.com) for their powerful APIs\n- [Anthropic](https://anthropic.com) for Claude AI\n- [Ollama](https://ollama.ai) for local LLM support  \n- [Google](https://ai.google.dev) for Gemini API\n- [JetBrains](https://jetbrains.com) for Kotlin Multiplatform\n- [Ktor](https://ktor.io) for cross-platform HTTP client\n\n---\n\nMade with ❤️ by [TDD Works](https://github.com/tddworks)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftddworks%2Fopenai-kotlin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftddworks%2Fopenai-kotlin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftddworks%2Fopenai-kotlin/lists"}