claudeers.

🔓 unclaimed — this page was auto-generated from GitHub. Are you the creator?

Claim this page →
// Frameworks & SDKs

openai-kotlin

OpenAI clients for kotlin multiplatform SDK, supports OpenAI, Anthropic, Azure, Gemini, Ollama with TDD

Dormant
46/100
last commit 7 months ago
last release 7 months ago
releases 4
open issues 0
// install
git clone https://github.com/tddworks/openai-kotlin

OpenAI Kotlin

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:

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
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:

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("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:

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

FrameworkDescription
OpenAIClientOpenAI API client
AnthropicClientAnthropic Claude API client
GeminiClientGoogle Gemini API client
OllamaClientOllama local LLM client
OpenAIGatewayMulti-provider unified gateway

Swift Usage Examples

OpenAI

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

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

import GeminiClient

let client = GeminiCompanion.shared.create(apiKey: "your-api-key")

Ollama (Local)

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

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

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 {
    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")
}

Maven

<dependency>
    <groupId>com.tddworks</groupId>
    <artifactId>openai-client-jvm</artifactId>
    <version>0.2.3</version>
</dependency>

Available Modules

ModuleDescriptionPlatforms
openai-client-*OpenAI API client (chat, images, completions)JVM, iOS, macOS
anthropic-client-*Anthropic Claude API clientJVM, iOS, macOS
ollama-client-*Ollama local LLM clientJVM, iOS, macOS
gemini-client-*Google Gemini API clientJVM, iOS, macOS
openai-gateway-*Multi-provider gatewayJVM, iOS, macOS
commonShared networking utilitiesAll platforms

💡 Usage Examples

Image Generation

val images = openAI.images(
    ImageCreate(
        prompt = "A beautiful sunset over mountains",
        size = Size.SIZE_1024x1024,
        quality = Quality.HD,
        n = 1
    )
)

Vision (Image Analysis)

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

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

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

PlatformHTTP ClientStreamingLocal Storage
JVMKtor CIOFile System
AndroidKtor CIOFile System
iOSNSURLSessionUserDefaults
macOSNSURLSessionUserDefaults

🔧 Configuration

Environment Variables

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

Configuration Examples

OpenAI with Custom Base URL

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

val anthropic = Anthropic.create(
    apiKey = System.getenv("ANTHROPIC_API_KEY"),
    baseUrl = "https://api.anthropic.com",
    anthropicVersion = "2023-06-01"
)

🧪 Testing

Unit Tests

./gradlew test

Integration Tests

./gradlew integrationTest

Code Coverage

./gradlew koverHtmlReport
open build/reports/kover/html/index.html

🤝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

  1. Clone the repository:

    git clone https://github.com/tddworks/openai-kotlin.git
    cd openai-kotlin
    
  2. Build the project:

    ./gradlew build
    
  3. Run tests:

    ./gradlew allTests
    
  4. Format code:

    ./gradlew spotlessApply
    

Code Style

This project uses 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

🌟 Acknowledgments


Made with ❤️ by TDD Works

// compatibility

Platformsapi, mobile
Operating systems
AI compatibilityclaude
LicenseApache-2.0
Pricingopen-source
LanguageKotlin

// faq

What is openai-kotlin?

OpenAI clients for kotlin multiplatform SDK, supports OpenAI, Anthropic, Azure, Gemini, Ollama with TDD. It is open-source on GitHub.

Is openai-kotlin free to use?

openai-kotlin is open-source under the Apache-2.0 license, so it is free to use.

What category does openai-kotlin belong to?

openai-kotlin is listed under other in the Claudeers registry of Claude-compatible tools.

0 views
53 stars
unclaimed
updated 15 days ago

// embed badge

openai-kotlin on Claudeers
[![Claudeers](https://claudeers.com/api/badge/openai-kotlin.svg)](https://claudeers.com/openai-kotlin)

// retro hit counter

openai-kotlin hit counter
[![Hits](https://claudeers.com/api/counter/openai-kotlin.svg)](https://claudeers.com/openai-kotlin)

// reviews

// guestbook

0/500

// related in Frameworks & SDKs

🔓

An open-source AI coding agent that lives in your terminal.

// frameworksQwenLM/TypeScript25,830Apache-2.0[ claude ]
🔓

Claude Code 泄露源码 - 本地可运行版本,新增跨平台桌面端软件补齐Computer Use(附带核心模块解析)

// frameworksNanmiCoder/TypeScript13,109NOASSERTION[ claude ]
🔓

LangGPT: Empowering everyone to become a prompt expert! 🚀 📌 结构化提示词(Structured Prompt)提出者 📌 元提示词(Meta-Prompt)发起者 📌 最流行的提示词落地范式 | Language of GPT The p…

// frameworkslanggptai/Jupyter Notebook12,304Apache-2.0[ claude ]
🔓

Multi-Agent Harness for Production AI

// frameworksaden-hive/Python10,632Apache-2.0[ claude ]
Ecosystem hubone of the most connected projects in the claude ecosystem · 24 connections
→ see how openai-kotlin connects across the ecosystem