convez.ai
PluginIntegração & APIsIntermediário
tddworks

OpenAI Kotlin Multiplatform

tddworks/openai-kotlin

Cliente IA unificado multiplataforma para Kotlin com suporte a múltiplos provedores

Ver no GitHub
BomPluginScore · de 0 a 100

Biblioteca Kotlin multiplataforma que oferece acesso unificado a múltiplos provedores de IA (OpenAI, Anthropic Claude, Google Gemini, Ollama). Suporta JVM, Android, iOS e plataformas nativas com streaming em tempo real e interface type-safe.

Instalação

$npx convez-ai tddworks/openai-kotlin

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
58
Forks
2
Acompanhando
2
Saúde
50%
Último commit
há 11 meses
Versão
0.2.3
Issues abertas
0
Contribuidores
2

Casos de uso

  • Integrar múltiplos provedores de LLM em aplicações Kotlin
  • Implementar chat completions com streaming em aplicações mobile e backend
  • Trocar dinamicamente entre provedores de IA sem alterar código cliente

Veredito

SDK robusto e bem-estruturado para quem trabalha com Kotlin multiplataforma e precisa de suporte a múltiplos provedores de IA. Boa cobertura de testes e design modular, mas requer familiaridade com Kotlin/Native.

README

A tradução para o português deste README ainda está na fila.

OpenAI Kotlin

CI codecov Maven Central Kotlin KMP Ktor License GitHub Release Issues Stars

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 CIO✅File System
AndroidKtor CIO✅File System
iOSNSURLSession✅UserDefaults
macOSNSURLSession✅UserDefaults

🔧 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

Ver o original no GitHub

Bom para

Relacionados