OpenAIClient

class OpenAIClient(apiKey: ApiKey = ApiKey.fromEnv("OPENAI_API_KEY"), baseUrl: String = "https://api.openai.com/v1", httpClient: KoryHttpClient? = null) : ChatClient, ToolCapable, FilesAPISupport

OpenAI-compatible chat client implementing ChatClient and ToolCapable.

Supports chat completions, streaming, tool execution, and model listing. Works with any OpenAI-compatible API (OpenAI, Ollama, Groq, etc.).

Parameters

apiKey

The API key for authentication.

baseUrl

The base URL of the API (default: "https://api.openai.com/v1").

httpClient

The HTTP client to use. Defaults to a platform-appropriate client: on JVM, the available engine is loaded via ServiceLoader; on Native, the default system engine is used. Bearer authentication is automatically applied.

Samples

// Create OpenAI client.
val client = try {
    OpenAIClient(apiKey = ApiKey.fromEnv()) // Set AI_API_KEY in your environment.
} catch (kNfEx: KeyNotFoundException) {
    error("No api key provided.\nDetail message: ${kNfEx.message}")
} catch (e: Exception) {
    error("Error: ${e.message}")
}

// With custom base url.
val clientWithCustomUrl = try {
    OpenAIClient(apiKey = ApiKey.fromEnv())
} catch (e: Exception) {
    error("Error: ${e.message}")
}

val baseUrl = "https://openai/compatible.domain/v1"
val apiKey = ApiKey.fromEnv()

// And with kory http client.
val clientWithCustomHttpClient = OpenAIClient(
    apiKey = apiKey,
    baseUrl = baseUrl,
    httpClient = KoryHttpClient.create(
        KoryHttpClientConfig(
            baseUrl = baseUrl, // https://openai/compatible.domain/v1
            auth = KoryAuth.Bearer(apiKey.value) // Authentication
        )
    )
)
// Get OpenAI API Key from Env.
val openAIApiKey = ApiKey.fromEnv("OPEN_AI_API_KEY") { e ->
    error(e)
}

// Create OpenAI client.
val client = OpenAIClient(
    apiKey = openAIApiKey
)

runBlocking {
    val response =
        client.chat { // Call this function from coroutine or another suspend function(function automatic set Dispatchers.IO pool)
            chat(model = "gpt-5.6-sol") {
                user("Ping!")
            }
        }

    for (choice in response.choices) { // AI Responses can be [Choice(1, content), Choice(2, content)].
        for (content in choice.contents) { // Get all response contents from choices(Content.Text, Content.Reasoning...)
            when (content) {
                is Content.Parts -> println("Parts: $content")
                is Content.Reasoning -> println("Reasoning: $content.value")
                is Content.Text -> println("Output: $content.text")
                is Content.ToolCall -> println("Tool Call: ${content.name} on ${content.argumentsJson}")
            }
        }
    }
}

Constructors

Link copied to clipboard
constructor(apiKey: ApiKey = ApiKey.fromEnv("OPENAI_API_KEY"), baseUrl: String = "https://api.openai.com/v1", httpClient: KoryHttpClient? = null)

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard

Cancels an in-progress response from the OpenAI Responses API.

Link copied to clipboard
open suspend override fun chat(request: ChatRequest): ChatResponse

Sends a chat request to the OpenAI and returns a non-streaming response.

open suspend override fun chat(block: ChatRequestBuilder.() -> Unit): ChatResponse
open suspend override fun chat(model: String, blocks: ChatBuilder.() -> Unit): ChatResponse

Sends a chat request to the OpenAI API and returns a non-streaming response.

Link copied to clipboard

Sends a raw OpenAI chat completion request.

Sends a raw OpenAI chat completion request using the request DSL.

Link copied to clipboard

Streams raw OpenAI chat completion chunks.

Streams raw OpenAI chat completion chunks using the request DSL.

Link copied to clipboard
suspend fun chatResponses(request: OpenAIResponsesRequest, onCanceled: (cancelResult: OpenAIResponsesResponse?) -> Unit? = null): OpenAIResponsesResponse
suspend fun chatResponses(model: String, input: String): OpenAIResponsesResponse
Link copied to clipboard
open override fun chatStream(request: ChatRequest): Flow<ChatChunk>

Sends a chat request to the OpenAI API and returns a streaming response.

open override fun chatStream(block: ChatRequestBuilder.() -> Unit): Flow<ChatChunk>

Sends a chat request and returns a streaming response using full DSL configuration.

open override fun chatStream(model: String, blocks: ChatBuilder.() -> Unit): Flow<ChatChunk>

Sends a chat request and returns a streaming response using DSL message builder.

Link copied to clipboard
open override fun chatStreamWithTools(request: ChatRequest, autoExecute: Boolean, maxSteps: Int?, currentStep: Int, onFullToolCollected: ToolCapable.ToolCallCallback, onToolCall: ToolCapable.ToolCallCallback, onToolExecutionFailed: ToolCapable.ToolExecutionFailedCallback): Flow<ChatChunk>

Sends a chat request with tool support and returns a streaming response.

open override fun chatStreamWithTools(autoExecute: Boolean, maxSteps: Int?, currentStep: Int, onFullToolCollected: ToolCapable.ToolCallCallback, onToolCall: ToolCapable.ToolCallCallback, onToolExecutionFailed: ToolCapable.ToolExecutionFailedCallback, block: ChatRequestBuilder.() -> Unit): Flow<ChatChunk>

Sends a chat request with tool support and returns a streaming response using full DSL configuration.

