Skip to content
Projetos

cequence-io/openai-scala-client

Ver no GitHub

Sobre

Scala client for OpenAI API and other major LLM providers

IA e aprendizado de máquina

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

OpenAI Scala Client 🤖

version License GitHub Stars Follow on X GitHub CI

This is a no-nonsense async Scala client for OpenAI API and multiple LLM providers supporting all the available endpoints and params including streaming (with a provider-neutral typed stream of text / thinking / tool-call / tool-result chunks), chat completion, responses API, agents API, tools (including MCP), graders, vision (with provider-uniform file/image attachments), batch processing, and voice routines (as defined here), provided in a single, convenient service called OpenAIService with adapters for Anthropic (incl. Bedrock and Managed Agents), Google Gemini/Vertex AI, Groq, Perplexity (incl. its decision model), TypeSafe AI (Jev), Liquid AI (d1), Microsoft Foundry (Microsoft-Decision-1), SubQ (SubQ Snap), ScaleDown (Classify), the decision models on OpenRouter and Vercel AI Gateway, and others. The supported calls are:

🔥 New in 2.0: the client is decoupled from its HTTP engine - it runs on any of ws-client's six engines: the JDK's java.net.http (the default, no Akka), Play WS on Akka or Pekko, Pekko HTTP, zio-http and sttp - and its streams run on plain Futures or natively in Akka, Pekko, fs2 or ZIO (see HTTP engines).

The Anthropic client additionally covers the native Messages (incl. typed stream events), Message Batches, Files, Skills, and the whole Managed Agents API surface (agents, environments and their work queue, sessions, deployments, vaults and credentials, memory stores) - see the Anthropic Managed Agents page.

Note that in order to be consistent with the OpenAI API naming, the service function names match exactly the API endpoint titles/descriptions in camelCase. Also, we aimed for the library to be self-contained with the fewest dependencies possible. Therefore, we implemented our own generic WS client, ws-client, with pluggable HTTP engines, JDK by default: out of the box the library runs on java.net.http - no Akka, no actor system - and an Akka, Pekko, ZIO or sttp engine is one dependency away (see HTTP engines). Every stream is a backend-neutral AsyncStream, run on plain Futures or handed to Akka, Pekko, fs2 or ZIO. Additionally, if dependency injection is required, we use the scala-guice library.


👉 No time to read a lengthy tutorial? Sure, we hear you! Check out the examples to see how to use the lib in practice.

👉 Follow @0xbnd on X for release announcements and LLM provider news.


In addition to OpenAI, this library supports many other LLM providers. For providers that aren't natively compatible with the chat completion API, we've implemented adapters to streamline integration (see examples).

Provider Structured output Tools Batch Notes
OpenAI Full Yes, Responses API too Yes Full API support; GPT-6.2 Sol / Astra 🔥
Azure OpenAI Full Yes, Responses API too Yes OpenAI on Azure
Anthropic Full Yes, MCP and Skills too Yes Claude models; Fable 5.2 and Mythos 5.2
Anthropic Bedrock Full Yes, MCP too Yes ¹ Claude on AWS
OpenAI Bedrock Full Yes, Responses API too – GPT-5.x, gpt-oss, Grok and more on AWS ²
Azure AI Varies – – Open-source models
Cerebras Full ³ Yes – Fast inference
Deepseek JSON object mode only – – Chinese provider; deepseek-flash is V4.1 Flash 1017
FastChat Varies – – Local LLMs
Fireworks AI Full – – Cloud provider
Google Gemini Full Yes Yes Google's models; Gemini 4 Carbon and Hydrogen
Google Vertex AI Full Yes Yes Gemini models; the global, EU and US endpoints
Grok Full Yes – x.AI models
Groq Full ³ Yes, MCP and server-side tools too Yes Fast inference
Meta Model API Full ⁶ Yes – Muse Wonder, Muse Ember, Muse Spark (open weights: Muse Spark Open on Together, Fireworks, OpenRouter, Vercel) ⁶
MiniMax Varies ⁴ – – Chinese provider (global and China); MiniMax-M3.1-Flash
Mistral Full – – Open-source leader
Novita Model-dependent – – Cloud provider
Octo AI JSON object mode only – – Cloud provider (obsolete)
Ollama Varies – – Local LLMs
OpenRouter Model-dependent Model-dependent – provider/model ids, e.g. meta/muse-wonder
Perplexity Implied only – – Agent API ⁵
TogetherAI Model-dependent – – Cloud provider
Vercel AI Gateway Model-dependent Model-dependent – provider/model ids, e.g. meta/muse-spark-open

