https://github.com/tddworks/openai-kotlin
OpenAI clients for kotlin multiplatform SDK, supports OpenAI, Anthropic, Azure, Gemini, Ollama with TDD
https://github.com/tddworks/openai-kotlin
anthropic-claude anthropic-kotlin azureai chatgpt claude claude-ai claude-api gemini-api kmp koin kotlin ollama-api openai-api openai-gateway openai-kotlin
Last synced: 5 months ago
JSON representation
OpenAI clients for kotlin multiplatform SDK, supports OpenAI, Anthropic, Azure, Gemini, Ollama with TDD
- Host: GitHub
- URL: https://github.com/tddworks/openai-kotlin
- Owner: tddworks
- License: apache-2.0
- Created: 2024-02-09T09:37:29.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2025-12-18T08:53:25.000Z (6 months ago)
- Last Synced: 2025-12-20T18:46:01.198Z (5 months ago)
- 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
- Language: Kotlin
- Homepage:
- Size: 835 KB
- Stars: 46
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- awesome-java - OpenAI Kotlin
README
# OpenAI Kotlin

[](https://codecov.io/gh/tddworks/openai-kotlin)
[](https://central.sonatype.com/artifact/com.tddworks/openai-client-core)
[](http://kotlinlang.org)
[](https://kotlinlang.org/docs/multiplatform.html)
[](https://ktor.io)
[](LICENSE)
[](https://github.com/tddworks/openai-kotlin/releases)
[](https://github.com/tddworks/openai-kotlin/issues)
[](https://github.com/tddworks/openai-kotlin/stargazers)
A 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.
## โจ Features
- ๐ **Multi-Provider Support**: OpenAI, Anthropic Claude, Google Gemini, Ollama, and custom providers
- ๐ **Kotlin Multiplatform**: JVM, Android, iOS, macOS, and other Kotlin/Native targets
- ๐ **Streaming Support**: Real-time chat completions with Flow-based streaming
- ๐ **Unified Gateway**: Switch between providers seamlessly with a single interface
- ๐ฑ **Platform-Optimized**: Native HTTP clients for each platform (Ktor CIO, NSURLSession)
- ๐ฏ **Type-Safe**: Fully typed APIs with comprehensive data classes
- ๐ฆ **Modular Design**: Use only what you need with granular dependencies
- ๐งช **Well-Tested**: Comprehensive test coverage with integration tests
## ๐ Quick Start
### Basic OpenAI Client
Add the dependency:
```kotlin
implementation("com.tddworks:openai-client-jvm:0.2.3")
```
```kotlin
import com.tddworks.openai.api.OpenAI
import com.tddworks.openai.api.chat.api.*
// Simple - just provide your API key
val openAI = OpenAI.create(apiKey = "your-api-key")
// Or with custom base URL
val openAI = OpenAI.create(apiKey = "your-api-key", baseUrl = "https://custom.api.com")
// Dynamic configuration (values that may change at runtime)
val openAI = OpenAI.create(
apiKey = { settings.apiKey },
baseUrl = { settings.baseUrl }
)
// Chat completion
val response = openAI.chatCompletions(
ChatCompletionRequest(
messages = listOf(ChatMessage.UserMessage("Hello, world!")),
model = Model.GPT_4O,
maxTokens = 1000
)
)
// Streaming chat completion
openAI.streamChatCompletions(
ChatCompletionRequest(
messages = listOf(ChatMessage.UserMessage("Tell me a story")),
model = Model.GPT_4O
)
).collect { chunk ->
print(chunk.choices?.firstOrNull()?.delta?.content ?: "")
}
```
### Multi-Provider Gateway
For applications requiring multiple AI providers:
```kotlin
implementation("com.tddworks:openai-gateway-jvm:0.2.3")
```
```kotlin
import com.tddworks.openai.gateway.api.OpenAIGateway
// Simple - just provide your API keys
val gateway = OpenAIGateway.create(
openAIKey = "openai-api-key",
anthropicKey = "anthropic-api-key",
geminiKey = "gemini-api-key"
)
// Dynamic configuration
val gateway = OpenAIGateway.create(
openAIKey = { settings.openAIKey },
anthropicKey = { settings.anthropicKey },
geminiKey = { settings.geminiKey }
)
// Use any provider with the same interface
val response = gateway.chatCompletions(
ChatCompletionRequest(
messages = listOf(ChatMessage.UserMessage("Compare AI models")),
model = Model("claude-3-sonnet") // or "llama2", "gpt-4", etc.
)
)
```
## ๐ Swift / iOS / macOS
### Installation via Swift Package Manager
Add the package to your `Package.swift` or via Xcode:
```swift
dependencies: [
.package(url: "https://github.com/tddworks/openai-kotlin.git", from: "0.2.3")
]
```
Or add via Xcode: File โ Add Package Dependencies โ Enter the repository URL.
### Available Frameworks
| Framework | Description |
|-----------|-------------|
| `OpenAIClient` | OpenAI API client |
| `AnthropicClient` | Anthropic Claude API client |
| `GeminiClient` | Google Gemini API client |
| `OllamaClient` | Ollama local LLM client |
| `OpenAIGateway` | Multi-provider unified gateway |
### Swift Usage Examples
#### OpenAI
```swift
import OpenAIClient
// Simple configuration
let client = OpenAICompanion.shared.create(apiKey: "your-api-key")
// With custom base URL
let client = OpenAICompanion.shared.create(apiKey: "your-api-key", baseUrl: "https://custom.api.com")
// Dynamic configuration (values that may change at runtime)
let client = OpenAICompanion.shared.create(
apiKey: { Settings.shared.apiKey },
baseUrl: { Settings.shared.baseUrl }
)
```
#### Anthropic Claude
```swift
import AnthropicClient
let client = AnthropicCompanion.shared.create(apiKey: "your-api-key")
// With custom configuration
let client = AnthropicCompanion.shared.create(
apiKey: "your-api-key",
baseUrl: "https://api.anthropic.com",
anthropicVersion: "2023-06-01"
)
```
#### Google Gemini
```swift
import GeminiClient
let client = GeminiCompanion.shared.create(apiKey: "your-api-key")
```
#### Ollama (Local)
```swift
import OllamaClient
// Default localhost:11434
let client = OllamaCompanion.shared.create()
// Custom host
let client = OllamaCompanion.shared.create(baseUrl: "192.168.1.100", port: 11434)
```
#### Multi-Provider Gateway
```swift
import OpenAIGateway
let gateway = OpenAIGatewayCompanion.shared.create(
openAIKey: "your-openai-key",
anthropicKey: "your-anthropic-key",
geminiKey: "your-gemini-key"
)
// Dynamic configuration
let gateway = OpenAIGatewayCompanion.shared.create(
openAIKey: { Settings.shared.openAIKey },
anthropicKey: { Settings.shared.anthropicKey },
geminiKey: { Settings.shared.geminiKey }
)
```
### Swift Chat Example
```swift
import OpenAIClient
let openAI = OpenAI.shared.create(apiKey: "your-api-key")
// Chat completion
Task {
let response = try await openAI.chatCompletions(
request: ChatCompletionRequest(
messages: [ChatMessage.UserMessage(content: "Hello!")],
model: Model.gpt4o
)
)
print(response.choices?.first?.message?.content ?? "")
}
// Streaming
for try await chunk in openAI.streamChatCompletions(request: request) {
print(chunk.choices?.first?.delta?.content ?? "", terminator: "")
}
```
## ๐ฆ Installation
### Gradle (Kotlin DSL)
For multiplatform projects:
```kotlin
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.tddworks:openai-client-core:0.2.3")
implementation("com.tddworks:openai-gateway-core:0.2.3")
}
}
}
```
For JVM/Android projects:
```kotlin
dependencies {
implementation("com.tddworks:openai-client-jvm:0.2.3")
implementation("com.tddworks:anthropic-client-jvm:0.2.3")
implementation("com.tddworks:ollama-client-jvm:0.2.3")
implementation("com.tddworks:gemini-client-jvm:0.2.3")
implementation("com.tddworks:openai-gateway-jvm:0.2.3")
}
```
### Maven
```xml
com.tddworks
openai-client-jvm
0.2.3
```
### Available Modules
| Module | Description | Platforms |
|--------|-------------|-----------|
| `openai-client-*` | OpenAI API client (chat, images, completions) | JVM, iOS, macOS |
| `anthropic-client-*` | Anthropic Claude API client | JVM, iOS, macOS |
| `ollama-client-*` | Ollama local LLM client | JVM, iOS, macOS |
| `gemini-client-*` | Google Gemini API client | JVM, iOS, macOS |
| `openai-gateway-*` | Multi-provider gateway | JVM, iOS, macOS |
| `common` | Shared networking utilities | All platforms |
## ๐ก Usage Examples
### Image Generation
```kotlin
val images = openAI.images(
ImageCreate(
prompt = "A beautiful sunset over mountains",
size = Size.SIZE_1024x1024,
quality = Quality.HD,
n = 1
)
)
```
### Vision (Image Analysis)
```kotlin
val response = openAI.chatCompletions(
ChatCompletionRequest(
messages = listOf(
ChatMessage.UserMessage(
content = listOf(
VisionMessageContent.TextContent("What's in this image?"),
VisionMessageContent.ImageContent(
imageUrl = ImageUrl("data:image/jpeg;base64,${base64Image}")
)
)
)
),
model = Model.GPT_4_VISION,
maxTokens = 1000
)
)
```
### Anthropic Claude
```kotlin
import com.tddworks.anthropic.api.Anthropic
val claude = Anthropic.create(apiKey = "your-anthropic-key")
val message = claude.messages(
CreateMessageRequest(
messages = listOf(
Message(
role = Role.USER,
content = listOf(ContentMessage.TextContent("Explain quantum computing"))
)
),
model = AnthropicModel.CLAUDE_3_SONNET,
maxTokens = 1000
)
)
```
### Local Ollama
```kotlin
import com.tddworks.ollama.api.Ollama
// Default localhost:11434
val ollama = Ollama.create()
// Or custom host
val ollama = Ollama.create(baseUrl = "192.168.1.100", port = 11434)
val response = ollama.chat(
OllamaChatRequest(
model = OllamaModel.LLAMA2.value,
messages = listOf(
OllamaChatMessage(
role = "user",
content = "What is the capital of France?"
)
)
)
)
```
## ๐๏ธ Architecture
This library follows a clean, modular architecture:
```
โโโโโโโโโโโโโโโโโโโโโโโ
โ Applications โ (Your Kotlin/Java/Swift apps)
โโโโโโโโโโโโโโโโโโโโโโโค
โ OpenAI Gateway โ (Unified interface for all providers)
โโโโโโโโโโโโโโโโโโโโโโโค
โ Provider Clients โ (OpenAI, Anthropic, Ollama, Gemini)
โโโโโโโโโโโโโโโโโโโโโโโค
โ Common Networking โ (HTTP abstraction, serialization)
โโโโโโโโโโโโโโโโโโโโโโโ
```
### Core Components
- **HttpRequester**: Cross-platform HTTP client abstraction using Ktor
- **Provider Configs**: Type-safe configuration for each AI provider
- **Streaming Support**: Flow-based streaming for real-time responses
- **Error Handling**: Comprehensive exception hierarchy with detailed error information
- **Dependency Injection**: Koin-based DI for clean separation of concerns
## ๐ Platform Support
### Supported Platforms
- โ
**JVM** (Java 8+, Android API 21+)
- โ
**iOS** (iOS 14+)
- โ
**macOS** (macOS 11+)
- ๐ง **watchOS** (planned)
- ๐ง **tvOS** (planned)
- ๐ง **Linux** (planned)
- ๐ง **Windows** (planned)
### Platform-Specific Features
| Platform | HTTP Client | Streaming | Local Storage |
|----------|-------------|-----------|---------------|
| JVM | Ktor CIO | โ
| File System |
| Android | Ktor CIO | โ
| File System |
| iOS | NSURLSession| โ
| UserDefaults |
| macOS | NSURLSession| โ
| UserDefaults |
## ๐ง Configuration
### Environment Variables
Set these environment variables or provide them programmatically:
```bash
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
GEMINI_API_KEY=your-gemini-key
```
### Configuration Examples
#### OpenAI with Custom Base URL
```kotlin
val openAI = OpenAI.create(
apiKey = System.getenv("OPENAI_API_KEY"),
baseUrl = "https://api.openai.com/v1"
)
// Or with dynamic configuration
val openAI = OpenAI.create(
apiKey = { System.getenv("OPENAI_API_KEY") },
baseUrl = { settings.baseUrl }
)
```
#### Anthropic with Custom Version
```kotlin
val anthropic = Anthropic.create(
apiKey = System.getenv("ANTHROPIC_API_KEY"),
baseUrl = "https://api.anthropic.com",
anthropicVersion = "2023-06-01"
)
```
## ๐งช Testing
### Unit Tests
```bash
./gradlew test
```
### Integration Tests
```bash
./gradlew integrationTest
```
### Code Coverage
```bash
./gradlew koverHtmlReport
open build/reports/kover/html/index.html
```
## ๐ค Contributing
We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.
### Development Setup
1. **Clone the repository**:
```bash
git clone https://github.com/tddworks/openai-kotlin.git
cd openai-kotlin
```
2. **Build the project**:
```bash
./gradlew build
```
3. **Run tests**:
```bash
./gradlew allTests
```
4. **Format code**:
```bash
./gradlew spotlessApply
```
### Code Style
This project uses [Spotless](https://github.com/diffplug/spotless) for code formatting. Please run `./gradlew spotlessApply` before submitting PRs.
## ๐ License
```
Copyright 2024 TDD Works
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
## ๐ Support
- ๐ [Documentation](https://tddworks.github.io/openai-kotlin)
- ๐ฌ [GitHub Discussions](https://github.com/tddworks/openai-kotlin/discussions)
- ๐ [Issue Tracker](https://github.com/tddworks/openai-kotlin/issues)
- ๐ง Email: support@tddworks.com
## ๐ Acknowledgments
- [OpenAI](https://openai.com) for their powerful APIs
- [Anthropic](https://anthropic.com) for Claude AI
- [Ollama](https://ollama.ai) for local LLM support
- [Google](https://ai.google.dev) for Gemini API
- [JetBrains](https://jetbrains.com) for Kotlin Multiplatform
- [Ktor](https://ktor.io) for cross-platform HTTP client
---
Made with โค๏ธ by [TDD Works](https://github.com/tddworks)