Link copied to clipboard
open suspend override fun chatWithTools(request: ChatRequest, autoExecute: Boolean, maxSteps: Int?, currentStep: Int, onToolCall: ToolCapable.ToolCallCallback, onToolExecutionFailed: ToolCapable.ToolExecutionFailedCallback): ChatResponse

Sends a chat request with tool support and returns a non-streaming response.

open suspend override fun chatWithTools(autoExecute: Boolean, maxSteps: Int?, currentStep: Int, onToolCall: ToolCapable.ToolCallCallback, onToolExecutionFailed: ToolCapable.ToolExecutionFailedCallback, block: ChatRequestBuilder.() -> Unit): ChatResponse

Sends a chat request with tool support using full DSL configuration.

Link copied to clipboard
open suspend override fun deleteFile(fileId: String): DeleteApiFileResult

Deletes a single file by its ID.

Link copied to clipboard
open suspend override fun deleteFiles(filesIds: List<String>, maxConcurrency: Int): List<DeleteFileResult>

Deletes multiple files with controlled concurrency.

Link copied to clipboard

Deletes a file from the OpenAI Files API.

Link copied to clipboard
suspend fun deleteOpenAIFiles(filesIds: List<String>, maxConcurrency: Int = 5): List<DeleteFileResult>
Link copied to clipboard
Link copied to clipboard
open suspend override fun downloadFileContentTo(fileId: String, file: KoryFile, onProgress: UploadFileProgressListener<SingleFileProgress>?): Long

Downloads a file's content and writes it to a KoryFile.

Link copied to clipboard

Downloads a file from the OpenAI Files API and writes its content to a KoryFile.

Link copied to clipboard
open suspend override fun executeTool(toolCall: Content.ToolCall, toolMap: Map<String, KoryTool<*, *>>): String
Link copied to clipboard
open suspend override fun getFileContent(fileId: String): ByteArray

Retrieves the raw content of a file as a byte array.

Link copied to clipboard
open suspend override fun getFiles(ids: List<String>, pageToken: String?, concurrency: Int): ApiFilesList

Retrieves file objects by their IDs with controlled concurrency.

Link copied to clipboard
open suspend override fun listModels(): List<Model>

Retrieves the list of available models from the OpenAI API.

Link copied to clipboard
suspend fun listOpenAIFiles(after: String? = null, limit: Int? = null, order: OpenAIOrder? = null, purpose: OpenAIPurpose? = null): OpenAIFileListResponse

Retrieves a paginated list of files uploaded to the OpenAI Files API.

Link copied to clipboard

Lists all available OpenAI models.

Link copied to clipboard
Link copied to clipboard

Retrieves the raw content of a file from the OpenAI Files API.

Link copied to clipboard
suspend fun retrieveResponse(responseId: String, stream: Boolean = false): OpenAIResponsesResponse
Link copied to clipboard
open override fun streamFileContent(fileId: String): Flow<ByteArray>

Streams a file's content as a Flow of byte arrays.

Link copied to clipboard

Streams the content of a file from the OpenAI Files API as a Flow of byte arrays.

Link copied to clipboard
open suspend override fun uploadFile(request: UploadFileRequest, onProgress: UploadFileProgressListener<SingleFileProgress>?): ApiFile

Uploads a single file to the OpenAI Files API.

open suspend override fun uploadFile(onProgress: UploadFileProgressListener<SingleFileProgress>?, block: UploadFileRequestBuilder.() -> Unit): ApiFile

Uploads a single file to the OpenAI Files API using the request DSL.

Link copied to clipboard
open suspend override fun uploadFiles(maxConcurrency: Int, onProgress: UploadFileProgressListener<MultiFileProgress>?, block: UploadFilesRequestBuilder.() -> Unit): List<UploadFileResult>

Uploads multiple files using the request DSL.

open suspend override fun uploadFiles(requests: List<UploadFileRequest>, maxConcurrency: Int, onProgress: UploadFileProgressListener<MultiFileProgress>?): List<UploadFileResult>

Uploads multiple files with controlled concurrency.

Link copied to clipboard

Uploads a single file to the OpenAI Files API.

suspend fun uploadOpenAIFile(onProgress: UploadFileProgressListener<SingleFileProgress>? = null, purpose: OpenAIFilePurpose = OpenAIFilePurpose.FINE_TUNE, block: OpenAIUploadFileRequestBuilder.() -> Unit): OpenAIFileObject

Uploads a single file to the OpenAI Files API using the request DSL.

Link copied to clipboard
suspend fun uploadOpenAIFiles(maxConcurrency: Int = 5, onProgress: UploadFileProgressListener<MultiFileProgress>? = null, requests: OpenAIUploadFilesBuilder.() -> Unit): List<UploadFileResult>

Uploads multiple files to the OpenAI Files API using the DSL.

suspend fun uploadOpenAIFiles(requests: List<OpenAIUploadFileRequest>, maxConcurrency: Int = 5, onProgress: UploadFileProgressListener<MultiFileProgress>? = null): List<UploadFileResult>

Uploads multiple files to the OpenAI Files API with controlled concurrency.

Link copied to clipboard
fun uploadOpenAIFilesAsFlow(maxConcurrency: Int = 5, requests: OpenAIUploadFilesBuilder.() -> Unit): Flow<UploadFileState>

Uploads multiple files and emits progress/completion events as a Flow using the DSL.

fun uploadOpenAIFilesAsFlow(requests: List<OpenAIUploadFileRequest>, maxConcurrency: Int = 5): Flow<UploadFileState>

Uploads multiple files and emits progress/completion events as a Flow.