¹ No prompt caching in batches.
² Through bedrock-mantle or bedrock-runtime.
³ Cerebras: gpt-oss-120b, qwen-3.8-27b; Groq: openai/gpt-oss-*, qwen/qwen3.x-27b.
⁴ JSON-object mode: M3 / M3.1-Flash accept strict json_schema but do not enforce it (live 2026-11-02).
⁵ Perplexity's Sonar chat completions retired on 2026-09-27 (see Services and providers).
⁶ ChatProviderSettings.meta (MODEL_API_KEY); Muse Wonder (2026-10-12) and Muse Spark live-verified with strict json_schema, tools and streams (see Services and providers).
🔥 New in 2.0.1.

Decision models give typed answers with calibrated probabilities. Two APIs serve them - TypeSafe AI's System One (TypeSafeService.systemOne: Jev, Liquid's d1, Perplexity's decider, Google's Gemini Decision 1, Microsoft-Decision-1, SubQ Snap, ScaleDown's Classify, Sarvam Prism, Bespoke's Nimble, OpenRouter, Vercel AI Gateway, llama.cpp) and OpenAI's Decisions API (OpenAIService.createDecision: gpt-6-luna) - and the client speaks either interface to either host: asOpenAIDecisions puts OpenAI's interface on a System One host, DecisionProviderSettings.openAI runs the System One routines (typed decisions, re-ranking, the json_schema-only chat adapter) on OpenAI's. No tools or batch. See Decision models.

