openai-kotlin
0.2.3indexedOffers streamlined integration with OpenAI API for chat and completion tasks, supporting multiple service providers and customizable configurations for API keys and base URLs.
Offers streamlined integration with OpenAI API for chat and completion tasks, supporting multiple service providers and customizable configurations for API keys and base URLs.
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.
Add the dependency:
implementation("com.tddworks:openai-client-jvm:0.2.3")
import com.tddworks.openai.api.OpenAI
import com.tddworks.openai.api.chat.api.*
// Simple - just provide your API key
openAI = OpenAI.create(apiKey = )
openAI = OpenAI.create(apiKey = , baseUrl = )
openAI = OpenAI.create(
apiKey = { settings.apiKey },
baseUrl = { settings.baseUrl }
)
response = openAI.chatCompletions(
ChatCompletionRequest(
messages = listOf(ChatMessage.UserMessage()),
model = Model.GPT_4O,
maxTokens =
)
)
openAI.streamChatCompletions(
ChatCompletionRequest(
messages = listOf(ChatMessage.UserMessage()),
model = Model.GPT_4O
)
).collect { chunk ->
print(chunk.choices?.firstOrNull()?.delta?.content ?: )
}
For applications requiring multiple AI providers:
implementation("com.tddworks:openai-gateway-jvm:0.2.3")
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()),
model = Model()
)
)
Add the package to your Package.swift or via Xcode:
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.
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: )
client .shared.create(
apiKey: { .shared.apiKey },
baseUrl: { .shared.baseUrl }
)
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"
)
import GeminiClient
let client = GeminiCompanion.shared.create(apiKey: "your-api-key")
import OllamaClient
// Default localhost:11434
let client = OllamaCompanion.shared.create()
// Custom host
let client = OllamaCompanion.shared.create(baseUrl: "192.168.1.100", port: 11434)
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 }
)
For multiplatform projects:
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:
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")
}
<dependency>
<groupId>com.tddworks</groupId>
<artifactId>openai-client-jvm</artifactId>
<version>0.2.3</version>
</dependency>
val images = openAI.images(
ImageCreate(
prompt = "A beautiful sunset over mountains",
size = Size.SIZE_1024x1024,
quality = Quality.HD,
n = 1
)
)
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
)
)
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
)
)
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?"
)
)
)
)
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)
└─────────────────────┘
Set these environment variables or provide them programmatically:
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
GEMINI_API_KEY=your-gemini-key
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 }
)
val anthropic = Anthropic.create(
apiKey = System.getenv("ANTHROPIC_API_KEY"),
baseUrl = "https://api.anthropic.com",
anthropicVersion = "2023-06-01"
)
./gradlew test
./gradlew integrationTest
./gradlew koverHtmlReport
open build/reports/kover/html/index.html
We welcome contributions! Please see our Contributing Guidelines for details.
This project uses Spotless for code formatting. Please run ./gradlew spotlessApply before submitting PRs.
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:
Unless applicable law agreed to writing, software
distributed under the License distributed an BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
See the License the specific language governing permissions
limitations under the License.
Made with ❤️ by TDD Works
| 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 |
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: "")
}
| 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 |
| Platform | HTTP Client | Streaming | Local Storage |
|---|
| JVM | Ktor CIO | ✅ | File System |
| Android | Ktor CIO | ✅ | File System |
| iOS | NSURLSession | ✅ | UserDefaults |
| macOS | NSURLSession | ✅ | UserDefaults |
Clone the repository:
git clone https://github.com/tddworks/openai-kotlin.git
cd openai-kotlin
Build the project:
./gradlew build
Run tests:
./gradlew allTests
Format code:
./gradlew spotlessApply
Surfaced from shared tags and platforms — no rankings paid for.