# LLM4S > LLM4S (Large Language Models for Scala) is a type-safe Scala 3 framework for LLM-powered applications: multi-provider chat and embeddings, tools, agents, RAG and observability, with Java and Kotlin APIs. Version: 0.5.1 Full text of every page below: https://llm4s.org/llms-full.txt. Rules for code written with a coding assistant: https://llm4s.org/llm4s-rules.md (https://llm4s.org/ai-assistants). ## Getting started - [Getting Started](https://llm4s.org/getting-started/): Get started with LLM4S: install it, run a first program, configure a provider, and pick a quick start for sbt, Scala CLI, Maven, Gradle, Mill or JBang. - [Installation](https://llm4s.org/getting-started/installation): Add LLM4S to an sbt build: JDK 21 and Scala 3.7 requirements, the llm4s-core artifact, and which provider module to depend on. - [First Example](https://llm4s.org/getting-started/first-example): Write your first LLM4S program in Scala: build a client from configuration, send one prompt, and read the Result of the call. - [Configuration](https://llm4s.org/getting-started/configuration): Configure LLM4S providers in application.conf: named provider sections, API keys from the environment, precedence and per-section validation. - [Next Steps](https://llm4s.org/getting-started/next-steps): Where to go after your first LLM4S program: learning paths for agents, tool integration, conversational AI, RAG and production systems. - [Ollama Quick Start](https://llm4s.org/getting-started/ollama-quickstart): Run LLM4S against Ollama for free local inference in Scala: install Ollama, pull a model, configure the provider and make your first call. - [Gradle Integration](https://llm4s.org/getting-started/gradle): Use LLM4S from a Gradle build in Java, Kotlin or Kotlin/Ktor: the _3 artifact names, dependency declarations and a first call. - [Testing Guide](https://llm4s.org/getting-started/testing-guide): Test LLM-powered Scala code without paying for API calls: fast, deterministic tests with mock clients, plus when to run a live model. - [Scala CLI Quick Start](https://llm4s.org/getting-started/scala-cli): Call an LLM from a single Scala CLI file with LLM4S: dependencies declared in the file, no sbt project, and a first answer in minutes. - [Maven Quick Start](https://llm4s.org/getting-started/maven): A complete Maven pom.xml that compiles and runs a first LLM call from Java with llm4s-java-api, built against the library in CI. - [JBang Quick Start](https://llm4s.org/getting-started/jbang): Run a first LLM call from one Java file with JBang and llm4s-java-api: dependencies declared in the file, no build tool, no project. - [First-Run Troubleshooting](https://llm4s.org/getting-started/troubleshooting): Fix the problems met when an LLM4S program fails on its first run: each error message with its cause and fix, such as a missing API key. - [Using LLM4S from Scala 2.13](https://llm4s.org/getting-started/scala-2-13): Call LLM4S from Scala 2.13 projects such as Spark, Play or Pekko services through the TASTy reader, with the compiler settings it needs. - [Mill Quick Start](https://llm4s.org/getting-started/mill): Use LLM4S in a Mill 1.x project: a complete build.mill, a program that asks a model one question, its configuration and a unit test without an API key. - [Playground (Codespaces)](https://llm4s.org/getting-started/playground): Try LLM4S in the browser with no install and no API key: a GitHub Codespace with JDK 21, sbt, Scala CLI, Metals and a small local Ollama model. - [Try llm4s in the REPL](https://llm4s.org/getting-started/repl): One import for the Scala CLI REPL, Metals worksheets and scripts: ask, extract, chat, history and lastUsage, with an offline session that needs no API key. - [First Answer, No Key, No Server](https://llm4s.org/getting-started/local-jlama): A first LLM answer from Scala in five minutes with no API key and no model server: llm4s-jlama runs a small open model inside your JVM. - [AI Coding Assistants](https://llm4s.org/ai-assistants): Point Copilot, Claude Code, Cursor and Codex at llm4s: llms.txt, llms-full.txt and a rules file that keeps generated code compiling. ## User guide (including Java and Kotlin) - [User Guide](https://llm4s.org/guide/): The LLM4S user guide: providers, agents, tools, structured output, RAG, vector stores, Java, effect systems and observability for the Scala JVM. - [Basic Usage](https://llm4s.org/guide/basic-usage): Create an LLM4S client, send a conversation, choose a model and handle the Result and LLMError values that every call returns in Scala. - [Providers](https://llm4s.org/guide/providers): Which LLM providers LLM4S supports, including OpenAI, Anthropic, Azure, Gemini and Ollama, how to select one and configure its API key and models. - [Vector Store](https://llm4s.org/guide/vector-store): The VectorStore API for RAG and semantic search in Scala: in-memory, file, PostgreSQL with pgvector, Qdrant, Elasticsearch and OpenSearch stores. - [Permission-Based RAG](https://llm4s.org/guide/permission-based-rag): Add access control to RAG in LLM4S: organise documents in collections, grant principals access, and retrieve only what a user may read. - [Error Handling](https://llm4s.org/guide/error-handling): Handle failures in LLM4S with Result[A] and LLMError: the basic pattern, for-comprehensions, error types, converting to exceptions and combining results. - [Structured Output](https://llm4s.org/guide/structured-output): Get a typed value instead of free text with completeStructured: describe the type, set options and handle replies that do not comply. - [Spring Boot](https://llm4s.org/guide/spring-boot): Use LLM4S with Spring Boot: add llm4s-spring-boot-starter, configure it in application.properties and inject an LLM4STemplate with a health indicator. - [Image Generation](https://llm4s.org/guide/image-generation): Generate images from Scala with LLM4S using Stable Diffusion through a local WebUI or the Hugging Face Inference API, with setup and options. - [Speech (STT/TTS)](https://llm4s.org/guide/speech): Speech-to-text and text-to-speech in Scala with the LLM4S speech module: Vosk, Whisper, OpenAI, Azure and ElevenLabs, with configuration. - [Built-in Tools](https://llm4s.org/guide/builtin-tools): Ready-made agent tools in LLM4S: calculator, date and time, UUID, JSON, files, HTTP, shell and web search, with the bundles and their configuration. - [Context Window Pruning](https://llm4s.org/guide/context-window-pruning): Keep a long conversation inside the model's context window with LLM4S pruning strategies: oldest first, middle out, recent turns and adaptive. - [Agents](https://llm4s.org/guide/agents/): Build AI agents in Scala with LLM4S: tools, multi-turn conversations, guardrails, handoffs, memory, streaming and multi-agent coordination. - [Guardrails](https://llm4s.org/guide/agents/guardrails): Validate an agent's inputs and outputs with LLM4S guardrails: length, profanity, JSON and regex checks, LLM-as-judge and RAG guardrails. - [Memory System](https://llm4s.org/guide/agents/memory): Give LLM4S agents short-term and long-term memory: user facts, entity knowledge, memory managers and stores that persist across conversations. - [Handoffs](https://llm4s.org/guide/agents/handoffs): Hand a query from one LLM4S agent to a specialist agent: handoff configuration, handing back, handoff options and how handoffs work. - [Streaming Events](https://llm4s.org/guide/agents/streaming): Watch an LLM4S agent turn as it happens: answer tokens, tool calls and model calls as StreamEvents, with replay and the live-versus-durable rule. - [Durable Checkpointers](https://llm4s.org/guide/agents/durable-checkpointers): Share an LLM4S checkpoint store between runtimes, recover a run whose process died, fork and prune thread history, and test a store against the contract. - [Human Review](https://llm4s.org/guide/agents/human-review): Pause an LLM4S agent for a person: approve a tool call, answer a question, review an answer or inspect a step, then resume the run. - [Delegation](https://llm4s.org/guide/agents/delegation): Delegate a bounded task to a typed subagent in LLM4S and get back only its typed report: inheritance, bounds, permissions and approvals. - [Running agents on several machines](https://llm4s.org/guide/agents/multiple-machines): Run an LLM4S agent service as several instances sharing threads through one PostgreSQL database, with a run queue, workers and recovery of dead runs. - [Real-World Application Patterns](https://llm4s.org/guide/patterns/): Production patterns for LLM applications in Scala: multi-agent orchestration, enterprise RAG, monitoring, scaling, error recovery and security. - [Multi-Agent Orchestration](https://llm4s.org/guide/patterns/multi-agent-orchestration): Design multi-agent systems in Scala: sequential and parallel delegation, with use cases, implementation sketches and the trade-offs of each pattern. - [RAG for Enterprise](https://llm4s.org/guide/patterns/rag-enterprise): Production RAG strategies: chunking, ingesting large document sets, hybrid vector and keyword search and multi-stage retrieval, as illustrative patterns. - [Production Monitoring](https://llm4s.org/guide/patterns/production-monitoring): What to track when running LLM applications in production: performance, quality and cost metrics, alert rules, request tracing and debug logging. - [Scaling Strategies](https://llm4s.org/guide/patterns/scaling-strategies): Scale LLM applications: request and distributed caching, rate limiting, batching embeddings and worker pools, as illustrative patterns. - [Error Recovery](https://llm4s.org/guide/patterns/error-recovery): Recover from LLM failures: retries with exponential backoff and jitter, timeouts, circuit breakers, model fallback and graceful degradation. - [Security Best Practices](https://llm4s.org/guide/patterns/security-best-practices): Security patterns for LLM applications: API key management and rotation, input validation, prompt injection defence, PII redaction and audit logging. - [Writing a Provider](https://llm4s.org/guide/writing-a-provider): Publish your own LLM4S provider module, a chat client or embedding provider, against llm4s-core without changing LLM4S itself. - [cats-effect Integration](https://llm4s.org/guide/cats-effect): Use LLM4S with cats-effect: llm4s-effect wraps LLMClient and Agent in IO, streams with fs2 and keeps blocking calls off the compute pool. - [ZIO Integration](https://llm4s.org/guide/zio): Use LLM4S with ZIO: llm4s-zio wraps LLMClient and Agent in ZIO effects, with ZLayer, ZIO Streams and LLMError in the error channel. - [Caching](https://llm4s.org/guide/caching): Avoid paying twice for the same LLM work in LLM4S: an embedding cache for exact repeats and a semantic cache for model responses. - [JSON Libraries](https://llm4s.org/guide/json-libraries): Use LLM4S with circe, play-json, zio-json or jsoniter-scala: pass your own types in and get them back without writing a second schema. - [RAG Evaluation](https://llm4s.org/guide/rag-evaluation): Measure the quality of a RAG pipeline in Scala with RAGAS metrics (faithfulness, relevancy, context precision and recall) and the LLM4S benchmark harness. - [Java](https://llm4s.org/guide/java): Call an LLM from Java with llm4s-java-api: add the dependency, configure a provider, send a prompt or conversation and read failures without Scala. - [Java Threading and Cancellation](https://llm4s.org/guide/java-threading-and-cancellation): Which thread an llm4s-java-api call blocks, whether a client can be shared, how to use virtual threads, and what an interrupt or timeout does. - [Monitoring](https://llm4s.org/guide/observability/): Monitor LLM4S applications in production: logging, tracing with Langfuse or OpenTelemetry, metrics, token usage and cost, and provider reliability. - [Provider Exchange Logging](https://llm4s.org/guide/observability/provider-exchange-logging): Capture the raw request and response of each provider call in LLM4S, to a JSON Lines file or your own sink, with redaction and truncation. - [Micrometer metrics](https://llm4s.org/guide/observability/micrometer): Record LLM4S request, token, cost and error metrics in a Micrometer MeterRegistry, so a Spring Boot or Quarkus service shows them with its own metrics. - [Enhanced Tracing Use Cases](https://llm4s.org/guide/observability/enhanced-tracing-use-cases): Use cases for in-process tracing in LLM4S with TraceCollectorTracing and InMemoryTraceStore: trace lookup by id, deterministic agent tests and latency. - [RAG Query Transformers](https://llm4s.org/guide/rag-query-transformers): Rewrite a user's query before it is embedded in an LLM4S RAG pipeline to improve retrieval for vague or conversational questions. - [Apache Pekko Integration](https://llm4s.org/guide/pekko): Use LLM4S with Apache Pekko: llm4s-pekko exposes streamed completions and agent runs as Pekko Streams Sources with backpressure and cancellation. - [Jev decision model](https://llm4s.org/guide/jev): Use llm4s-jev, a client for TypeSafe's Jev System One model: send a state and typed questions, and get typed answers your code can act on. - [Comparing LLM4S](https://llm4s.org/guide/comparison): How LLM4S compares with LangChain4j, Spring AI, Koog and Embabel for JVM LLM apps: capabilities, gaps, and when to choose or avoid it. - [Coming from LangChain4j or Spring AI](https://llm4s.org/guide/migrating-from-langchain4j): Move from LangChain4j or Spring AI to LLM4S: concepts side by side, with working code for model calls, typed output, tools, memory and RAG. - [Derived Schemas](https://llm4s.org/guide/derived-schemas): Derive the JSON schema for structured output and typed tools from a Scala case class with llm4s-schema-derivation (experimental). - [Testing with the Testkit](https://llm4s.org/guide/testing-with-the-testkit): Test code that calls an LLM with llm4s-testkit: a scriptable fake LLMClient that records what you sent and never touches the network. - [Multimodal content](https://llm4s.org/guide/multimodal): Send images and documents to a model in a user message or tool result with LLM4S, and check provider support before the request goes out. - [Java RAG](https://llm4s.org/guide/java-rag): Ingest documents and answer questions over them from Java with llm4s-java-rag, with answers that carry the chunks they came from. - [Spark and Databricks](https://llm4s.org/guide/spark): Enrich a Spark or Databricks DataFrame with LLM calls from Scala: one client per partition, retries and rate limits, and failed calls kept as data. - [Embeddings](https://llm4s.org/guide/embeddings): Turn text into vectors with LLM4S: choose a provider and model, create an EmbeddingClient, embed documents and queries, and handle dimensions. - [Custom Tools](https://llm4s.org/guide/custom-tools): Write a tool for an LLM4S agent with ToolBuilder: declare parameters, read arguments safely, return a result or error, and test it without a model. - [Java Reactor](https://llm4s.org/guide/java-reactor): Stream a model's reply as a Reactor Flux from Java with llm4s-reactor, for Spring WebFlux and other reactive pipelines. - [Serving an Agent over HTTP](https://llm4s.org/guide/http-reference-apps): Reference apps that serve an LLM4S agent over HTTP with http4s, ZIO HTTP, Tapir and Play: a chat endpoint, a streamed endpoint, cancellation and tests. - [Quarkus](https://llm4s.org/guide/quarkus): Call a model from a Quarkus app with LLM4S: a CDI producer for JLlmClient, settings in application.properties and a REST endpoint off the event loop. - [Data Protection](https://llm4s.org/guide/data-protection): What personal data LLM4S sends where, what it keeps and logs by default, provider data residency, and deletion, for privacy and DPIA reviews. - [Moving a Java app from LangChain4j or Spring AI](https://llm4s.org/guide/java-migration): Map LangChain4j and Spring AI concepts to llm4s-java-api, with compiled Java for tools, records, RAG, streaming, Spring Boot and tests. - [STT Domain Model](https://llm4s.org/guide/stt-domain-model): The expanded speech-to-text domain model in LLM4S: STTOptions, WordTimestamp, Transcription and the STTError cases, with validation and examples. - [Coming from sttp-ai or openai-scala-client](https://llm4s.org/guide/migrating-from-scala-llm-clients): Move a Scala app from sttp-ai or openai-scala-client to LLM4S: calls side by side with compiled code, and when to stay on your client. - [Typed Prompts](https://llm4s.org/guide/prompts): Build LLM prompts in Scala 3 with compile-time checked interpolation: values rendered by a derived type class, untrusted input fenced (experimental). - [Capability-Typed Clients](https://llm4s.org/guide/capabilities): Check once that a model can see images or call tools, then let the Scala compiler refuse a client that was not checked (llm4s-capabilities, experimental). - [Kafka](https://llm4s.org/guide/kafka): Enrich a Kafka topic with an LLM using fs2-kafka and LLM4S: bounded concurrency, retries, a dead-letter topic and offsets committed after the produce. - [Replacing a Python Sidecar](https://llm4s.org/guide/replacing-a-python-sidecar): Move a Python sidecar's LLM logic into Scala with LLM4S: vLLM, TGI and llama.cpp models as OpenAI-compatible sections, Python functions as MCP tools. - [Reference Architecture](https://llm4s.org/guide/reference-architecture): Deploy LLM4S behind an AI gateway: secret injection, egress policy, failover, quotas and spend, with tested Kubernetes manifests. - [Direct Style and Ox](https://llm4s.org/guide/direct-style): Use LLM4S in direct style on JDK 21 virtual threads: plain Result code, and llm4s-ox for streamed completions as an Ox Flow, bounded fan-out, races, timeouts and retries. - [Apache Flink](https://llm4s.org/guide/flink): Enrich an Apache Flink 2.x stream with LLM calls from Scala 3: an async function per task, timeouts and capacity, and failed calls sent to a dead-letter side output. - [Tapir Endpoints as Tools](https://llm4s.org/guide/tapir-tools): Turn the tapir endpoints a Scala service already has into LLM4S tools, with each tool's schema derived from its endpoint. - [Pick Your Stack](https://llm4s.org/guide/effect-systems): One LLM4S program in plain Result, cats-effect, ZIO and Pekko side by side: the semantics every effect bridge shares, and the honest differences. - [Java AI services](https://llm4s.org/guide/java-ai-services): Declare an annotated Java interface and let llm4s-java-api implement it: prompt templates, typed answers, tools, memory, async and streaming. - [Your HTTP Client](https://llm4s.org/guide/http-transport): Send the provider clients' requests through the sttp backend your service already has, and test a provider call against sttp's stub backend. - [Coming from Python](https://llm4s.org/guide/for-python-developers): LLM code in Python (OpenAI SDK, LangChain, LlamaIndex, Pydantic) next to the same thing in Scala 3 with LLM4S, one Scala concept per step. - [Micronaut](https://llm4s.org/guide/micronaut): Call a model from a Micronaut 4 app with LLM4S: a @Factory bean for JLlmClient, settings in application.yml, blocking and streamed endpoints and a health indicator. - [Helidon](https://llm4s.org/guide/helidon): Call a model from a Helidon SE 4 app with LLM4S: JLlmClient built from application.yaml, blocking and streamed routes on virtual threads and a health check. - [Jupyter Notebooks](https://llm4s.org/guide/notebooks): Run LLM4S in Jupyter with the Almond Scala kernel: two offline notebooks, configuration inside a notebook, and known limits. - [Spring AI](https://llm4s.org/guide/spring-ai): Use any llm4s client as a Spring AI ChatModel or EmbeddingModel, and a Spring AI ChatModel as an llm4s client, with llm4s-spring-ai. - [Modular RAG Example](https://llm4s.org/guide/modular-rag-example): A modular RAG example for LLM4S: ingestion, retrieval and generation as separate modules, how to run the sample and use your own document folder. ## Cookbook - [Cookbook](https://llm4s.org/examples/cookbook): The LLM4S cookbook: complete Scala programs for classification, extraction, summarising, RAG, tool calling, streaming and agents, each runnable without a key. - [Classify text into an enum](https://llm4s.org/examples/cookbook/structured-output): Classify a customer message into an enum with LLM4S structured output: a Ticket case class with a fixed category set and an urgency field. - [Extract structured data from an email](https://llm4s.org/examples/cookbook/email-extraction): Extract an order change from a free-text email into a Scala case class with a list of line items, using LLM4S structured output. - [Summarise a long document](https://llm4s.org/examples/cookbook/summarise): Summarise a document longer than the context window in Scala: cut it into parts, summarise each, then summarise the summaries (map-reduce). - [Answer questions over a folder of files](https://llm4s.org/examples/cookbook/folder-qa): Answer questions over a folder of files in Scala: ingest each file into the LLM4S RAG pipeline, retrieve passages and answer from them. - [An agent that calls two tools](https://llm4s.org/examples/cookbook/tool-calling): Give an LLM4S agent an exchange-rate tool of your own plus the built-in calculator, and let the model chain the two to answer. - [A guardrailed chatbot](https://llm4s.org/examples/cookbook/guardrails): Build a guardrailed chatbot in Scala: reject a bad request before the model sees it and an over-long answer before the user does. - [Stream tokens to the terminal](https://llm4s.org/examples/cookbook/streaming): Print each piece of an LLM reply as it is produced with streamComplete in Scala, and get the whole completion at the end. - [Fall back between providers](https://llm4s.org/examples/cookbook/fallback): Retry a provider with ReliableClient and ask a second provider when the first still fails, in an LLM4S Scala program. - [Cache repeated calls](https://llm4s.org/examples/cookbook/caching): Wrap an LLM4S client in CachingLLMClient so a question asked again is answered from the cache without a second model call. - [Evaluate an answer with a judge](https://llm4s.org/examples/cookbook/judge): Grade an LLM answer against a reference with a judge model from 1 to 5, to check whether a prompt or model change made answers better. - [Answer questions with keyword search](https://llm4s.org/examples/cookbook/document-qa): Answer questions from a small document set in Scala with no embedding model: an in-memory BM25 keyword index retrieves the best passage. - [Remember facts between turns](https://llm4s.org/examples/cookbook/memory): Record what a user says in an LLM4S memory manager and put the relevant facts in the system prompt of the next question. - [Several agents in one graph](https://llm4s.org/examples/cookbook/multi-agent-graph): Ask two specialist agents in parallel and let an editor agent combine their views, using an LLM4S agent graph in Scala.