Provider Models Factory method
TypeSafe AI Jev; images, bounding boxes (Jev 1.14) and long context (the factory's default) - experimental asOpenAI()
Liquid AI d1.1 (the default), d1, images too; d1-ultra liquidAsOpenAI()
llama.cpp (local) Liquid's Open d1 (d1-3B, d1-omni-600M) once llama.cpp loads them; Julia-1, Laya, Lev, Kev, OpenJev, Nimble, Clef asOpenAI(DecisionProviderSettings.llamaCpp)
Perplexity Decisions pplx-decider-v1.3 and the 4B pplx-decider-flash-v1.3, v1.2 (+ Flash), v1.1-27b / v1-27b; images too perplexityAsOpenAI()
Gemini Decisions Gemini Decision 1 (up to 1,000 questions, 262k tokens); images too asOpenAI(DecisionProviderSettings.gemini)
OpenRouter Jev, d1, Perplexity's deciders, OpenAI's Luna, Microsoft-Decision-1, Cloudflare's Clef (+ Flash, Omni), Solar Decide, Mercury Decide, Tev1, Kev 4B, NACE's Drex, Span-01, ScaleDown's Classify-1, Jev 1.14, d1-ultra, Span-02; d1.1, Baseten's Elephant-1 / Mammoth-1, NACE's Drex Max; Baseten's Joey-1, Morph's Reflex, NACE's Drex Max Finance and Parallel's Decisions Fast; Google's Gemini Decision 1, HeyGen's Decision 1 (+ Turbo) and Perplexity's v1.3 deciders; images too asOpenAI(DecisionProviderSettings.openRouter)
OpenAI Decisions gpt-6-luna, images too asOpenAI(DecisionProviderSettings.openAI)
Vercel AI Gateway Jev, d1 (images too), Microsoft-Decision-1, OpenAI's Luna; on the free tier Convai's Laya and ScaleDown's Classify-1, also Baseten's Elephant-1 / Mammoth-1, d1-ultra, Perplexity's v1.2 and v1.3 deciders and NACE's Drex Max v1.1; Gemini Decision 1 asOpenAI(DecisionProviderSettings.vercel)
SubQ SubQ Snap 1.2 (the default), 1.1 and Snap Preview (public preview; long context - 295,957 input tokens, up to 4 images) asOpenAI(DecisionProviderSettings.subq)
Sarvam Sarvam Prism (English, ten Indian languages and Hinglish) asOpenAI(DecisionProviderSettings.sarvam)
Bespoke Labs Nimble (nimble-latest = Nimble v4 Max, 27B; text only, at most 64 questions) asOpenAI(DecisionProviderSettings.bespoke)
ScaleDown Classify (a constrained decoding model; text plus one document, 1M context) asOpenAI(DecisionProviderSettings.scaleDown)
Microsoft Foundry Microsoft-Decision-1 (public preview; your own deployment in a Foundry resource) microsoftFoundryAsOpenAI()

👉 For background information how the project started read an article about the lib/client on Medium.

✔️ Important: this is a "community-maintained" library and, as such, has no relation to OpenAI company.

Installation 🚀

The currently supported Scala versions are 2.12, 2.13, and 3 (built with 2.12.18, 2.13.18 and 3.2.2 - on 2.13, sbt 1.10+ asks for a scalaVersion of at least 2.13.18), on Java 11+.

👉 Coming from 1.x? The 1.x line - 1.7.x, on the 1.7.x branch - runs on Akka (Play WS, Akka Source streams); 2.0.0 needs neither. 1.7.2 is the last 1.x release, so please upgrade: see Migrating to 2.0.

To install the library, add the following dependency to your build.sbt

"io.cequence" %% "openai-scala-client" % "2.0.1"

or to pom.xml (if you use maven)

<dependency>
    <groupId>io.cequence</groupId>
    <artifactId>openai-scala-client_2.12</artifactId>
    <version>2.0.1</version>
</dependency>

If you want streaming support, use "io.cequence" %% "openai-scala-client-stream" % "2.0.1" instead.

For a single dependency that includes all provider clients (Anthropic, Gemini, Vertex AI, Perplexity, TypeSafe AI, token counting):

"io.cequence" %% "openai-scala-all" % "2.0.1"

For ZIO, "io.cequence" %% "openai-scala-zio" % "2.0.1" (Scala 2.12, 2.13 and 3.3+) gives every service as ZIO Tasks and ZStreams, with ZLayers. It brings the OpenAI client and its streaming module; add the provider modules you use (Anthropic, Gemini, ...) yourself. See ZIO services.

Logging: the library logs through SLF4J and, since 2.0.0, brings no logging backend (1.x brought logback-classic) - add the binding of your choice, e.g. logback-classic; without one, nothing is logged.

HTTP engines: calls go through an engine of ws-client 1.2.2. The default, jdk (java.net.http), comes with the library: no Akka, no actor system, streaming included. For another engine add its artifact - "io.cequence" %% "<artifact>" % "1.2.2", one version for every ws-client artifact - and the engine with the highest priority on the classpath is used; -Dws-client.engine=<id> names one instead. See Choosing an engine.

Engine id Artifact Priority Streams Scala
play-pekko-stream ws-client-play-pekko-stream 21 Yes 2.13, 3.3+
play-pekko ws-client-play-pekko 20 – 2.13, 3.3+
pekko-http ws-client-pekko-http 15 Yes 2.13, 3.3+
play-akka-stream ws-client-play-akka-stream 11 Yes 2.12, 2.13, 3
play-akka ws-client-play-akka 10 – 2.12, 2.13, 3
zio-http ws-client-zio-http 7 Yes 2.12, 2.13
sttp ws-client-sttp 5 – 2.12, 2.13
jdk (the default) ws-client-jdk (included) 0 Yes 2.12, 2.13, 3

Streamed services pick the highest-priority engine that streams (jdk at least). Akka and Pekko artifacts must not share a classpath. Each engine with what the factories pick and a runnable example: Engine by engine.

Config ⚙️

  • Env. variables: OPENAI_SCALA_CLIENT_API_KEY and optionally also OPENAI_SCALA_CLIENT_ORG_ID (if you have one)
  • File config (default): openai-scala-client.conf
  • Streams: one frame (a server-sent event or JSON line) may take up to 32 MiB - a generated image in base64 arrives in one event. Change the cap with openai-scala-client.streaming.maxFrameLength (e.g. 128 MiB) or the env. variable OPENAI_SCALA_CLIENT_STREAM_MAX_FRAME_LENGTH; a larger frame fails the stream with an exception naming both the setting and the variable (see the FAQ).

Quick start 🏁

import io.cequence.openaiscala.domain._
import io.cequence.openaiscala.domain.settings.CreateChatCompletionSettings
import io.cequence.openaiscala.service.OpenAIServiceFactory

import scala.concurrent.ExecutionContext.Implicits.global

val service = OpenAIServiceFactory() // the key from OPENAI_SCALA_CLIENT_API_KEY

service
  .createChatCompletion(
    Seq(UserMessage("What is the capital of Norway? One word.")),
    CreateChatCompletionSettings(model = ModelId.gpt_5_4_mini)
  )
  .map(response => println(response.contentHead))
  .andThen { case _ => service.close() } // close a service when done with it - it owns its HTTP client

Every provider in the tables above is reached the same way - through its factory's asOpenAI() (or OpenAIChatCompletionServiceFactory(ChatProviderSettings.<provider>)), after which the calls, adapters and streams are the same. See Services and providers.

Streaming (with openai-scala-client-stream):

import io.cequence.openaiscala.domain._
import io.cequence.openaiscala.domain.settings.CreateChatCompletionSettings
import io.cequence.openaiscala.service.OpenAIServiceFactory
import io.cequence.openaiscala.service.OpenAIStreamedServiceImplicits._

import scala.concurrent.ExecutionContext.Implicits.global

val streamedService = OpenAIServiceFactory.withStreaming()

streamedService
  .createChatCompletionStreamedTyped(
    Seq(UserMessage("Name three Norwegian fjords.")),
    CreateChatCompletionSettings(model = ModelId.gpt_5_4_mini)
  )
  .texts // the answer's text; the typed chunks also carry thinking, tool calls and usage
  .runForeach(text => print(text)) // nothing is sent until the stream runs - each run is a new request
  .andThen { case _ => streamedService.close() }

Consuming a stream: every stream is a back-pressured, cold AsyncStream (ws-client) - nothing is sent until it runs, and each run is a new request. Run it on plain Futures (runForeach, runFold, runToSeq, ...) or hand it to your streaming library with one import (each module is ws-client's, version 1.2.2):

  • Akka (ws-client-core-akka): import io.cequence.wsclient.stream.SourceInterop._, then stream.toSource - on the play-akka-stream engine it compiles to that engine's own Source, with no bridge
  • Pekko (ws-client-core-pekko): the same import, then stream.toSource - native on play-pekko-stream and pekko-http
  • fs2 (ws-client-fs2): import io.cequence.wsclient.stream.Fs2Interop._, then stream.toFs2[IO]
  • ZIO (ws-client-zio): import io.cequence.wsclient.stream.ZioInterop._, then stream.toZStream - native on zio-http; or the ZIO services, which return ZStreams
  • Reactive Streams: stream.toPublisher (a java.util.concurrent.Flow.Publisher)

See Consuming a stream.

Documentation 📚

Page What it covers
Services and providers Factories, config and keys; every provider's adapter - Azure, Anthropic and Bedrock, Gemini and Vertex AI, Mistral, Groq, Grok, Cerebras, DeepSeek, Perplexity, Liquid AI, any OpenAI-compatible endpoint
Chat completions Calls, JSON / structured output (schemas from case classes), failover, tools, reasoning effort, files and images
Responses API Inputs and images, file / web search, function calls, MCP, multi-agent execution
Agents API Durable cloud agents (beta): sessions, events, the chat adapter
Streaming AsyncStream and consuming it from Akka, Pekko, fs2 or ZIO; OpenAI-shaped and typed streams (ChatChunk), the frame cap, human approval mid-stream
Decision models OpenAI's Decisions API, TypeSafe (Jev), Liquid (d1), Perplexity's decider, Google's Gemini Decision 1, Microsoft-Decision-1, SubQ Snap, ScaleDown's Classify, Sarvam Prism, Bespoke's Nimble, OpenRouter, Vercel AI Gateway, llama.cpp; either API on either host, typed decisions, re-ranking, the models' execution time side by side
Adapters Round robin, retry, logging, routing, batch processing, interception, guardrails
HTTP engines Choosing an engine - JDK by default; Akka, Pekko, ZIO, sttp; one engine for many services and providers; timeouts, proxy and HTTP version; embedding in an Akka, Pekko or ZIO application
ZIO services openai-scala-zio: every service with ZIO Tasks and ZStreams, and ZLayers
Graders API Evaluating model outputs
Anthropic Managed Agents Server-hosted agents with tool-permission pauses
Claude Agent Client The claude CLI as a subprocess transport
FAQ Timeouts, errors, the stream frame cap, ...
Migrating to 2.0 From 1.x: Futures-only, Akka, Pekko, fs2 and ZIO code; cold streams; logging; Materializer and Scheduler arguments; implementing the service traits; the guice module

Ready-to-run examples (on plain Futures and AsyncStreams) are in openai-examples; the release notes are in CHANGELOG.md. Run one with the provider's key set, in a forked JVM on the default jdk engine: sbt "examples/runMain io.cequence.openaiscala.examples.CreateChatCompletion"; the same on another engine and stream library: examples_akka, examples_pekko, examples_fs2, examples_zio, examples_sttp (Engine by engine). In a program of your own, wait for a call's Future before main returns (Await.result, or your effect system's runner): the jdk engine's threads are daemons, so a main that returns first ends the JVM at once - exit code 0, nothing printed. Wait in a plain def main: a Scala 3 App body runs in its object's initializer, where blocking hangs as soon as a callback touches the object.

License ⚖️

This library is available and published as open source under the terms of the MIT License.

Contributors 🙏

This project is open-source and welcomes any contribution or feedback (here).

Development of this library has been supported by - Cequence.io - The future of contracting

Created and maintained by Peter Banda (on X here).

Explore projetos relacionados

Carregando…