<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>Vitthal Mirji</title><link>https://vitthalmirji.com/tags/azure/</link><description>Technical articles on Scala, data engineering, functional programming, and software architecture by Vitthal Mirji.</description><language>en-us</language><copyright>Vitthal Mirji</copyright><managingEditor>vitthalmirji@gmail.com (Vitthal Mirji)</managingEditor><lastBuildDate>Fri, 06 Nov 2026 13:45:55 +0000</lastBuildDate><atom:link href="https://vitthalmirji.com/tags/azure/index.xml" rel="self" type="application/rss+xml"/><image><url>https://vitthalmirji.com/images/default-og.png</url><title>Vitthal Mirji</title><link>https://vitthalmirji.com/</link></image><item><title>llm4s: Type-safe LLM infra for Scala that makes runtime errors compile-time</title><link>https://vitthalmirji.com/2025/10/llm4s-type-safe-llm-infra-for-scala-that-makes-runtime-errors-compile-time/</link><guid isPermaLink="true">https://vitthalmirji.com/2025/10/llm4s-type-safe-llm-infra-for-scala-that-makes-runtime-errors-compile-time/</guid><pubDate>Fri, 31 Oct 2025 00:00:00 +0000</pubDate><dc:creator>vitthal-mirji</dc:creator><category>Scala</category><category>llm4s</category><category>LLM</category><category>Type Safety</category><category>Functional Programming</category><category>Error Handling</category><category>Production</category><category>OpenAI</category><category>Anthropic</category><category>Azure</category><category>Ollama</category><category>Agent Framework</category><category>llm</category><category>Software Engineering</category><category>Scala</category><category>LLM</category><description>Deep-dive into llm4s, a production-grade Scala framework for building LLM applications. From type-safe error handling to provider abstraction and context management, it covers agent orchestration and shipping reliable LLM systems in Scala.</description><content:encoded><![CDATA[<p class="lead"><p>You&rsquo;re shipping an LLM feature. You test it with OpenAI. It works. You push to production. Someone changes the API key format. Your app crashes with a cryptic error at 2 AM.</p>
<p>Or you&rsquo;re switching providers - OpenAI to Anthropic. You rewrite half your codebase because the APIs are completely different. Message formats, tool calling, streaming - all different. Three days of work.</p>
<p>Been there. Done that. That&rsquo;s when I discovered llm4s in the Scala community - a framework built to solve exactly these problems. I started contributing, and this is what I learned.</p>
</p>


<p><a class="btn" href="https://github.com/llm4s/llm4s" target="_blank" rel="noopener noreferrer">Explore llm4s on GitHub</a></p>


<h3 id="the-unglamorous-work-that-matters">The unglamorous work that matters</h3>
<p>Here&rsquo;s the thing about AI/ML/LLM: everyone wants to build the cool AI features. LLM orchestration. Agent frameworks. RAG pipelines. That&rsquo;s the sexy stuff that gets your Leadership/Managers excited who are just fan of buzzwords &amp; boss/upper-management-pleasing. And you will get LinkedIn/Twitter followers as well.</p>
<p>But you know what actually makes a framework production-ready? The boring parts. Error handling. Developer experience. Type safety. Safety utilities. The plumbing nobody sees but everyone curses when it breaks.</p>
<p>I found myself working on exactly that - the edges, the foundations, the fundamentals. Not because it&rsquo;s glamorous, but because it&rsquo;s what teams need when the on-call pager goes off at 2 AM and someone&rsquo;s screaming &ldquo;EVERYTHING IS DOWN!&rdquo;</p>
<p>Research backs this up: <a href="https://openssf.org/blog/2025/09/23/open-infrastructure-is-not-free-a-joint-statement-on-sustainable-stewardship/" rel="noopener external" target="_blank">96% of open source&rsquo;s $8.8 trillion value depends on just 5% of contributors</a>
 doing infrastructure work. The stuff that doesn&rsquo;t get headlines but prevents cascading failures.</p>
<p>My llm4s contributions? <a href="/2025/08/production-error-handling-when-our-llm-pipeline-threw-unknown-error-in-logs/">Type-safe error hierarchies</a>
 that made debugging 60% faster. <a href="/2025/08/error-hierarchy-refinement-smart-constructors-and-the-code-we-deleted-in-prod/">Smart constructors</a>
 that prevent invalid states at compile time. <a href="/2025/09/safety-refactor-the-p1-streaming-bug-wrong-errors-and-47-try-catch-blocks/">Safety utilities</a>
 that eliminate try-catch blocks. <a href="/2025/10/five-production-patterns-from-building-llm4s-what-actually-works-in-prod-today/">Production patterns</a>
 that scale across 8 LLM providers.</p>
<p>This isn&rsquo;t the core AI/ML/LLM work. But it&rsquo;s what lets the core AI/ML/LLM work actually run in production without crashing.</p>
<p>The rest of this article &amp; llm4s:series explains what llm4s does and why it&rsquo;s built this way. If you want the deep-dive into how we built the foundation - error handling, developer tooling, safety patterns - that&rsquo;s the six-part series this belongs to.</p>
<h2 id="why-scala-for-llms">Why Scala for LLMs?</h2>
<p>Most LLM work happens in Python. LangChain, LlamaIndex, CrewAI - all Python. But here&rsquo;s the thing: Python&rsquo;s flexibility becomes a liability at scale.</p>
<p>You&rsquo;re building an AI feature for an enterprise app. It needs to integrate with existing JVM services. It needs type safety. It needs to handle millions of requests. Python starts showing cracks.</p>
<p><strong>Here&rsquo;s the mental model that matters:</strong> Python is perfect for three things - prototypes, proof-of-concepts, and interview coding challenges. You want to test an idea in an afternoon? Python. You need to demo something to stakeholders tomorrow? Python. You&rsquo;re in a Google interview? Python.</p>
<p>But the moment you move past &ldquo;does this work?&rdquo; to &ldquo;can we run this in production?&rdquo; - that&rsquo;s when you need the JVM.</p>
<p>Why? Because production isn&rsquo;t about writing code fast. It&rsquo;s about code that doesn&rsquo;t break when your colleague refactors something three months later. It&rsquo;s about integrating with Kafka without network serialization overhead. It&rsquo;s about debugging a P0 incident at 3 AM with structured errors, not generic stack traces.</p>
<p>Python gets you to the prototype. The JVM gets you to production. Different tools for different jobs.</p>
<p><strong>When to choose Scala + llm4s vs Python:</strong></p>
<pre class="mermaid">flowchart TD
    START{Building LLM app} --&gt; Q1{Running on JVM?}

    Q1 --&gt;|Yes| Q2{Need Kafka/Spark&lt;br/&gt;integration?}
    Q1 --&gt;|No| Q3{Team size &gt; 10?}

    Q2 --&gt;|Yes| SCALA[✅ Use Scala + llm4s&lt;br/&gt;Native JVM integration]
    Q2 --&gt;|No| Q4{Production scale?}

    Q3 --&gt;|Yes| Q5{Type safety critical?}
    Q3 --&gt;|No| PYTHON[Use Python&lt;br/&gt;LangChain/LlamaIndex]

    Q4 --&gt;|Enterprise| SCALA
    Q4 --&gt;|Prototype| Q3

    Q5 --&gt;|Yes| SCALA
    Q5 --&gt;|No| PYTHON

    style SCALA fill:#e1ffe1,stroke:#2d7a2d,color:#000
    style PYTHON fill:#e1f5ff,stroke:#0066cc,color:#000
</pre><p>Scala gives you:</p>
<ul>
<li><strong>Type safety</strong>: Catch errors at compile time, not in production</li>
<li><strong>JVM ecosystem</strong>: Native integration with enterprise systems (Kafka, Spark, Akka, ZIO)</li>
<li><strong>Functional programming</strong>: Immutable data structures, composable error handling, predictable systems</li>
<li><strong>Performance</strong>: JVM speed with functional elegance</li>
<li><strong>Concurrency</strong>: Advanced models for safe, efficient parallelism</li>
</ul>
<p>But there was no production-grade LLM framework for Scala. Until now.</p>
<div class="admonition warning">
  <div class="admonition-title">Warning</div>
  <div class="admonition-content">
    <p>The prototype-to-production trap: You build a prototype in Python because it&rsquo;s fast. Stakeholders love it. &ldquo;Ship this to production!&rdquo; Now you&rsquo;re stuck maintaining Python in a JVM shop, dealing with REST overhead to Kafka, debugging generic exceptions, and watching refactorings break things your tests didn&rsquo;t catch.</p>
<p>Save yourself the pain. If you know it&rsquo;s going to production, start with the JVM. If you&rsquo;re just prototyping, Python is fine - just know you&rsquo;ll rewrite it before shipping.</p>

  </div>
</div>
<h2 id="why-another-llm-library">Why another LLM library?</h2>
<p>I&rsquo;ve been working with LLMs in Scala for a while now. Every project started the same way: wrap an HTTP client, handle JSON parsing, deal with errors. Rinse and repeat.</p>
<p>The problems kept showing up:</p>
<p><strong>Problem 1: Runtime errors you should&rsquo;ve caught at compile time</strong></p>
<p>Someone typos a role: <code>&quot;asistant&quot;</code> instead of <code>&quot;assistant&quot;</code>. It compiles. It runs. It fails when the API rejects it. Why didn&rsquo;t the compiler catch this?</p>
<p><strong>Problem 2: Every provider is a snowflake</strong></p>
<p>OpenAI uses <code>messages</code>, Anthropic uses a different format. Tool calling? Different JSON structure for each provider. Streaming? Different SSE formats. You end up with provider-specific code scattered everywhere.</p>
<p><strong>Problem 3: Error handling is everyone&rsquo;s custom solution</strong></p>
<p>One team throws exceptions. Another returns <code>Option</code>. Another uses <code>Try</code>. None of them distinguish recoverable errors (rate limits, network issues) from non-recoverable ones (auth failures, invalid input). Your retry logic is a mess.</p>
<p><strong>Problem 4: Production concerns are afterthoughts</strong></p>
<p>You need tracing. You need context management (token limits). You need proper logging. You need health checks. You build these one-off for every project. They&rsquo;re never quite right.</p>
<p><strong>Problem 5: Python doesn&rsquo;t scale with your team</strong></p>
<p>Five engineers, ten engineers, fifty engineers - Python&rsquo;s dynamic typing becomes chaos. Refactorings break things. Tests catch some errors. Production catches the rest. Your team spends more time debugging than building.</p>
<p>llm4s fixes all of this. Not by doing more. By doing it right - once.</p>
<p><strong>So what is llm4s, and how does it solve these problems?</strong> Let&rsquo;s start with the fundamentals.</p>
<div class="admonition tip">
  <div class="admonition-title">Quick Win</div>
  <div class="admonition-content">
    Already running Scala + Spark or Kafka? You can integrate llm4s with zero network overhead - it&rsquo;s just another JVM dependency. No REST endpoints, no serialization layers, no Python bridge processes burning CPU. Direct method calls from your existing pipeline code to LLM APIs.
  </div>
</div>
<hr>
<h2 id="what-is-llm4s">What is llm4s?</h2>
<p>llm4s is a production-grade Scala framework for building LLM applications with compile-time safety, functional error handling, and provider abstraction.</p>
<p>Here&rsquo;s what that means in practice:</p>
<p><strong>Type-safe everything</strong></p>
<p>String-based enums? No. Sealed traits with exhaustive pattern matching. Invalid states? Can&rsquo;t construct them - smart constructors prevent it. Mixing up IDs? Compile error.</p>
<p><strong>Functional error handling</strong></p>
<p>No exceptions. All errors are values. <code>Result[A] = Either[LLMError, A]</code>. Recoverable vs non-recoverable errors. Composable error handling with for-comprehensions.</p>
<p><strong>Provider abstraction</strong></p>
<p>Same API for OpenAI, Anthropic, Azure, Ollama, OpenRouter. Switch providers by changing config. No code changes. Your business logic stays clean.</p>
<p><strong>Production ready</strong></p>
<p>Built-in tracing (Langfuse integration). Context management (automatic token limit handling). Agent framework. Tool calling API. Streaming. Cross-compiled for Scala 2.13 and 3.x.</p>
<h3 id="run-it-now">Run it now</h3>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// Add to build.sbt
</span></span></span><span class="line"><span class="cl"><span class="n">libraryDependencies</span> <span class="o">+=</span> <span class="s">&#34;org.llm4s&#34;</span> <span class="o">%%</span> <span class="s">&#34;core&#34;</span> <span class="o">%</span> <span class="s">&#34;0.9.0&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Your first LLM call
</span></span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect._</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect.model._</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.config.ConfigReader</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">configResult</span> <span class="k">=</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">Provider</span><span class="o">()</span>
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="n">configResult</span><span class="o">.</span><span class="n">flatMap</span> <span class="o">{</span> <span class="n">config</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">client</span> <span class="k">=</span> <span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">(</span><span class="n">config</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">conversation</span> <span class="k">=</span> <span class="nc">Conversation</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">    <span class="nc">UserMessage</span><span class="o">(</span><span class="nc">TextContent</span><span class="o">(</span><span class="s">&#34;What&#39;s the capital of France?&#34;</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">  <span class="o">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="n">client</span><span class="o">.</span><span class="n">flatMap</span><span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="o">))</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">result</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="n">println</span><span class="o">(</span><span class="n">completion</span><span class="o">.</span><span class="n">message</span><span class="o">.</span><span class="n">content</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="n">println</span><span class="o">(</span><span class="s">s&#34;Error: </span><span class="si">${</span><span class="n">error</span><span class="o">.</span><span class="n">formatted</span><span class="si">}</span><span class="s">&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><div class="admonition info">
  <div class="admonition-title">Information</div>
  <div class="admonition-content">
    Get started instantly with the Giter8 template: <code>sbt new llm4s/llm4s.g8</code> - working app in 60 seconds.
  </div>
</div>
<p><strong>Okay, that&rsquo;s the high-level pitch. Now let&rsquo;s dive into how llm4s actually works under the hood.</strong> We&rsquo;ll start with type safety - the foundation that makes everything else possible.</p>
<hr>
<h2 id="part-1---type-safety-making-bad-code-unwritable">Part 1 - Type safety: making bad code unwritable</h2>
<h3 id="why-type-safety-matters">Why type safety matters</h3>
<p>You know how it goes. You&rsquo;re writing message roles as strings: <code>&quot;user&quot;</code>, <code>&quot;assistant&quot;</code>, <code>&quot;system&quot;</code>. Works fine. Until someone typos it: <code>&quot;asistant&quot;</code>. One missing &rsquo;s&rsquo;. One innocent typo.</p>
<p>It compiles. Your IDE gives you the green checkmark of false confidence. Your tests pass because you didn&rsquo;t test for typos (who does?). It deploys.</p>
<p>And then it fails in production. The API returns a cryptic 400 error. You spend 20 minutes debugging. You check the API key. You check the network. You check everything except the one thing that&rsquo;s wrong. Finally you spot it: <code>&quot;asistant&quot;</code>.</p>
<p>You fix it. You deploy again. You think: &ldquo;Why didn&rsquo;t the compiler catch this?&rdquo;</p>
<p>Because strings are liars. They&rsquo;ll accept anything.</p>
<h3 id="how-llm4s-handles-message-roles">How llm4s handles message roles</h3>
<p>llm4s uses sealed traits. Not strings.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// core/src/main/scala/org/llm4s/llmconnect/model/Message.scala
</span></span></span><span class="line"><span class="cl"><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">role</span><span class="k">:</span> <span class="kt">String</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">content</span><span class="k">:</span> <span class="kt">Content</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">UserMessage</span><span class="o">(</span><span class="n">content</span><span class="k">:</span> <span class="kt">Content</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">role</span> <span class="k">=</span> <span class="s">&#34;user&#34;</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">AssistantMessage</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">content</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">toolCalls</span><span class="k">:</span> <span class="kt">Seq</span><span class="o">[</span><span class="kt">ToolCall</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Seq</span><span class="o">.</span><span class="n">empty</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">role</span> <span class="k">=</span> <span class="s">&#34;assistant&#34;</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">SystemMessage</span><span class="o">(</span><span class="n">content</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">role</span> <span class="k">=</span> <span class="s">&#34;system&#34;</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">ToolMessage</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">toolCallId</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">content</span><span class="k">:</span> <span class="kt">String</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">role</span> <span class="k">=</span> <span class="s">&#34;tool&#34;</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Now typos are compile errors:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// This won&#39;t compile
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">msg</span> <span class="k">=</span> <span class="nc">AsistantMessage</span><span class="o">(</span><span class="s">&#34;Hello&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="c1">// Error: not found: type AsistantMessage
</span></span></span><span class="line"><span class="cl"><span class="c1">// The compiler is your friend, pointing at your typo before you even run the code
</span></span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// This is the only way
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">msg</span> <span class="k">=</span> <span class="nc">AssistantMessage</span><span class="o">(</span><span class="s">&#34;Hello&#34;</span><span class="o">)</span>  <span class="o">//</span> <span class="nc">OK</span> <span class="o">-</span> <span class="n">autocomplete</span> <span class="n">won</span>&#39;t <span class="n">even</span> <span class="n">let</span> <span class="n">you</span> <span class="n">mess</span> <span class="k">this</span> <span class="n">up</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="the-power-of-exhaustive-pattern-matching">The power of exhaustive pattern matching</h3>
<p>Sealed traits give you something powerful: the compiler knows all possible cases.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">def</span> <span class="n">routeMessage</span><span class="o">(</span><span class="n">msg</span><span class="k">:</span> <span class="kt">Message</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span> <span class="k">=</span> <span class="n">msg</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="k">_:</span> <span class="kt">UserMessage</span> <span class="o">=&gt;</span> <span class="n">handleUser</span><span class="o">(</span><span class="n">msg</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="k">_:</span> <span class="kt">AssistantMessage</span> <span class="o">=&gt;</span> <span class="n">handleAssistant</span><span class="o">(</span><span class="n">msg</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="k">_:</span> <span class="kt">SystemMessage</span> <span class="o">=&gt;</span> <span class="n">handleSystem</span><span class="o">(</span><span class="n">msg</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// Forgot ToolMessage? Compiler warning:
</span></span></span><span class="line"><span class="cl">  <span class="c1">// &#34;match may not be exhaustive. It would fail on: ToolMessage&#34;
</span></span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Add a new message type? Every pattern match in your codebase gets a compiler warning. You fix them all before the code even runs.</p>
<h3 id="real-production-benefit">Real production benefit</h3>
<p>When we added <code>ToolMessage</code> for function calling support, the compiler flagged 18 pattern matches across the codebase. We fixed all 18 before deploying. Zero runtime issues.</p>
<p>With string-based roles, we would&rsquo;ve shipped, discovered missing cases through bug reports, then scrambled to fix them.</p>
<p><strong>Type safety moved bugs from runtime to compile time. That&rsquo;s the difference between a 2 AM page and sleeping through the night.</strong></p>
<div class="admonition success">
  <div class="admonition-title">Production Win</div>
  <div class="admonition-content">
    Exhaustive pattern matching catches breaking changes at compile time. When we added ToolMessage support, the compiler flagged 18 locations that needed updates. We fixed all 18 before deploying. Zero production issues. With string-based approaches, you discover these through bug reports at 3 AM.
  </div>
</div>
<p><strong>But what about the errors that do happen at runtime?</strong> LLMs fail. APIs go down. Rate limits hit. You need a better way to handle these than try-catch. That&rsquo;s where Result types come in.</p>
<hr>
<h2 id="part-2---result-types-functional-error-handling-without-exceptions">Part 2 - Result types: functional error handling without exceptions</h2>
<h3 id="why-exceptions-dont-work-for-llm-code">Why exceptions don&rsquo;t work for LLM code</h3>
<p>Exceptions are wrong for LLM code. Here&rsquo;s why.</p>
<p>LLM calls fail. A lot. Rate limits. Network timeouts. Invalid JSON. Auth failures. Service errors. If Murphy&rsquo;s Law had a favorite API, it&rsquo;d be LLM providers.</p>
<p>If you throw exceptions for all of these, your code becomes a mess of try-catch blocks. You catch generic <code>Exception</code>. You lose type information. You can&rsquo;t distinguish &ldquo;retry this&rdquo; from &ldquo;give up now.&rdquo; Your error handling is basically a coin flip.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// Bad: Exception-based code (AKA &#34;hope and pray&#34;)
</span></span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">response</span> <span class="k">=</span> <span class="n">callOpenAI</span><span class="o">(</span><span class="n">prompt</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="n">parseJSON</span><span class="o">(</span><span class="n">response</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span> <span class="k">catch</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="n">ex</span><span class="k">:</span> <span class="kt">RateLimitException</span> <span class="o">=&gt;</span> <span class="c1">// How long to wait? The exception doesn&#39;t tell you
</span></span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="n">ex</span><span class="k">:</span> <span class="kt">NetworkException</span> <span class="o">=&gt;</span> <span class="c1">// Should we retry? Your guess is as good as mine
</span></span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="n">ex</span><span class="k">:</span> <span class="kt">AuthException</span> <span class="o">=&gt;</span> <span class="c1">// This is fatal, but we&#39;re catching it the same way
</span></span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="n">ex</span><span class="k">:</span> <span class="kt">Exception</span> <span class="o">=&gt;</span> <span class="c1">// What even is this? Good luck debugging at 3 AM
</span></span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>You need a better way. Enter: Result types.</p>
<h3 id="how-resulta-makes-errors-explicit">How Result[A] makes errors explicit</h3>
<p>llm4s uses <code>Result[A] = Either[LLMError, A]</code>. Every LLM operation returns a Result. Errors are values, not exceptions.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">def</span> <span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="k">:</span> <span class="kt">Conversation</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Completion</span><span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">//</span> <span class="nc">Returns</span><span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">LLMError</span>, <span class="kt">Completion</span><span class="o">]</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Pattern matching on results is clean:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="n">result</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="c1">// Success - use the completion
</span></span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="c1">// Error - handle it
</span></span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="composing-operations-with-for-comprehensions">Composing operations with for-comprehensions</h3>
<p>The real power: composing multiple operations. Each can fail. The for-comprehension short-circuits on the first error.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="n">config</span> <span class="k">&lt;-</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">Provider</span><span class="o">()</span>           <span class="c1">// Might fail: ConfigurationError
</span></span></span><span class="line"><span class="cl">  <span class="n">client</span> <span class="k">&lt;-</span> <span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">(</span><span class="n">config</span><span class="o">)</span>         <span class="c1">// Might fail: ValidationError
</span></span></span><span class="line"><span class="cl">  <span class="n">completion</span> <span class="k">&lt;-</span> <span class="n">client</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="o">)</span> <span class="c1">// Might fail: RateLimitError, NetworkError
</span></span></span><span class="line"><span class="cl">  <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">tracer</span><span class="o">.</span><span class="n">traceCompletion</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span>     <span class="c1">// Might fail: TracingError
</span></span></span><span class="line"><span class="cl"><span class="o">}</span> <span class="k">yield</span> <span class="n">completion</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// If any step fails, you get Left(error)
</span></span></span><span class="line"><span class="cl"><span class="o">//</span> <span class="nc">If</span> <span class="n">all</span> <span class="n">steps</span> <span class="n">succeed</span><span class="o">,</span> <span class="n">you</span> <span class="n">get</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><p>No try-catch. No nested error handling. Clean, composable code.</p>
<h3 id="recoverable-vs-non-recoverable-errors">Recoverable vs non-recoverable errors</h3>
<p>llm4s distinguishes errors you can retry from errors you can&rsquo;t.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">LLMError</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Errors you can retry
</span></span></span><span class="line"><span class="cl"><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">RecoverableError</span> <span class="k">extends</span> <span class="nc">LLMError</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">shouldRetry</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=</span> <span class="kc">true</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">retryAfter</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Duration</span><span class="o">]</span> <span class="k">=</span> <span class="nc">None</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Errors you can&#39;t recover from
</span></span></span><span class="line"><span class="cl"><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">NonRecoverableError</span> <span class="k">extends</span> <span class="nc">LLMError</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">canRecover</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Error types and recovery strategies:</strong></p>
<table>
	<thead>
			<tr>
					<th>Error type</th>
					<th>Category</th>
					<th>What it means</th>
					<th>What to do</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>RateLimitError</code></td>
					<td>Recoverable</td>
					<td>API rate limit hit</td>
					<td>Wait <code>retryAfter</code> duration, then retry</td>
			</tr>
			<tr>
					<td><code>TimeoutError</code></td>
					<td>Recoverable</td>
					<td>Request took too long</td>
					<td>Retry with exponential backoff</td>
			</tr>
			<tr>
					<td><code>NetworkError</code></td>
					<td>Recoverable</td>
					<td>Connection failed</td>
					<td>Retry, check network connectivity</td>
			</tr>
			<tr>
					<td><code>ServiceError</code></td>
					<td>Recoverable</td>
					<td>Provider service issue (5xx)</td>
					<td>Retry with backoff, escalate if persists</td>
			</tr>
			<tr>
					<td><code>AuthenticationError</code></td>
					<td>Non-recoverable</td>
					<td>Invalid API key</td>
					<td>Fix credentials, don&rsquo;t retry</td>
			</tr>
			<tr>
					<td><code>ValidationError</code></td>
					<td>Non-recoverable</td>
					<td>Invalid input data</td>
					<td>Fix the input, don&rsquo;t retry</td>
			</tr>
			<tr>
					<td><code>ModelNotFoundError</code></td>
					<td>Non-recoverable</td>
					<td>Model doesn&rsquo;t exist</td>
					<td>Update model name, don&rsquo;t retry</td>
			</tr>
			<tr>
					<td><code>ContentFilterError</code></td>
					<td>Non-recoverable</td>
					<td>Content policy violation</td>
					<td>Modify prompt, don&rsquo;t retry</td>
			</tr>
	</tbody>
</table>
<p>The hierarchy guides your retry logic automatically.</p>
<p>Your retry logic becomes simple:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="n">result</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">completion</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="k">:</span> <span class="kt">RecoverableError</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="n">error</span><span class="o">.</span><span class="n">retryAfter</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="nc">Some</span><span class="o">(</span><span class="n">delay</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nc">Thread</span><span class="o">.</span><span class="n">sleep</span><span class="o">(</span><span class="n">delay</span><span class="o">.</span><span class="n">toMillis</span><span class="o">);</span> <span class="n">retry</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="nc">None</span> <span class="k">=&gt;</span> <span class="n">exponentialBackoff</span><span class="o">();</span> <span class="n">retry</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="k">:</span> <span class="kt">NonRecoverableError</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="n">logError</span><span class="o">(</span><span class="n">error</span><span class="o">);</span> <span class="n">failFast</span><span class="o">()</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="real-production-scenario">Real production scenario</h3>
<p>Before Result types, we&rsquo;d see this beauty in logs:</p>
<div class="highlight highlight-text" data-lang="text"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Exception in thread &#34;main&#34; java.lang.RuntimeException: API call failed</span></span></code></pre></td></tr></table>
</div>
</div><p>Useless. Might as well say &ldquo;Something broke somewhere, good luck!&rdquo; We couldn&rsquo;t tell if it was a rate limit (wait and retry), network error (retry with backoff), or auth failure (wake up the ops team). Every error looked the same.</p>
<p>After Result types:</p>
<div class="highlight highlight-text" data-lang="text"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Left(RateLimitError(&#34;Rate limit exceeded&#34;, retryAfter=Some(30 seconds), provider=Some(&#34;openai&#34;)))</span></span></code></pre></td></tr></table>
</div>
</div><p>Clear. Actionable. Self-documenting. The error tells you exactly what&rsquo;s wrong, which provider it came from, and when to retry. No guessing. No prayers. Just facts.</p>
<p><strong>Type safety prevents typos. Result types handle runtime failures gracefully. But there&rsquo;s still a problem:</strong> every LLM provider has a different API. OpenAI looks nothing like Anthropic. That means code duplication, or worse - vendor lock-in. Let&rsquo;s fix that.</p>
<hr>
<h2 id="part-3---provider-abstraction-write-once-run-anywhere">Part 3 - Provider abstraction: write once, run anywhere</h2>
<h3 id="why-provider-abstraction-matters">Why provider abstraction matters</h3>
<p>You&rsquo;re using OpenAI. Your app is live. Customers are happy. Then management drops this on you: &ldquo;Switch to Anthropic. Costs are killing us.&rdquo;</p>
<p>Without abstraction, you&rsquo;re in for a rough week. Message formats are different. Tool calling uses completely different JSON. Streaming has different SSE formats. Error codes don&rsquo;t line up. Three days minimum to rewrite everything. Then another day to test it. Then a risky deployment where you&rsquo;re basically crossing your fingers.</p>
<p>With llm4s? You change one line of config. Literally one line. Deploy. Done. Go back to drinking your coffee.</p>
<h3 id="how-the-llmclient-trait-works">How the LLMClient trait works</h3>
<p>llm4s defines one interface: <code>LLMClient</code>. Every provider implements it.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">trait</span> <span class="nc">LLMClient</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">complete</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">conversation</span><span class="k">:</span> <span class="kt">Conversation</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">options</span><span class="k">:</span> <span class="kt">CompletionOptions</span> <span class="o">=</span> <span class="nc">CompletionOptions</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">  <span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Completion</span><span class="o">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">streamComplete</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">conversation</span><span class="k">:</span> <span class="kt">Conversation</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">options</span><span class="k">:</span> <span class="kt">CompletionOptions</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">onChunk</span><span class="k">:</span> <span class="kt">StreamedChunk</span> <span class="o">=&gt;</span> <span class="nc">Unit</span>
</span></span><span class="line"><span class="cl">  <span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Completion</span><span class="o">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">validate</span><span class="o">()</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Unit</span><span class="o">]</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">close</span><span class="o">()</span><span class="k">:</span> <span class="kt">Unit</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">healthCheck</span><span class="o">()</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">ClientStatus</span><span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>OpenAI implements it. Anthropic implements it. Azure implements it. Ollama implements it. OpenRouter implements it.</p>
<p>Your code doesn&rsquo;t care which provider you&rsquo;re using. You code against <code>LLMClient</code>.</p>
<p><strong>Provider support at a glance:</strong></p>
<table>
	<thead>
			<tr>
					<th>Provider</th>
					<th>Use case</th>
					<th>Model example</th>
					<th>Special features</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><strong>OpenAI</strong></td>
					<td>Production, vision tasks</td>
					<td><code>gpt-4o</code>, <code>gpt-4o-mini</code></td>
					<td>Vision, function calling, structured outputs</td>
			</tr>
			<tr>
					<td><strong>Anthropic</strong></td>
					<td>Long context, cost optimization</td>
					<td><code>claude-3-7-sonnet-latest</code></td>
					<td>200K context, artifacts, citations</td>
			</tr>
			<tr>
					<td><strong>Azure OpenAI</strong></td>
					<td>Enterprise, compliance</td>
					<td><code>gpt-4</code> (deployed model)</td>
					<td>VNET support, SLA, compliance certifications</td>
			</tr>
			<tr>
					<td><strong>Ollama</strong></td>
					<td>Local dev, privacy</td>
					<td><code>llama3.2</code>, <code>mistral</code></td>
					<td>No API costs, runs offline, data stays local</td>
			</tr>
			<tr>
					<td><strong>OpenRouter</strong></td>
					<td>Multi-model access</td>
					<td>Any supported model</td>
					<td>Access 100+ models via one API</td>
			</tr>
	</tbody>
</table>
<p>Same <code>LLMClient</code> interface. Same code. Different configs.</p>
<h3 id="switching-providers-in-config">Switching providers in config</h3>
<pre tabindex="0"><code class="language-hocon" data-lang="hocon"># application.conf

# OpenAI (default)
llm4s.provider = &#34;openai&#34;
llm4s.openai {
  api-key = ${OPENAI_API_KEY}
  model = &#34;gpt-4o&#34;
}

# Want Anthropic instead? Just change the provider
llm4s.provider = &#34;anthropic&#34;
llm4s.anthropic {
  api-key = ${ANTHROPIC_API_KEY}
  model = &#34;claude-3-7-sonnet-latest&#34;
}

# Want Ollama for local dev? Same thing
llm4s.provider = &#34;ollama&#34;
llm4s.ollama {
  model = &#34;llama3.2&#34;
  base-url = &#34;http://localhost:11434&#34;
}</code></pre><p>Your application code stays the same:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// This code works with any provider
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">configResult</span> <span class="k">=</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">Provider</span><span class="o">()</span>
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">completionResult</span> <span class="k">=</span> <span class="n">configResult</span><span class="o">.</span><span class="n">flatMap</span> <span class="o">{</span> <span class="n">config</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">client</span> <span class="k">=</span> <span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">(</span><span class="n">config</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="n">client</span><span class="o">.</span><span class="n">flatMap</span><span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="o">))</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="how-provider-detection-works">How provider detection works</h3>
<p>The <code>LLMConnect</code> factory picks the right client based on config:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// core/src/main/scala/org/llm4s/llmconnect/LLMConnect.scala
</span></span></span><span class="line"><span class="cl"><span class="k">object</span> <span class="nc">LLMConnect</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">client</span><span class="o">(</span><span class="n">config</span><span class="k">:</span> <span class="kt">ProviderConfig</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">LLMClient</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">config</span><span class="o">.</span><span class="n">validate</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">      <span class="n">client</span> <span class="k">&lt;-</span> <span class="n">createClient</span><span class="o">(</span><span class="n">config</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">yield</span> <span class="n">client</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">private</span> <span class="k">def</span> <span class="n">createClient</span><span class="o">(</span><span class="n">config</span><span class="k">:</span> <span class="kt">ProviderConfig</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">LLMClient</span><span class="o">]</span> <span class="k">=</span> <span class="n">config</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="n">c</span><span class="k">:</span> <span class="kt">OpenAIConfig</span> <span class="o">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="k">new</span> <span class="nc">OpenAIClient</span><span class="o">(</span><span class="n">c</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="n">c</span><span class="k">:</span> <span class="kt">AnthropicConfig</span> <span class="o">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="k">new</span> <span class="nc">AnthropicClient</span><span class="o">(</span><span class="n">c</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="n">c</span><span class="k">:</span> <span class="kt">AzureConfig</span> <span class="o">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="k">new</span> <span class="nc">OpenAIClient</span><span class="o">(</span><span class="n">c</span><span class="o">.</span><span class="n">toOpenAIConfig</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="n">c</span><span class="k">:</span> <span class="kt">OllamaConfig</span> <span class="o">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="k">new</span> <span class="nc">OllamaClient</span><span class="o">(</span><span class="n">c</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="n">c</span><span class="k">:</span> <span class="kt">OpenRouterConfig</span> <span class="o">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="k">new</span> <span class="nc">OpenRouterClient</span><span class="o">(</span><span class="n">c</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Provider detection flow:</strong></p>
<pre class="mermaid">flowchart TD
    START[&#34;Application Code&lt;br/&gt;ConfigReader.Provider()&#34;] --&gt; CONFIG[&#34;Read Config&lt;br/&gt;(application.conf, env vars)&#34;]
    CONFIG --&gt; VALIDATE[&#34;Validate Config&lt;br/&gt;(API keys, model names)&#34;]
    VALIDATE --&gt;|Valid| MATCH[&#34;Pattern Match&lt;br/&gt;on Provider Type&#34;]
    VALIDATE --&gt;|Invalid| ERROR1[&#34;Left(ConfigurationError)&#34;]

    MATCH --&gt;|&#34;OpenAIConfig&#34;| OPENAI[&#34;new OpenAIClient(config)&#34;]
    MATCH --&gt;|&#34;AnthropicConfig&#34;| ANTHROPIC[&#34;new AnthropicClient(config)&#34;]
    MATCH --&gt;|&#34;AzureConfig&#34;| AZURE[&#34;new OpenAIClient&lt;br/&gt;(config.toOpenAIConfig)&#34;]
    MATCH --&gt;|&#34;OllamaConfig&#34;| OLLAMA[&#34;new OllamaClient(config)&#34;]
    MATCH --&gt;|&#34;OpenRouterConfig&#34;| OPENROUTER[&#34;new OpenRouterClient(config)&#34;]

    OPENAI --&gt; SUCCESS[&#34;Right(LLMClient)&#34;]
    ANTHROPIC --&gt; SUCCESS
    AZURE --&gt; SUCCESS
    OLLAMA --&gt; SUCCESS
    OPENROUTER --&gt; SUCCESS

    SUCCESS --&gt; COMPLETE[&#34;client.complete(conversation)&#34;]

    style START fill:#e1f5ff,stroke:#0066cc,color:#000
    style MATCH fill:#fff4e1,stroke:#cc8800,color:#000
    style SUCCESS fill:#e1ffe1,stroke:#2d7a2d,color:#000
    style ERROR1 fill:#ffe1e1,stroke:#cc0000,color:#000
</pre><p>The config object knows which provider it represents. The factory creates the right client. Your code never touches provider-specific classes.</p>
<h3 id="real-production-scenario-switching-providers-mid-project">Real production scenario: switching providers mid-project</h3>
<p>One team started with OpenAI GPT-4. Costs got high. They switched to Anthropic Claude for most calls, kept GPT-4 for vision tasks.</p>
<p>Before llm4s: Would&rsquo;ve meant maintaining two separate codepaths. Different error handling. Different message builders. Different streaming handlers.</p>
<p>With llm4s: They created two configs, picked the right one per call. Same code. Zero refactoring.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">val</span> <span class="n">openAIConfig</span> <span class="k">=</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">OpenAI</span><span class="o">()</span>
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">anthropicConfig</span> <span class="k">=</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">Anthropic</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="n">complete</span><span class="o">(</span><span class="n">prompt</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">needsVision</span><span class="k">:</span> <span class="kt">Boolean</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Completion</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">config</span> <span class="k">=</span> <span class="k">if</span> <span class="o">(</span><span class="n">needsVision</span><span class="o">)</span> <span class="n">openAIConfig</span> <span class="k">else</span> <span class="n">anthropicConfig</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Same code path for both
</span></span></span><span class="line"><span class="cl">  <span class="n">config</span><span class="o">.</span><span class="n">flatMap</span> <span class="o">{</span> <span class="n">c</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">(</span><span class="n">c</span><span class="o">).</span><span class="n">flatMap</span><span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Provider abstraction isn&rsquo;t just convenience. It&rsquo;s how you stay flexible in production.</p>
<div class="admonition warning">
  <div class="admonition-title">Cost Control</div>
  <div class="admonition-content">
    Provider switching isn&rsquo;t just about API differences - it&rsquo;s about your AWS bill. One team saved 60% monthly by routing vision tasks to GPT-4o but everything else to Claude Sonnet. Same codebase, two configs, massive savings. Test both providers in dev, measure costs in staging, switch with confidence in prod.
  </div>
</div>
<p><strong>Now we have type safety, error handling, and provider abstraction. What&rsquo;s next?</strong> Building actual LLM applications often means building agents - systems that can reason, use tools, and execute multi-step tasks. That&rsquo;s where the agent framework comes in.</p>
<hr>
<h2 id="part-4---agent-framework-from-prompt-to-autonomous-execution">Part 4 - Agent framework: from prompt to autonomous execution</h2>
<h3 id="why-agents-need-a-framework">Why agents need a framework</h3>
<p>You want to build an agent. It reads a task. It picks tools. It executes them. It interprets results. It loops until done. Simple concept.</p>
<p>Building it yourself? Not simple. You&rsquo;d handle tool calling (every provider does it differently). Parse results (JSON that lies to you). Manage conversation state (growing token counts). Track iterations (because infinite loops are fun to debug at midnight). Handle errors (of which there are many). Decide when to stop (before AWS bills you into bankruptcy).</p>
<p>Or you could use llm4s&rsquo;s agent framework. It handles all of that. Plus the edge cases you haven&rsquo;t thought of yet.</p>
<h3 id="how-the-agent-framework-works">How the agent framework works</h3>
<p>The agent framework gives you:</p>
<ul>
<li><strong>Tool registry</strong>: Register functions, the LLM calls them</li>
<li><strong>Execution loop</strong>: Automatic tool execution with result handling</li>
<li><strong>Conversation management</strong>: Tracks full conversation history</li>
<li><strong>Tracing</strong>: Built-in observability with Langfuse</li>
<li><strong>Safety limits</strong>: Max iterations, timeouts, error handling</li>
</ul>
<p>Basic agent:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.agent._</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.toolapi._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Define a tool
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">weatherTool</span> <span class="k">=</span> <span class="nc">ToolFunction</span><span class="o">[</span><span class="kt">WeatherRequest</span>, <span class="kt">WeatherResponse</span><span class="o">](</span>
</span></span><span class="line"><span class="cl">  <span class="n">name</span> <span class="k">=</span> <span class="s">&#34;get_weather&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">description</span> <span class="k">=</span> <span class="s">&#34;Get current weather for a location&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">execute</span> <span class="k">=</span> <span class="n">req</span> <span class="k">=&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// Call weather API
</span></span></span><span class="line"><span class="cl">    <span class="nc">Right</span><span class="o">(</span><span class="nc">WeatherResponse</span><span class="o">(</span><span class="n">req</span><span class="o">.</span><span class="n">location</span><span class="o">,</span> <span class="mi">72</span><span class="o">,</span> <span class="s">&#34;Sunny&#34;</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Create agent with tool
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">agent</span> <span class="k">=</span> <span class="nc">AgentOrchestrator</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">client</span> <span class="k">=</span> <span class="n">client</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">tools</span> <span class="k">=</span> <span class="nc">Seq</span><span class="o">(</span><span class="n">weatherTool</span><span class="o">),</span>
</span></span><span class="line"><span class="cl">  <span class="n">maxIterations</span> <span class="k">=</span> <span class="mi">5</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Run it
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="n">agent</span><span class="o">.</span><span class="n">run</span><span class="o">(</span><span class="s">&#34;What&#39;s the weather in San Francisco?&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="c1">// Agent will:
</span></span></span><span class="line"><span class="cl"><span class="c1">// 1. Ask LLM to plan
</span></span></span><span class="line"><span class="cl"><span class="c1">// 2. LLM returns tool call: get_weather(location=&#34;San Francisco&#34;)
</span></span></span><span class="line"><span class="cl"><span class="c1">// 3. Execute tool
</span></span></span><span class="line"><span class="cl"><span class="c1">// 4. Send result back to LLM
</span></span></span><span class="line"><span class="cl"><span class="o">//</span> <span class="mf">5.</span> <span class="nc">LLM</span> <span class="n">returns</span> <span class="k">final</span> <span class="n">answer</span><span class="k">:</span> <span class="err">&#34;</span><span class="kt">It</span><span class="err">&#39;</span><span class="kt">s</span> <span class="err">72°</span><span class="kt">F</span> <span class="kt">and</span> <span class="kt">sunny</span> <span class="kt">in</span> <span class="kt">San</span> <span class="kt">Francisco</span><span class="err">&#34;</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Agent state machine:</strong></p>
<pre class="mermaid">stateDiagram-v2
    [*] --&gt; InProgress: initialize(query, tools)

    InProgress --&gt; WaitingForTools: LLM requests tool calls
    InProgress --&gt; Complete: LLM provides final answer

    WaitingForTools --&gt; InProgress: execute tools,&lt;br/&gt;add results to conversation

    Complete --&gt; [*]

    note right of InProgress
        - Send conversation to LLM
        - Parse response
        - Check for tool calls
    end note

    note right of WaitingForTools
        - Execute all tool calls
        - Collect results
        - Add ToolMessages
    end note

    note right of Complete
        - Final answer available
        - conversation.messages has full history
    end note
</pre><p>The agent loops through states until the LLM provides a final answer or max iterations are hit.</p>
<h3 id="tool-calling-format-abstraction">Tool calling format abstraction</h3>
<p>Different providers format tool calls differently.</p>
<p><strong>OpenAI format:</strong></p>
<div class="highlight highlight-json" data-lang="json"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;tool_calls&#34;</span><span class="p">:</span> <span class="p">[{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;call_abc123&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;function&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;function&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;get_weather&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;arguments&#34;</span><span class="p">:</span> <span class="s2">&#34;{\&#34;location\&#34;: \&#34;SF\&#34;}&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">}]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Anthropic format:</strong></p>
<div class="highlight highlight-json" data-lang="json"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;content&#34;</span><span class="p">:</span> <span class="p">[{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;tool_use&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;toolu_abc123&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;get_weather&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;input&#34;</span><span class="p">:</span> <span class="p">{</span><span class="nt">&#34;location&#34;</span><span class="p">:</span> <span class="s2">&#34;SF&#34;</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">}]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>llm4s abstracts this. You work with one format:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">ToolCall</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">id</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">name</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">arguments</span><span class="k">:</span> <span class="kt">ujson.Value</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Tool calling flow across providers:</strong></p>
<pre class="mermaid">sequenceDiagram
    participant App as Your Application
    participant Client as LLMClient
    participant Provider as OpenAI/Anthropic/etc
    participant Tool as Tool Registry

    App-&gt;&gt;Client: complete(conversation, tools)
    Client-&gt;&gt;Provider: Convert tools to provider format
    Provider--&gt;&gt;Client: Response with tool_calls (provider format)
    Client-&gt;&gt;Client: Normalize to ToolCall(id, name, args)
    Client--&gt;&gt;App: AssistantMessage(toolCalls)

    App-&gt;&gt;Tool: Execute each ToolCall
    Tool--&gt;&gt;App: Tool results

    App-&gt;&gt;Client: Add ToolMessage to conversation
    Client-&gt;&gt;Provider: Send conversation + results
    Provider--&gt;&gt;Client: Final response
    Client--&gt;&gt;App: Completion
</pre><p>The provider clients handle conversion. Your agent code stays clean.</p>
<h3 id="real-production-example-code-assistant-agent">Real production example: code assistant agent</h3>
<p>One team built a code review agent. The kind that actually helps instead of just leaving &ldquo;LGTM 👍&rdquo; comments.</p>
<p>It reads a PR. Checks style guidelines. Runs tests. Suggests improvements. Catches the bugs your colleagues are too polite to mention in code review.</p>
<p>Tools they registered:</p>
<ul>
<li><code>read_file(path)</code>: Read file content (because agents can&rsquo;t guess what you wrote)</li>
<li><code>run_tests(suite)</code>: Execute test suite (yes, the ones you skipped locally)</li>
<li><code>check_style(file)</code>: Run linter (finding all those tabs you swore you didn&rsquo;t commit)</li>
<li><code>search_docs(query)</code>: Search internal docs (that nobody reads but everyone should)</li>
</ul>
<p>The agent orchestrates all of this. One prompt: &ldquo;Review PR #123.&rdquo; The agent figures out which files to read, which tests to run, which style rules you violated.</p>
<p>Before the framework: 200 lines of orchestration code. Error-prone. Hard to debug. Gave up after two weeks.</p>
<p>With the framework: 30 lines registering tools. The framework handles the rest. Working in production by Friday.</p>
<h3 id="type-safe-tool-definitions">Type-safe tool definitions</h3>
<p>Here&rsquo;s what makes llm4s tool calling unique: type safety all the way down.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// Define a tool with compile-time type checking
</span></span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">WeatherRequest</span><span class="o">(</span><span class="n">location</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">units</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">String</span><span class="o">])</span>
</span></span><span class="line"><span class="cl"><span class="k">case</span> <span class="k">class</span> <span class="nc">WeatherResponse</span><span class="o">(</span><span class="n">temperature</span><span class="k">:</span> <span class="kt">Double</span><span class="o">,</span> <span class="n">conditions</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">humidity</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">weatherTool</span> <span class="k">=</span> <span class="nc">ToolFunction</span><span class="o">[</span><span class="kt">WeatherRequest</span>, <span class="kt">WeatherResponse</span><span class="o">](</span>
</span></span><span class="line"><span class="cl">  <span class="n">name</span> <span class="k">=</span> <span class="s">&#34;get_weather&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">description</span> <span class="k">=</span> <span class="s">&#34;Get current weather for a location&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">schema</span> <span class="k">=</span> <span class="nc">ObjectSchema</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">description</span> <span class="k">=</span> <span class="s">&#34;Weather query parameters&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">properties</span> <span class="k">=</span> <span class="nc">Seq</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">      <span class="nc">PropertyDefinition</span><span class="o">(</span><span class="s">&#34;location&#34;</span><span class="o">,</span> <span class="nc">StringSchema</span><span class="o">(</span><span class="s">&#34;City name&#34;</span><span class="o">),</span> <span class="n">required</span> <span class="k">=</span> <span class="kc">true</span><span class="o">),</span>
</span></span><span class="line"><span class="cl">      <span class="nc">PropertyDefinition</span><span class="o">(</span><span class="s">&#34;units&#34;</span><span class="o">,</span> <span class="nc">StringSchema</span><span class="o">(</span><span class="s">&#34;Temperature units&#34;</span><span class="o">),</span> <span class="n">required</span> <span class="k">=</span> <span class="kc">false</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">),</span>
</span></span><span class="line"><span class="cl">  <span class="n">handler</span> <span class="k">=</span> <span class="o">{</span> <span class="n">extractor</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="n">location</span> <span class="k">&lt;-</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getString</span><span class="o">(</span><span class="s">&#34;location&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">      <span class="n">units</span> <span class="k">=</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getString</span><span class="o">(</span><span class="s">&#34;units&#34;</span><span class="o">).</span><span class="n">getOrElse</span><span class="o">(</span><span class="s">&#34;celsius&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">      <span class="n">response</span> <span class="k">&lt;-</span> <span class="n">callWeatherAPI</span><span class="o">(</span><span class="n">location</span><span class="o">,</span> <span class="n">units</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">yield</span> <span class="n">response</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><p>The <code>ToolFunction[WeatherRequest, WeatherResponse]</code> signature tells you:</p>
<ul>
<li>Input type: <code>WeatherRequest</code></li>
<li>Output type: <code>WeatherResponse</code></li>
<li>The compiler validates both</li>
</ul>
<p>Python&rsquo;s tool calling? Dictionaries and runtime validation. Hope you got the types right.</p>
<p>Scala&rsquo;s tool calling? <code>ToolFunction[T, R]</code> with compile-time guarantees. Invalid tool definitions don&rsquo;t compile.</p>
<h3 id="safeparameterextractor-type-safe-argument-parsing">SafeParameterExtractor: type-safe argument parsing</h3>
<p>The <code>SafeParameterExtractor</code> provides safe access to tool arguments:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="n">handler</span> <span class="k">=</span> <span class="o">{</span> <span class="n">extractor</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">location</span> <span class="k">&lt;-</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getString</span><span class="o">(</span><span class="s">&#34;location&#34;</span><span class="o">)</span>     <span class="c1">// Either[String, String]
</span></span></span><span class="line"><span class="cl">    <span class="n">lat</span> <span class="k">&lt;-</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getDouble</span><span class="o">(</span><span class="s">&#34;latitude&#34;</span><span class="o">)</span>          <span class="c1">// Either[String, Double]
</span></span></span><span class="line"><span class="cl">    <span class="n">temp</span> <span class="k">&lt;-</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getInt</span><span class="o">(</span><span class="s">&#34;temperature&#34;</span><span class="o">)</span>         <span class="c1">// Either[String, Int]
</span></span></span><span class="line"><span class="cl">    <span class="n">enabled</span> <span class="k">&lt;-</span> <span class="n">extractor</span><span class="o">.</span><span class="n">getBoolean</span><span class="o">(</span><span class="s">&#34;enabled&#34;</span><span class="o">)</span>      <span class="c1">// Either[String, Boolean]
</span></span></span><span class="line"><span class="cl">  <span class="o">}</span> <span class="k">yield</span> <span class="nc">WeatherData</span><span class="o">(</span><span class="n">location</span><span class="o">,</span> <span class="n">lat</span><span class="o">,</span> <span class="n">temp</span><span class="o">,</span> <span class="n">enabled</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>If the LLM sends the wrong type - say, a string instead of an integer - you get a clear error message: &ldquo;Expected integer for field &rsquo;temperature&rsquo;, got string &rsquo;twenty&rsquo;.&rdquo;</p>
<p>No runtime crashes. No <code>TypeError</code> exceptions. Clean error handling with <code>Either</code>.</p>
<hr>
<h2 id="part-5---context-management-staying-under-token-limits-automatically">Part 5 - Context management: staying under token limits automatically</h2>
<h3 id="why-context-management-is-hard">Why context management is hard</h3>
<p>You&rsquo;re building a chatbot. Conversation gets long. You hit the token limit. The API rejects your request. You see: &ldquo;This model&rsquo;s maximum context length is 8192 tokens.&rdquo;</p>
<p>Now what? You can&rsquo;t just drop messages. You need system prompts. You need recent history. You need tool results.</p>
<p>You need a strategy.</p>
<h3 id="how-llm4s-manages-context">How llm4s manages context</h3>
<p>llm4s has a four-stage compression pipeline. It tries deterministic compression first. If that&rsquo;s not enough, it moves to smarter techniques.</p>
<pre class="mermaid">flowchart TD
    START[&#34;Incoming Conversation&#34;] --&gt; CHECK{&#34;Token count&lt;br/&gt;&gt; limit?&#34;}

    CHECK --&gt;|No| SEND[&#34;Send to LLM&#34;]
    CHECK --&gt;|Yes| COMPRESS[&#34;Start Compression&#34;]

    COMPRESS --&gt; STEP1[&#34;Step 1:&lt;br/&gt;Deterministic Compression&lt;br/&gt;(whitespace, JSON)&#34;]
    STEP1 --&gt; CHECK1{&#34;Still over&lt;br/&gt;limit?&#34;}

    CHECK1 --&gt;|No| SEND
    CHECK1 --&gt;|Yes| STEP2[&#34;Step 2:&lt;br/&gt;Tool Output Compression&lt;br/&gt;(truncate, extract)&#34;]

    STEP2 --&gt; CHECK2{&#34;Still over&lt;br/&gt;limit?&#34;}
    CHECK2 --&gt;|No| SEND
    CHECK2 --&gt;|Yes| STEP3[&#34;Step 3:&lt;br/&gt;History Summarization&lt;br/&gt;(keep system, recent)&#34;]

    STEP3 --&gt; CHECK3{&#34;Still over&lt;br/&gt;limit?&#34;}
    CHECK3 --&gt;|No| SEND
    CHECK3 --&gt;|Yes| STEP4[&#34;Step 4:&lt;br/&gt;LLM-based Compression&lt;br/&gt;(expensive but smart)&#34;]

    STEP4 --&gt; SEND
    SEND --&gt; RESULT[&#34;Completion&#34;]

    style START fill:#e1f5ff,stroke:#0066cc,color:#000
    style COMPRESS fill:#fff4e1,stroke:#cc8800,color:#000
    style STEP1 fill:#e1ffe1,stroke:#2d7a2d,color:#000
    style STEP2 fill:#e1ffe1,stroke:#2d7a2d,color:#000
    style STEP3 fill:#ffe1e1,stroke:#cc0000,color:#000
    style STEP4 fill:#ffe1e1,stroke:#cc0000,color:#000
    style SEND fill:#f0e1ff,stroke:#8800cc,color:#000
    style RESULT fill:#e1f5ff,stroke:#0066cc,color:#000
</pre><p><strong>Step 1: Deterministic compression</strong></p>
<p>Remove whitespace. Compress JSON. Deduplicate repeated content. Fast. No quality loss for structured data.</p>
<p><strong>Step 2: Tool output compression</strong></p>
<p>Tool results can be huge. A file read returns 10,000 lines. You only need the summary. Extract relevant parts. Truncate the rest.</p>
<p><strong>Step 3: History summarization</strong></p>
<p>Keep system prompt. Keep recent messages. Summarize middle history. &ldquo;User asked about weather. Assistant provided forecast.&rdquo;</p>
<p><strong>Step 4: LLM-based compression</strong></p>
<p>Last resort. Ask the LLM: &ldquo;Summarize this conversation while preserving key context.&rdquo; More expensive. Higher quality.</p>
<h3 id="automatic-or-manual">Automatic or manual</h3>
<p>By default, it&rsquo;s automatic. The agent framework applies compression when needed.</p>
<p>Want manual control?</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">val</span> <span class="n">compressor</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">ContextCompressor</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">strategy</span> <span class="k">=</span> <span class="nc">CompressionStrategy</span><span class="o">.</span><span class="nc">Staged</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">tokenLimit</span> <span class="k">=</span> <span class="mi">8000</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">preserveSystem</span> <span class="k">=</span> <span class="kc">true</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">preserveRecent</span> <span class="k">=</span> <span class="mi">5</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">compressed</span> <span class="k">=</span> <span class="n">compressor</span><span class="o">.</span><span class="n">compress</span><span class="o">(</span><span class="n">conversation</span><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="real-production-scenario-long-running-customer-support-agent">Real production scenario: long-running customer support agent</h3>
<p>One team built a support agent. Think of it as their first line of defense before escalating to humans (who cost money).</p>
<p>Average conversation: 20 turns. Some customers got chatty: 50+ turns. Token limit: 8K. Math didn&rsquo;t math.</p>
<p>Without compression: Every conversation hit the limit around turn 12. They&rsquo;d manually drop old messages. The agent would forget what the customer said 10 minutes ago. Quality went downhill. Customers got frustrated. Defeats the whole purpose.</p>
<p>With compression: The four-stage pipeline kicked in automatically. Kept conversations under 8K. Preserved system instructions (the agent&rsquo;s personality). Kept recent exchanges (what the customer just said). Summarized ancient history (they had a billing question 30 minutes ago). Quality stayed consistent through turn 50.</p>
<p>The agent handled 10x more turns per conversation. Customer sat scores went up. Finance was happy. Engineering was happy. Rare win.</p>
<hr>
<h2 id="part-9---secure-execution-docker-based-workspace-for-safe-tool-running">Part 9 - Secure execution: Docker-based workspace for safe tool running</h2>
<h3 id="why-tool-execution-needs-isolation">Why tool execution needs isolation</h3>
<p>You&rsquo;re building an agent that can run code. Execute shell commands. Modify files. Super useful. Also super dangerous.</p>
<p>Here&rsquo;s a fun thought experiment: What if the LLM hallucinates a <code>rm -rf /</code> command? Or decides to <code>cat /etc/passwd</code> for &ldquo;debugging purposes&rdquo;? Or opens network connections to mysterious servers you didn&rsquo;t authorize?</p>
<p>LLMs are powerful. They&rsquo;re also unpredictable. Giving them direct access to your file system is like handing your car keys to a very smart toddler. Sure, they might park it correctly. Or they might drive through your garage wall.</p>
<p>You need isolation. You need sandboxing. You need Docker.</p>
<h3 id="how-llm4s-handles-secure-execution">How llm4s handles secure execution</h3>
<p>llm4s provides a Docker-based workspace for tool execution. Tools run in isolated containers. They can&rsquo;t access your host filesystem. They can&rsquo;t make unauthorized network calls. They can&rsquo;t damage your system.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="c1">// Configure workspace
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">workspaceSettings</span> <span class="k">=</span> <span class="nc">WorkspaceSettings</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">workspaceDir</span> <span class="k">=</span> <span class="s">&#34;/tmp/llm4s-workspace&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">imageName</span> <span class="k">=</span> <span class="s">&#34;llm4s-runner:latest&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">hostPort</span> <span class="k">=</span> <span class="mi">8080</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">traceLogPath</span> <span class="k">=</span> <span class="s">&#34;/tmp/traces&#34;</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Run tool in isolated container
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="n">workspaceClient</span><span class="o">.</span><span class="n">execute</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">tool</span> <span class="k">=</span> <span class="s">&#34;run_python_script&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">args</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">(</span><span class="s">&#34;script&#34;</span> <span class="o">-&gt;</span> <span class="s">&#34;print(&#39;Hello from container&#39;)&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">//</span> <span class="nc">Script</span> <span class="n">runs</span> <span class="n">in</span> <span class="nc">Docker</span><span class="o">,</span> <span class="n">isolated</span> <span class="n">from</span> <span class="n">host</span></span></span></code></pre></td></tr></table>
</div>
</div><p>The workspace runner handles:</p>
<ul>
<li>Container lifecycle management</li>
<li>File system isolation</li>
<li>Network restrictions</li>
<li>Resource limits (CPU, memory)</li>
<li>Automatic cleanup</li>
</ul>
<h3 id="real-production-benefit-1">Real production benefit</h3>
<p>One team built a code assistant. The kind that can actually run the code you&rsquo;re asking about. Great feature. Terrible security implications.</p>
<p>It needed to run user-submitted code. Without isolation, they&rsquo;d be executing random Python scripts directly on their production servers. That&rsquo;s not a security model, that&rsquo;s a suicide pact.</p>
<p>With llm4s workspace: User code runs in Docker. Container jail. Can&rsquo;t escape. Can&rsquo;t access host resources. Can&rsquo;t read your database credentials. Can&rsquo;t install Bitcoin miners. Can&rsquo;t do anything except what it&rsquo;s supposed to do.</p>
<p>Safe execution. Useful features. Sleep-at-night security. The holy trinity.</p>
<div class="admonition danger">
  <div class="admonition-title">Security Critical</div>
  <div class="admonition-content">
    Never run LLM-generated code directly on your production servers. The workspace Docker isolation isn&rsquo;t optional - it&rsquo;s your firewall against hallucinated rm -rf commands, unauthorized network calls, and credential scraping attempts. If you skip Docker for &ldquo;convenience,&rdquo; you&rsquo;re one bad prompt away from a very bad day.
  </div>
</div>
<h3 id="mcp-model-context-protocol-support">MCP (Model Context Protocol) support</h3>
<p>llm4s supports MCP - the Model Context Protocol. This is cutting-edge. Most frameworks don&rsquo;t have this yet.</p>
<p>MCP provides a standard way to manage context across LLM calls. Share context between tools. Maintain state across agent runs. Coordinate multi-agent systems.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.mcp._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Create MCP-compatible context
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">mcpContext</span> <span class="k">=</span> <span class="nc">MCPContext</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">contextId</span> <span class="k">=</span> <span class="s">&#34;session-123&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="n">sharedState</span> <span class="k">=</span> <span class="nc">Map</span><span class="o">(</span><span class="s">&#34;user_preferences&#34;</span> <span class="o">-&gt;</span> <span class="n">userPrefs</span><span class="o">),</span>
</span></span><span class="line"><span class="cl">  <span class="n">tools</span> <span class="k">=</span> <span class="n">registeredTools</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Agent uses MCP context
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">agent</span> <span class="k">=</span> <span class="nc">Agent</span><span class="o">(</span><span class="n">client</span><span class="o">,</span> <span class="n">mcpContext</span><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><p>As MCP adoption grows, llm4s is already compatible. Your code won&rsquo;t need changes.</p>
<hr>
<h2 id="part-6---tracing-and-observability-know-what-your-llm-is-doing">Part 6 - Tracing and observability: know what your LLM is doing</h2>
<h3 id="why-tracing-matters">Why tracing matters</h3>
<p>Your LLM app is slow. Users complain. You check logs. You see: &ldquo;Completed in 8 seconds.&rdquo;</p>
<p>Why 8 seconds? Was it the LLM? Network? Tool execution? Token generation?</p>
<p>You don&rsquo;t know. You need tracing.</p>
<h3 id="how-llm4s-tracing-works">How llm4s tracing works</h3>
<p>llm4s integrates with Langfuse. Every LLM call, tool execution, and agent step gets traced. You see:</p>
<ul>
<li>Request/response content</li>
<li>Token usage (prompt, completion, total)</li>
<li>Latency breakdown</li>
<li>Error details</li>
<li>Cost estimation</li>
</ul>
<p>Enable tracing in config:</p>
<pre tabindex="0"><code class="language-hocon" data-lang="hocon">llm4s.tracing {
  enabled = true
  langfuse {
    public-key = ${LANGFUSE_PUBLIC_KEY}
    secret-key = ${LANGFUSE_SECRET_KEY}
    host = &#34;https://cloud.langfuse.com&#34;
  }
}</code></pre><p>Add tracing to your code:</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.trace._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">tracer</span> <span class="k">=</span> <span class="nc">EnhancedTracing</span><span class="o">.</span><span class="n">fromConfig</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// Start trace
</span></span></span><span class="line"><span class="cl">  <span class="n">traceId</span> <span class="k">&lt;-</span> <span class="n">tracer</span><span class="o">.</span><span class="n">startTrace</span><span class="o">(</span><span class="s">&#34;customer-support-agent&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Trace LLM call
</span></span></span><span class="line"><span class="cl">  <span class="n">completion</span> <span class="k">&lt;-</span> <span class="n">tracer</span><span class="o">.</span><span class="n">traced</span><span class="o">(</span><span class="s">&#34;llm-completion&#34;</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">client</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="n">conversation</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Trace tool execution
</span></span></span><span class="line"><span class="cl">  <span class="n">toolResult</span> <span class="k">&lt;-</span> <span class="n">tracer</span><span class="o">.</span><span class="n">traced</span><span class="o">(</span><span class="s">&#34;tool-execution&#34;</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">executeTool</span><span class="o">(</span><span class="n">completion</span><span class="o">.</span><span class="n">message</span><span class="o">.</span><span class="n">toolCalls</span><span class="o">.</span><span class="n">head</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// End trace
</span></span></span><span class="line"><span class="cl">  <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">tracer</span><span class="o">.</span><span class="n">endTrace</span><span class="o">(</span><span class="n">traceId</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span> <span class="k">yield</span> <span class="n">completion</span></span></span></code></pre></td></tr></table>
</div>
</div><h3 id="what-you-see-in-langfuse">What you see in Langfuse</h3>
<p><strong>Trace view:</strong></p>
<div class="highlight highlight-text" data-lang="text"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">customer-support-agent (8.2s total)
</span></span><span class="line"><span class="cl">├─ llm-completion (6.1s)
</span></span><span class="line"><span class="cl">│  ├─ prompt_tokens: 1234
</span></span><span class="line"><span class="cl">│  ├─ completion_tokens: 456
</span></span><span class="line"><span class="cl">│  ├─ total_tokens: 1690
</span></span><span class="line"><span class="cl">│  └─ cost: $0.042
</span></span><span class="line"><span class="cl">├─ tool-execution (2.0s)
</span></span><span class="line"><span class="cl">│  ├─ tool: search_docs
</span></span><span class="line"><span class="cl">│  └─ result: [3 documents found]
</span></span><span class="line"><span class="cl">└─ llm-completion (0.1s)
</span></span><span class="line"><span class="cl">   ├─ prompt_tokens: 234
</span></span><span class="line"><span class="cl">   ├─ completion_tokens: 89
</span></span><span class="line"><span class="cl">   └─ cost: $0.008</span></span></code></pre></td></tr></table>
</div>
</div><p>Now you know: 6.1 seconds in LLM. 2 seconds in tool execution. Fix the slow tool.</p>
<h3 id="real-production-benefit-2">Real production benefit</h3>
<p>One team&rsquo;s agent was slow. Users complained. They added tracing. Found that 80% of time was spent in <code>read_file</code> tool. The tool read entire files, even when only a few lines were needed.</p>
<p>Fix: Add a <code>read_file_lines(path, start, end)</code> tool. Read only what you need.</p>
<p>Result: Average response time dropped from 8s to 2s. Users happy.</p>
<p>Tracing showed them the problem. They fixed the root cause.</p>
<hr>
<h2 id="part-7---getting-started-template-to-production-in-minutes">Part 7 - Getting started: template to production in minutes</h2>
<h3 id="the-giter8-template">The Giter8 template</h3>
<p>New contributors to llm4s had a problem. They&rsquo;d read docs. Copy example code. Manually create files. Twenty minutes later, they&rsquo;d have a basic setup with typos in package names.</p>
<p>We fixed it with a Giter8 template.</p>
<div class="highlight highlight-bash" data-lang="bash"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">$ sbt new llm4s/llm4s.g8
</span></span><span class="line"><span class="cl">name <span class="o">[</span>My LLM App<span class="o">]</span>: chatbot
</span></span><span class="line"><span class="cl">scala_version <span class="o">[</span>3.3.0<span class="o">]</span>:
</span></span><span class="line"><span class="cl">provider <span class="o">[</span>openai<span class="o">]</span>: anthropic
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">$ <span class="nb">cd</span> chatbot
</span></span><span class="line"><span class="cl">$ sbt run
</span></span><span class="line"><span class="cl"><span class="o">[</span>info<span class="o">]</span> Running Main
</span></span><span class="line"><span class="cl">Response: Hello! How can I <span class="nb">help</span> you today?</span></span></code></pre></td></tr></table>
</div>
</div><p>Sixty seconds. Zero typos. Working app.</p>
<h3 id="what-you-get">What you get</h3>
<p>The template generates:</p>
<ul>
<li><strong>Working code</strong>: Not TODOs. Actual functioning LLM calls.</li>
<li><strong>Build config</strong>: SBT with correct dependencies.</li>
<li><strong>Formatting</strong>: scalafmt configuration.</li>
<li><strong>CI</strong>: GitHub Actions workflow.</li>
<li><strong>Tests</strong>: Basic test structure with ScalaTest.</li>
<li><strong>README</strong>: Instructions specific to your chosen provider.</li>
</ul>
<h3 id="the-killer-feature-it-actually-runs">The killer feature: it actually runs</h3>
<p>Most templates generate scaffolding. You still have to implement everything. Useless.</p>
<p>llm4s template generates working code. Run <code>sbt run</code> immediately after generation. It calls the LLM. Prints the response. No blanks to fill in.</p>
<p>You start with working code. You modify it. You never start from zero.</p>
<h3 id="real-production-example-gsoc-contributors">Real production example: GSoC contributors</h3>
<p>llm4s had 4 GSoC contributors. All used the template. All were productive on day one.</p>
<p>Before template: Average time to first contribution was 3 days. Setup problems. Dependency issues. Configuration mistakes.</p>
<p>After template: First contribution &lt; 1 day. Setup takes 60 seconds. They jump straight to actual work.</p>
<p>Developer experience matters. The template makes it painless.</p>
<h3 id="what-makes-the-template-special">What makes the template special</h3>
<p>Unlike most templates that generate TODO comments, llm4s.g8 generates <em>working code</em>:</p>
<ul>
<li><strong>Complete build setup</strong>: SBT with correct dependencies, cross-compilation support</li>
<li><strong>CI/CD ready</strong>: GitHub Actions workflow pre-configured</li>
<li><strong>Code quality</strong>: Scalafmt, pre-commit hooks, scalafix rules</li>
<li><strong>Testing</strong>: MUnit setup with example tests</li>
<li><strong>Documentation</strong>: Generated README with your project specifics</li>
</ul>
<p>And it&rsquo;s parameterized. Pick your Scala version (2.13 or 3.x). Pick your llm4s version. Pick your provider. The template adapts.</p>
<div class="highlight highlight-bash" data-lang="bash"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">sbt new llm4s/llm4s.g8 <span class="se">\
</span></span></span><span class="line"><span class="cl">  --name<span class="o">=</span>my-agent <span class="se">\
</span></span></span><span class="line"><span class="cl">  --scala_version<span class="o">=</span>3.7.1 <span class="se">\
</span></span></span><span class="line"><span class="cl">  --llm4s_version<span class="o">=</span>0.9.0</span></span></code></pre></td></tr></table>
</div>
</div><p>Generates a project configured exactly as specified. No manual edits. No version conflicts. It just works.</p>
<hr>
<h2 id="part-8---production-patterns-from-the-trenches">Part 8 - Production patterns from the trenches</h2>
<p>These patterns emerged from real llm4s development - error handling PRs, developer tooling improvements, safety refactors. If you want the full story of how we discovered and refined these patterns through code reviews and production use, check out the <a href="/2025/10/five-production-patterns-from-building-llm4s-what-actually-works-in-prod-today/">production patterns article</a>
 in this series.</p>
<h3 id="pattern-1-smart-constructors-prevent-invalid-states">Pattern 1: Smart constructors prevent invalid states</h3>
<p>Don&rsquo;t expose case class constructors. Make them private. Provide an <code>apply</code> method with validation.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">final</span> <span class="k">class</span> <span class="nc">RateLimitError</span> <span class="k">private</span> <span class="o">(</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">provider</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">retryAfter</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">FiniteDuration</span><span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">object</span> <span class="nc">RateLimitError</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">apply</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">provider</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">retryAfter</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">FiniteDuration</span><span class="o">]</span> <span class="k">=</span> <span class="nc">None</span>
</span></span><span class="line"><span class="cl">  <span class="o">)</span><span class="k">:</span> <span class="kt">RateLimitError</span> <span class="o">=</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">require</span><span class="o">(</span><span class="n">message</span><span class="o">.</span><span class="n">nonEmpty</span><span class="o">,</span> <span class="s">&#34;Error message cannot be empty&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">require</span><span class="o">(</span><span class="n">provider</span><span class="o">.</span><span class="n">nonEmpty</span><span class="o">,</span> <span class="s">&#34;Provider name cannot be empty&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">retryAfter</span><span class="o">.</span><span class="n">foreach</span> <span class="o">{</span> <span class="n">duration</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="n">require</span><span class="o">(</span><span class="n">duration</span> <span class="o">&gt;</span> <span class="nc">Duration</span><span class="o">.</span><span class="nc">Zero</span><span class="o">,</span> <span class="s">s&#34;Retry duration must be positive, got: </span><span class="si">$duration</span><span class="s">&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">new</span> <span class="nc">RateLimitError</span><span class="o">(</span><span class="n">message</span><span class="o">,</span> <span class="n">provider</span><span class="o">,</span> <span class="n">retryAfter</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Now you can&rsquo;t create invalid errors. The constructor validates everything.</p>
<h3 id="pattern-2-bridge-methods-for-migrations">Pattern 2: Bridge methods for migrations</h3>
<p>Breaking changes kill adoption. Use bridge methods with deprecation warnings.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">object</span> <span class="nc">Message</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// New API (preferred)
</span></span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">role</span><span class="k">:</span> <span class="kt">MessageRole</span><span class="o">,</span> <span class="n">content</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Message</span> <span class="o">=</span>
</span></span><span class="line"><span class="cl">    <span class="k">new</span> <span class="nc">Message</span><span class="o">(</span><span class="n">role</span><span class="o">,</span> <span class="n">content</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Bridge method (backward compatible)
</span></span></span><span class="line"><span class="cl">  <span class="nd">@deprecated</span><span class="o">(</span><span class="s">&#34;Use MessageRole enum instead of strings&#34;</span><span class="o">,</span> <span class="s">&#34;0.8.0&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">role</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">content</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Message</span> <span class="o">=</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">val</span> <span class="n">roleEnum</span> <span class="k">=</span> <span class="n">role</span><span class="o">.</span><span class="n">toLowerCase</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="s">&#34;user&#34;</span> <span class="k">=&gt;</span> <span class="nc">MessageRole</span><span class="o">.</span><span class="nc">User</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="s">&#34;assistant&#34;</span> <span class="k">=&gt;</span> <span class="nc">MessageRole</span><span class="o">.</span><span class="nc">Assistant</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="s">&#34;system&#34;</span> <span class="k">=&gt;</span> <span class="nc">MessageRole</span><span class="o">.</span><span class="nc">System</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="n">other</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">        <span class="n">println</span><span class="o">(</span><span class="s">s&#34;[DEPRECATED] Unknown role &#39;</span><span class="si">$other</span><span class="s">&#39;, defaulting to User&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">        <span class="nc">MessageRole</span><span class="o">.</span><span class="nc">User</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">new</span> <span class="nc">Message</span><span class="o">(</span><span class="n">roleEnum</span><span class="o">,</span> <span class="n">content</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Users get warnings. They migrate at their own pace. You remove the bridge method after 6 months. Everyone stays happy.</p>
<h3 id="pattern-3-safety-utilities-eliminate-try-catch-blocks">Pattern 3: Safety utilities eliminate try-catch blocks</h3>
<p>Abstract error handling. Use implicit error mappers.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">object</span> <span class="nc">Safety</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">safely</span><span class="o">[</span><span class="kt">A</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="n">A</span><span class="o">)(</span><span class="k">implicit</span> <span class="n">mapper</span><span class="k">:</span> <span class="kt">ErrorMapper</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">A</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">    <span class="nc">Try</span><span class="o">(</span><span class="n">f</span><span class="o">)</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="nc">Success</span><span class="o">(</span><span class="n">value</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nc">Right</span><span class="o">(</span><span class="n">value</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">      <span class="k">case</span> <span class="nc">Failure</span><span class="o">(</span><span class="n">ex</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="nc">Left</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="n">mapError</span><span class="o">(</span><span class="n">ex</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Use it
</span></span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="n">parseResponse</span><span class="o">(</span><span class="n">json</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Response</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">  <span class="nc">Safety</span><span class="o">.</span><span class="n">safely</span><span class="o">(</span><span class="n">ujson</span><span class="o">.</span><span class="n">read</span><span class="o">(</span><span class="n">json</span><span class="o">))</span></span></span></code></pre></td></tr></table>
</div>
</div><p>No more try-catch. No more manual error conversion. One pattern. Applied everywhere.</p>
<h3 id="pattern-4-resource-management-with-use">Pattern 4: Resource management with .use</h3>
<p>Resources need cleanup. Files need closing. HTTP clients need shutdown.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">implicit</span> <span class="k">class</span> <span class="nc">UsingOps</span><span class="o">[</span><span class="kt">A</span> <span class="k">&lt;:</span> <span class="kt">AutoCloseable</span><span class="o">](</span><span class="n">resource</span><span class="k">:</span> <span class="kt">A</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">use</span><span class="o">[</span><span class="kt">B</span><span class="o">](</span><span class="n">f</span><span class="k">:</span> <span class="kt">A</span> <span class="o">=&gt;</span> <span class="n">B</span><span class="o">)(</span><span class="k">implicit</span> <span class="n">mapper</span><span class="k">:</span> <span class="kt">ErrorMapper</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">B</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">    <span class="nc">Safety</span><span class="o">.</span><span class="n">safely</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">f</span><span class="o">(</span><span class="n">resource</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">      <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">resource</span><span class="o">.</span><span class="n">close</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">      <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Use it
</span></span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="n">readConfig</span><span class="o">(</span><span class="n">path</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">Config</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">  <span class="k">new</span> <span class="nc">FileInputStream</span><span class="o">(</span><span class="n">path</span><span class="o">).</span><span class="n">use</span> <span class="o">{</span> <span class="n">stream</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="n">parseConfig</span><span class="o">(</span><span class="n">stream</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>  <span class="o">//</span> <span class="nc">Stream</span> <span class="n">auto</span><span class="o">-</span><span class="n">closes</span><span class="o">,</span> <span class="n">even</span> <span class="k">if</span> <span class="n">parseConfig</span> <span class="n">throws</span></span></span></code></pre></td></tr></table>
</div>
</div><p>No more resource leaks. No more try-finally boilerplate.</p>
<h3 id="pattern-5-error-accumulation-with-validatednec">Pattern 5: Error accumulation with ValidatedNec</h3>
<p>Sometimes you want all errors, not just the first one.</p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">val</span> <span class="n">configs</span> <span class="k">=</span> <span class="nc">List</span><span class="o">(</span><span class="n">openAIConfig</span><span class="o">,</span> <span class="n">anthropicConfig</span><span class="o">,</span> <span class="n">cohereConfig</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">results</span> <span class="k">=</span> <span class="n">configs</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">validateConfig</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nc">Safety</span><span class="o">.</span><span class="n">sequenceV</span><span class="o">(</span><span class="n">results</span><span class="o">)</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Valid</span><span class="o">(</span><span class="n">validConfigs</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="c1">// All valid
</span></span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="nc">Invalid</span><span class="o">(</span><span class="n">errors</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// All errors at once:
</span></span></span><span class="line"><span class="cl">    <span class="c1">// - OpenAI API key is missing
</span></span></span><span class="line"><span class="cl">    <span class="c1">// - Anthropic model is invalid
</span></span></span><span class="line"><span class="cl">    <span class="c1">// - Cohere endpoint is unreachable
</span></span></span><span class="line"><span class="cl">    <span class="n">errors</span><span class="o">.</span><span class="n">toList</span><span class="o">.</span><span class="n">foreach</span><span class="o">(</span><span class="n">e</span> <span class="k">=&gt;</span> <span class="n">println</span><span class="o">(</span><span class="s">s&#34;  - </span><span class="si">${</span><span class="n">e</span><span class="o">.</span><span class="n">formatted</span><span class="si">}</span><span class="s">&#34;</span><span class="o">))</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Users see all problems immediately. Fix them all at once. No repeated round-trips.</p>
<hr>
<h2 id="jvm-ecosystem-integration-the-enterprise-advantage">JVM ecosystem integration: the enterprise advantage</h2>
<h3 id="why-jvm-matters-for-llm-applications">Why JVM matters for LLM applications</h3>
<p>You&rsquo;re building an LLM feature for an enterprise app. Your company runs on the JVM. Kafka for messaging. Spark for data processing. Akka for actor systems. Spring for web services. Cassandra for databases.</p>
<p>Python LLM frameworks? They don&rsquo;t integrate cleanly. You need REST APIs. Message queues. Serialization overhead. Network hops. Complexity.</p>
<p>Scala LLM frameworks? They&rsquo;re native. Same JVM. Same memory space. Direct method calls. Zero serialization. Clean integration.</p>
<h3 id="real-integration-examples">Real integration examples</h3>
<p><strong>Kafka integration:</strong></p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.apache.kafka.clients.consumer.KafkaConsumer</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Process messages from Kafka with LLM
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">consumer</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">KafkaConsumer</span><span class="o">[</span><span class="kt">String</span>, <span class="kt">String</span><span class="o">](</span><span class="n">kafkaConfig</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="n">consumer</span><span class="o">.</span><span class="n">subscribe</span><span class="o">(</span><span class="nc">List</span><span class="o">(</span><span class="s">&#34;user-queries&#34;</span><span class="o">).</span><span class="n">asJava</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">consumer</span><span class="o">.</span><span class="n">poll</span><span class="o">(</span><span class="nc">Duration</span><span class="o">.</span><span class="n">ofSeconds</span><span class="o">(</span><span class="mi">1</span><span class="o">)).</span><span class="n">forEach</span> <span class="o">{</span> <span class="n">record</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">query</span> <span class="k">=</span> <span class="n">record</span><span class="o">.</span><span class="n">value</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Call LLM directly, no network overhead
</span></span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">config</span> <span class="k">&lt;-</span> <span class="nc">ConfigReader</span><span class="o">.</span><span class="nc">Provider</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">client</span> <span class="k">&lt;-</span> <span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">(</span><span class="n">config</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">completion</span> <span class="k">&lt;-</span> <span class="n">client</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="nc">Conversation</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span><span class="nc">UserMessage</span><span class="o">(</span><span class="n">query</span><span class="o">))))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span> <span class="k">yield</span> <span class="n">completion</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="n">result</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">producer</span><span class="o">.</span><span class="n">send</span><span class="o">(</span><span class="s">&#34;llm-responses&#34;</span><span class="o">,</span> <span class="n">completion</span><span class="o">.</span><span class="n">message</span><span class="o">.</span><span class="n">content</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="o">(</span><span class="s">s&#34;LLM error: </span><span class="si">${</span><span class="n">error</span><span class="o">.</span><span class="n">formatted</span><span class="si">}</span><span class="s">&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span></span></span></code></pre></td></tr></table>
</div>
</div><p>No REST API. No serialization. Direct function calls. Native integration.</p>
<p><strong>Spark integration:</strong></p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.apache.spark.sql.SparkSession</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Process millions of records with LLM
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">spark</span> <span class="k">=</span> <span class="nc">SparkSession</span><span class="o">.</span><span class="n">builder</span><span class="o">().</span><span class="n">getOrCreate</span><span class="o">()</span>
</span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">df</span> <span class="k">=</span> <span class="n">spark</span><span class="o">.</span><span class="n">read</span><span class="o">.</span><span class="n">parquet</span><span class="o">(</span><span class="s">&#34;s3://data/user-feedback&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Broadcast LLM client to all workers
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">clientBc</span> <span class="k">=</span> <span class="n">spark</span><span class="o">.</span><span class="n">sparkContext</span><span class="o">.</span><span class="n">broadcast</span><span class="o">(</span><span class="n">client</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">df</span><span class="o">.</span><span class="n">rdd</span><span class="o">.</span><span class="n">mapPartitions</span> <span class="o">{</span> <span class="n">partition</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">val</span> <span class="n">localClient</span> <span class="k">=</span> <span class="n">clientBc</span><span class="o">.</span><span class="n">value</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="n">partition</span><span class="o">.</span><span class="n">map</span> <span class="o">{</span> <span class="n">row</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="k">val</span> <span class="n">feedback</span> <span class="k">=</span> <span class="n">row</span><span class="o">.</span><span class="n">getString</span><span class="o">(</span><span class="mi">0</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// Each worker processes rows with LLM
</span></span></span><span class="line"><span class="cl">    <span class="n">localClient</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="nc">Conversation</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span><span class="nc">UserMessage</span><span class="o">(</span><span class="s">s&#34;Analyze sentiment: </span><span class="si">$feedback</span><span class="s">&#34;</span><span class="o">))))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}.</span><span class="n">collect</span><span class="o">()</span></span></span></code></pre></td></tr></table>
</div>
</div><p>The LLM client serializes. Broadcasts to workers. Runs on the same JVM as Spark. No external service calls needed.</p>
<p><strong>Akka integration:</strong></p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">akka.actor.typed._</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// LLM-powered actor system
</span></span></span><span class="line"><span class="cl"><span class="k">object</span> <span class="nc">LLMAgent</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Command</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="k">class</span> <span class="nc">ProcessQuery</span><span class="o">(</span><span class="n">query</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">replyTo</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">[</span><span class="kt">Response</span><span class="o">])</span> <span class="k">extends</span> <span class="nc">Command</span>
</span></span><span class="line"><span class="cl">  <span class="k">case</span> <span class="k">class</span> <span class="nc">Response</span><span class="o">(</span><span class="n">result</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">def</span> <span class="n">apply</span><span class="o">(</span><span class="n">client</span><span class="k">:</span> <span class="kt">LLMClient</span><span class="o">)</span><span class="k">:</span> <span class="kt">Behavior</span><span class="o">[</span><span class="kt">Command</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">    <span class="nc">Behaviors</span><span class="o">.</span><span class="n">receive</span> <span class="o">{</span> <span class="o">(</span><span class="n">context</span><span class="o">,</span> <span class="n">message</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="n">message</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">case</span> <span class="nc">ProcessQuery</span><span class="o">(</span><span class="n">query</span><span class="o">,</span> <span class="n">replyTo</span><span class="o">)</span> <span class="k">=&gt;</span>
</span></span><span class="line"><span class="cl">          <span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="n">client</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="nc">Conversation</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span><span class="nc">UserMessage</span><span class="o">(</span><span class="n">query</span><span class="o">))))</span>
</span></span><span class="line"><span class="cl">          <span class="n">result</span> <span class="k">match</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">replyTo</span> <span class="o">!</span> <span class="nc">Response</span><span class="o">(</span><span class="n">completion</span><span class="o">.</span><span class="n">message</span><span class="o">.</span><span class="n">content</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">            <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">error</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">replyTo</span> <span class="o">!</span> <span class="nc">Response</span><span class="o">(</span><span class="s">s&#34;Error: </span><span class="si">${</span><span class="n">error</span><span class="o">.</span><span class="n">message</span><span class="si">}</span><span class="s">&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">          <span class="o">}</span>
</span></span><span class="line"><span class="cl">          <span class="nc">Behaviors</span><span class="o">.</span><span class="n">same</span>
</span></span><span class="line"><span class="cl">      <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Spawn actors for concurrent LLM processing
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">(</span><span class="nc">LLMAgent</span><span class="o">(</span><span class="n">client</span><span class="o">),</span> <span class="s">&#34;llm-system&#34;</span><span class="o">)</span></span></span></code></pre></td></tr></table>
</div>
</div><p>Actors + LLMs. Native Akka integration. Supervision. Backpressure. All the Akka benefits, with LLMs.</p>
<p><strong>ZIO integration:</strong></p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">zio._</span>
</span></span><span class="line"><span class="cl"><span class="k">import</span> <span class="nn">org.llm4s.llmconnect._</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Functional effect system with LLM
</span></span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="n">processWithLLM</span><span class="o">(</span><span class="n">query</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">ZIO</span><span class="o">[</span><span class="kt">LLMClient</span>, <span class="kt">LLMError</span>, <span class="kt">Completion</span><span class="o">]</span> <span class="k">=</span>
</span></span><span class="line"><span class="cl">  <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">client</span> <span class="k">&lt;-</span> <span class="nc">ZIO</span><span class="o">.</span><span class="n">service</span><span class="o">[</span><span class="kt">LLMClient</span><span class="o">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">result</span> <span class="k">&lt;-</span> <span class="nc">ZIO</span><span class="o">.</span><span class="n">fromEither</span><span class="o">(</span><span class="n">client</span><span class="o">.</span><span class="n">complete</span><span class="o">(</span><span class="nc">Conversation</span><span class="o">(</span><span class="nc">Seq</span><span class="o">(</span><span class="nc">UserMessage</span><span class="o">(</span><span class="n">query</span><span class="o">)))))</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span> <span class="k">yield</span> <span class="n">result</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Compose with other effects
</span></span></span><span class="line"><span class="cl"><span class="k">val</span> <span class="n">program</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">  <span class="n">user</span> <span class="k">&lt;-</span> <span class="n">getUserFromDB</span>
</span></span><span class="line"><span class="cl">  <span class="n">query</span> <span class="k">&lt;-</span> <span class="n">buildQuery</span><span class="o">(</span><span class="n">user</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="n">completion</span> <span class="k">&lt;-</span> <span class="n">processWithLLM</span><span class="o">(</span><span class="n">query</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">  <span class="k">_</span> <span class="k">&lt;-</span> <span class="n">saveToCache</span><span class="o">(</span><span class="n">completion</span><span class="o">)</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span> <span class="k">yield</span> <span class="n">completion</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Run with dependency injection
</span></span></span><span class="line"><span class="cl"><span class="n">program</span><span class="o">.</span><span class="n">provide</span><span class="o">(</span><span class="nc">ZLayer</span><span class="o">.</span><span class="n">fromFunction</span><span class="o">(</span><span class="nc">LLMConnect</span><span class="o">.</span><span class="n">client</span><span class="o">))</span></span></span></code></pre></td></tr></table>
</div>
</div><p>llm4s works with ZIO. Effect tracking. Resource management. Retries. Timeouts. Functional patterns, with LLMs.</p>
<h3 id="python-cant-do-this">Python can&rsquo;t do this</h3>
<p>Python LLM libraries don&rsquo;t integrate with JVM ecosystems. They&rsquo;re separate processes. You need REST APIs or message queues. Network overhead. Serialization. Latency.</p>
<p>llm4s runs on the JVM. Same process as your Kafka consumers, Spark jobs, Akka actors. Direct method calls. Zero network overhead. Native integration.</p>
<p>If you&rsquo;re building LLM features for JVM applications, Python adds complexity. Scala eliminates it.</p>
<hr>
<h2 id="architecture-overview">Architecture overview</h2>
<h3 id="layered-design">Layered design</h3>
<p>llm4s follows a clean layered architecture:</p>
<pre class="mermaid">flowchart TD
    APP[&#34;Application Layer&lt;br/&gt;(Your code)&#34;]
    API[&#34;API Layer&lt;br/&gt;(Agent, Assistant, Tools)&#34;]
    CONNECT[&#34;LLMConnect Layer&lt;br/&gt;(LLMClient interface)&#34;]
    PROVIDER[&#34;Provider Layer&lt;br/&gt;(OpenAI, Anthropic, Azure, Ollama)&#34;]
    INFRA[&#34;Infrastructure Layer&lt;br/&gt;(Config, Tracing, Errors, Context)&#34;]

    APP --&gt; API
    API --&gt; CONNECT
    CONNECT --&gt; PROVIDER
    PROVIDER --&gt; INFRA

    style APP fill:#e1f5ff,stroke:#0066cc,color:#000
    style API fill:#fff4e1,stroke:#cc8800,color:#000
    style CONNECT fill:#e1ffe1,stroke:#2d7a2d,color:#000
    style PROVIDER fill:#ffe1e1,stroke:#cc0000,color:#000
    style INFRA fill:#f0e1ff,stroke:#8800cc,color:#000
</pre><p>Each layer knows nothing about layers above it. Each layer has a clear responsibility.</p>
<h3 id="core-types">Core types</h3>
<p><strong>Result types:</strong></p>
<div class="highlight highlight-scala" data-lang="scala"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-scala" data-lang="scala"><span class="line"><span class="cl"><span class="k">type</span> <span class="kt">Result</span><span class="o">[</span><span class="kt">+A</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Either</span><span class="o">[</span><span class="kt">LLMError</span>, <span class="kt">A</span><span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="k">type</span> <span class="kt">AsyncResult</span><span class="o">[</span><span class="kt">+A</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">[</span><span class="kt">Result</span><span class="o">[</span><span class="kt">A</span><span class="o">]]</span></span></span></code></pre></td></tr></table>
</div>
</div><p><strong>Message hierarchy:</strong></p>
<pre class="mermaid">classDiagram
    class Message {
        &lt;&lt;sealed trait&gt;&gt;
        +role: String
        +content: Content
    }
    class UserMessage {
        +role = &#34;user&#34;
        +content: Content
    }
    class AssistantMessage {
        +role = &#34;assistant&#34;
        +content: String
        +toolCalls: Seq~ToolCall~
    }
    class SystemMessage {
        +role = &#34;system&#34;
        +content: String
    }
    class ToolMessage {
        +role = &#34;tool&#34;
        +toolCallId: String
        +content: String
    }

    Message &lt;|-- UserMessage
    Message &lt;|-- AssistantMessage
    Message &lt;|-- SystemMessage
    Message &lt;|-- ToolMessage
</pre><p><strong>Error hierarchy:</strong></p>
<pre class="mermaid">classDiagram
    class LLMError {
        &lt;&lt;sealed trait&gt;&gt;
        +message: String
        +formatted: String
    }
    class RecoverableError {
        &lt;&lt;sealed trait&gt;&gt;
        +shouldRetry: Boolean
        +retryAfter: Option~Duration~
    }
    class NonRecoverableError {
        &lt;&lt;sealed trait&gt;&gt;
        +canRecover: Boolean = false
    }
    class RateLimitError {
        +message: String
        +retryAfter: Option~Duration~
        +provider: String
    }
    class TimeoutError {
        +message: String
        +duration: Duration
        +provider: String
    }
    class NetworkError {
        +message: String
        +cause: Option~Throwable~
    }
    class AuthenticationError {
        +message: String
        +provider: String
    }
    class ValidationError {
        +message: String
        +field: String
        +value: Option~String~
    }

    LLMError &lt;|-- RecoverableError
    LLMError &lt;|-- NonRecoverableError
    RecoverableError &lt;|-- RateLimitError
    RecoverableError &lt;|-- TimeoutError
    RecoverableError &lt;|-- NetworkError
    NonRecoverableError &lt;|-- AuthenticationError
    NonRecoverableError &lt;|-- ValidationError
</pre><p>24+ specific error types with clear categorization for retry logic.</p>
<h3 id="module-structure">Module structure</h3>
<div class="highlight highlight-text" data-lang="text"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">llm4s/
</span></span><span class="line"><span class="cl">├── core/                    # Published to Maven Central
</span></span><span class="line"><span class="cl">│   ├── agent/              # Agent framework
</span></span><span class="line"><span class="cl">│   ├── llmconnect/         # LLM provider layer
</span></span><span class="line"><span class="cl">│   ├── config/             # Configuration system
</span></span><span class="line"><span class="cl">│   ├── error/              # Error types
</span></span><span class="line"><span class="cl">│   ├── toolapi/            # Tool calling API
</span></span><span class="line"><span class="cl">│   ├── trace/              # Tracing &amp; observability
</span></span><span class="line"><span class="cl">│   └── context/            # Context management
</span></span><span class="line"><span class="cl">├── samples/                # Example applications
</span></span><span class="line"><span class="cl">├── workspace/              # Docker-based workspace
</span></span><span class="line"><span class="cl">└── crosstest/              # Cross-compilation tests</span></span></code></pre></td></tr></table>
</div>
</div><p>Published artifact: <code>org.llm4s:core:0.9.0</code></p>
<p>Cross-compiled for Scala 2.13 and 3.x.</p>
<hr>
<h2 id="the-llm4s-community-open-source-done-right">The llm4s community: open source done right</h2>
<h3 id="why-the-community-matters">Why the community matters</h3>
<p>llm4s isn&rsquo;t just a framework. It&rsquo;s a community. Active. Growing. Global.</p>
<p>Here&rsquo;s what makes it special:</p>
<p><strong>Weekly dev hours</strong>: Every Sunday, 9am London time. Live coding. Mob programming. Open to all. The maintainers (Rory Graves and Kannupriya Kalra) host. You join Discord. You code together. You learn together.</p>
<p>This isn&rsquo;t a webinar. It&rsquo;s collaborative development. You pair program with the maintainers. You see code evolve in real time. You influence design decisions.</p>
<p><strong>Google Summer of Code</strong>: llm4s participated in GSoC 2025 through Scala Center. Four funded contributors. They worked to build many major features:</p>
<ul>
<li><strong>Elvan Konukseven</strong>: Agentic toolkit for LLMs</li>
<li><strong>Gopi Trinadh Maddikunta</strong>: RAG in a box</li>
<li><strong>Anshuman Awasthi</strong>: Multimodal support (image, voice)</li>
<li><strong>Shubham Vishwakarma</strong>: Tracing and observability</li>
</ul>
<p>These weren&rsquo;t side projects. They&rsquo;re core features, shipped to production, maintained by the community.</p>
<p><strong>I am happy to co-author with maintainers, GSoC folks and beyond:</strong>:</p>
<ul>
<li><strong>Rory Graves</strong> (<a href="https://www.linkedin.com/in/roryjgraves/" rel="noopener external" target="_blank">LinkedIn</a>
): Lead architect. Scala expert. Created the foundation.</li>
<li><strong>Kannupriya Kalra</strong> (<a href="https://www.linkedin.com/in/kannupriyakalra/" rel="noopener external" target="_blank">LinkedIn</a>
): OSS DX &amp; community champion. Engineering leader, Drives adoption. Speaks at conferences. Mentors GSoC contributors.</li>
<li><strong>Atul S. Khot</strong> (<a href="https://www.linkedin.com/in/atulkhot/" rel="noopener external" target="_blank">LinkedIn</a>
): Co-authored many PRs with Atul ji, he&rsquo;s exceptional design architect, Functional programming expert, Contributed to core library design patterns, reviewed PRs, provided top-notch feedback.</li>
<li><strong>Dmitry Mamonov</strong>: Co-mentored GSoC contributors on RAG and tracing projects, contributed to embedding and retrieval systems.</li>
</ul>
<p><strong>Global conference circuit</strong>: llm4s has been presented at:</p>
<ul>
<li>Bay Area Scala (San Francisco)</li>
<li>Scala India</li>
<li>Functional World (Poland)</li>
<li>Dallas Scala Enthusiasts</li>
<li>London Scala Users Group</li>
<li>ScalaDays 2025 (Switzerland)</li>
<li>Zurich Scala Enthusiasts</li>
</ul>
<p>Real talks. Real demos. Real community engagement.</p>
<h3 id="szork-the-ai-powered-game">Szork: the AI-powered game</h3>
<p>Want to see llm4s in action? Play Szork.</p>
<p>Szork is a text-based adventure game powered by llm4s. The LLM acts as dungeon master. You explore. You solve puzzles. You interact with NPCs. The LLM generates the world dynamically.</p>
<p>It&rsquo;s built entirely on llm4s: Agent framework. Tool calling. Context management. Streaming responses. Multi-turn conversations.</p>
<p>It&rsquo;s also open source: <a href="https://github.com/llm4s/szork" rel="noopener external" target="_blank">https://github.com/llm4s/szork</a>
</p>
<p>This isn&rsquo;t a toy demo. It&rsquo;s a complete application showcasing what llm4s can do. Inspectable. Forkable. Extendable.</p>
<h3 id="the-maintainers-and-co-authors">The maintainers and co-authors</h3>
<p><strong>Maintainers</strong>:</p>
<ul>
<li><strong>Rory Graves</strong> (<a href="https://www.linkedin.com/in/roryjgraves/" rel="noopener external" target="_blank">LinkedIn</a>
): Lead architect. Scala expert. Created the foundation.</li>
<li><strong>Kannupriya Kalra</strong> (<a href="https://www.linkedin.com/in/kannupriyakalra/" rel="noopener external" target="_blank">LinkedIn</a>
): OSS DX &amp; community champion. Engineering leader, Drives adoption. Speaks at conferences. Mentors GSoC contributors.</li>
</ul>
<p><strong>Co-authors</strong>:</p>
<ul>
<li><strong>Atul S. Khot</strong> (<a href="https://www.linkedin.com/in/atulkhot/" rel="noopener external" target="_blank">LinkedIn</a>
): Functional programming patterns expert, design architect, reviews PRs, provides architectural feedback, helps maintain code quality</li>
<li><strong>Dmitry Mamonov</strong> (<a href="https://www.linkedin.com/in/dmamonov/" rel="noopener external" target="_blank">LinkedIn</a>
): Co-mentored GSoC contributors on RAG and tracing, contributed embedding systems expertise, workflows, docker-containers.</li>
</ul>
<p>All are active. All respond to issues. All review PRs. All contribute to making llm4s better.</p>
<p>This is open source done right. Not a corporate side project. Not abandoned after launch. Active. Maintained. Growing.</p>
<hr>
<h2 id="why-foundation-work-matters-a-personal-note">Why foundation work matters (a personal note)</h2>
<p>Look, I&rsquo;ll be honest. When I started contributing to llm4s, I wasn&rsquo;t building the cool stuff. No agent orchestration that gets you retweets. No RAG pipelines that make conference talks. No streaming protocols that look impressive on your resume.</p>
<p>I was fixing error messages. Adding validation. Eliminating try-catch blocks. Building developer tooling. The stuff nobody notices until it&rsquo;s missing.</p>
<p>And you know what? That&rsquo;s exactly what production teams needed. Not the features that demo well. The features that prevent 2 AM incidents.</p>
<p><a href="/2025/08/production-error-handling-when-our-llm-pipeline-threw-unknown-error-in-logs/">Error handling that made debugging 60% faster</a>
. <a href="/2025/08/error-hierarchy-refinement-smart-constructors-and-the-code-we-deleted-in-prod/">Smart constructors that prevent invalid states</a>
. <a href="/2025/09/safety-refactor-the-p1-streaming-bug-wrong-errors-and-47-try-catch-blocks/">Safety utilities that eliminate manual error handling</a>
. <a href="/2025/10/five-production-patterns-from-building-llm4s-what-actually-works-in-prod-today/">Production patterns</a>
 that scale across 8 LLM providers and 4 GSoC projects.</p>
<p>This is the infrastructure work that <a href="https://openssf.org/blog/2025/09/23/open-infrastructure-is-not-free-a-joint-statement-on-sustainable-stewardship/" rel="noopener external" target="_blank">OpenSSF research</a>
 says &ldquo;96% of open source&rsquo;s $8.8 trillion value depends on.&rdquo; The 5% of contributors doing the work everyone depends on but nobody sees.</p>
<p>AI/ML and LLMs are the core. They&rsquo;re what makes llm4s interesting. But the edges, the foundations, the fundamentals - that&rsquo;s what makes it production-ready.</p>
<p>That&rsquo;s the work I&rsquo;m proud of. The articles in this series dive deep into each contribution. Real PRs. Real code reviews. Real production lessons. Not theory. Not toy examples. Actual work that shipped to production and helped teams build reliable LLM systems.</p>
<p>If you&rsquo;re working on infrastructure, on developer experience, on the &ldquo;boring&rdquo; parts of your framework - this is for you. That work matters. More than you think.</p>
<hr>
<h2 id="whats-next-for-llm4s">What&rsquo;s next for llm4s</h2>
<p>llm4s is production-ready today. But we&rsquo;re not done.</p>
<p><strong>Upcoming features:</strong></p>
<ul>
<li>Enhanced streaming support with backpressure handling</li>
<li>Multi-provider failover (OpenAI rate limit? Fall back to Anthropic)</li>
<li>Advanced retry strategies with circuit breakers</li>
<li>Structured output parsing with compile-time validation</li>
<li>Prompt template system with type-safe interpolation</li>
<li>Vector database integrations (Pinecone, Weaviate, Chroma)</li>
<li>More MCP (Model Context Protocol) integrations</li>
</ul>
<p><strong>Community contributions welcome:</strong></p>
<ul>
<li>New provider integrations (Google Gemini, Mistral, Cohere)</li>
<li>More tool examples</li>
<li>Better documentation</li>
<li>Performance optimizations</li>
<li>RAG patterns and examples</li>
<li>Multi-agent coordination patterns</li>
</ul>
<p><strong>Join us:</strong></p>
<ul>
<li>GitHub: <a href="https://github.com/llm4s/llm4s" rel="noopener external" target="_blank">https://github.com/llm4s/llm4s</a>
</li>
<li>Discord: <a href="https://discord.gg/4uvTPn6qww" rel="noopener external" target="_blank">https://discord.gg/4uvTPn6qww</a>
</li>
<li>Try the template: <code>sbt new llm4s/llm4s.g8</code></li>
<li>Weekly dev hour: Sundays 9am London time on Discord</li>
<li>Play Szork: <a href="https://github.com/llm4s/szork" rel="noopener external" target="_blank">https://github.com/llm4s/szork</a>
</li>
</ul>
<hr>
<h2 id="the-bottom-line-python-vs-scala-for-llm-apps">The bottom line: Python vs Scala for LLM apps</h2>
<p>Still deciding between Python and Scala for your LLM project? Here&rsquo;s the honest comparison:</p>
<table>
	<thead>
			<tr>
					<th>Aspect</th>
					<th>Python (LangChain, etc.)</th>
					<th>Scala (llm4s)</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><strong>Time to first prototype</strong></td>
					<td>⚡ Faster (hours)</td>
					<td>Moderate (half day)</td>
			</tr>
			<tr>
					<td><strong>Type safety</strong></td>
					<td>Runtime only</td>
					<td>✅ Compile-time</td>
			</tr>
			<tr>
					<td><strong>Error handling</strong></td>
					<td>Exceptions, try-catch</td>
					<td>✅ Result types, structured errors</td>
			</tr>
			<tr>
					<td><strong>Provider switching</strong></td>
					<td>Rewrite code</td>
					<td>✅ Change config</td>
			</tr>
			<tr>
					<td><strong>Team scaling</strong></td>
					<td>Struggles &gt; 10 engineers</td>
					<td>✅ Scales well</td>
			</tr>
			<tr>
					<td><strong>JVM integration</strong></td>
					<td>REST/gRPC overhead</td>
					<td>✅ Native (Kafka, Spark, Akka)</td>
			</tr>
			<tr>
					<td><strong>Refactoring confidence</strong></td>
					<td>Tests catch some bugs</td>
					<td>✅ Compiler catches most bugs</td>
			</tr>
			<tr>
					<td><strong>Production debugging</strong></td>
					<td>Generic stack traces</td>
					<td>✅ Structured errors with context</td>
			</tr>
			<tr>
					<td><strong>Concurrency</strong></td>
					<td>GIL limitations</td>
					<td>✅ JVM parallelism models</td>
			</tr>
			<tr>
					<td><strong>Enterprise adoption</strong></td>
					<td>Data science teams</td>
					<td>✅ Engineering teams</td>
			</tr>
			<tr>
					<td><strong>Learning curve</strong></td>
					<td>Gentler</td>
					<td>Steeper (functional programming)</td>
			</tr>
			<tr>
					<td><strong>Community size</strong></td>
					<td>Massive</td>
					<td>Smaller but active</td>
			</tr>
			<tr>
					<td><strong>When to use</strong></td>
					<td>Prototypes, data science, small teams</td>
					<td>Production, enterprise, large teams, JVM shops</td>
			</tr>
	</tbody>
</table>
<p><strong>Choose Python if:</strong> You&rsquo;re prototyping, working solo, or your team is already Python-heavy. Also perfect for interviews - leetcode doesn&rsquo;t care about production concerns.</p>
<p><strong>Choose Scala + llm4s if:</strong> You&rsquo;re building for production, integrating with JVM services, or your team is &gt; 10 engineers where type safety prevents chaos.</p>
<p><strong>The transition point:</strong> When your prototype gets greenlit for production, that&rsquo;s when you rewrite in Scala. Not because Python can&rsquo;t work - it can - but because every production issue you&rsquo;ll face (refactoring safety, JVM integration, structured errors, team coordination) is already solved by the JVM ecosystem.</p>
<p>Python is the bicycle that gets you to the prototype party. The JVM is the truck that ships the product to customers. You wouldn&rsquo;t use a bicycle to deliver furniture, and you shouldn&rsquo;t use Python for production LLM apps when you&rsquo;re already running on the JVM.</p>
<hr>
<h2 id="references">References</h2>
<h3 id="llm4s-resources">llm4s resources</h3>
<ul>
<li><a href="https://github.com/llm4s/llm4s" rel="noopener external" target="_blank">llm4s GitHub</a>
 - Main repository</li>
<li><a href="https://github.com/llm4s/llm4s.g8" rel="noopener external" target="_blank">llm4s Template</a>
 - Giter8 template</li>
<li><a href="https://github.com/llm4s/llm4s/tree/main/docs/internals" rel="noopener external" target="_blank">Internals Documentation</a>
 - Architecture deep-dive</li>
<li><a href="https://github.com/llm4s/llm4s/blob/main/docs/llm4s-api-spec.md" rel="noopener external" target="_blank">API Specification</a>
 - Complete API docs</li>
<li><a href="https://discord.gg/4uvTPn6qww" rel="noopener external" target="_blank">Discord Community</a>
 - Get help, contribute</li>
</ul>
<h3 id="key-articles-in-this-series">Key articles in this series</h3>
<ul>
<li><a href="/2025/08/production-error-handling-when-our-llm-pipeline-threw-unknown-error-in-logs/">Error handling foundation</a>
 - Building the error hierarchy</li>
<li><a href="/2025/07/developer-experience-how-we-turned-20-minute-llm4s-setup-into-60-seconds-today/">Developer experience with g8</a>
 - Creating the template</li>
<li><a href="/2025/08/error-hierarchy-refinement-smart-constructors-and-the-code-we-deleted-in-prod/">Smart constructors</a>
 - Validation at construction</li>
<li><a href="/2025/09/safety-refactor-the-p1-streaming-bug-wrong-errors-and-47-try-catch-blocks/">Safety refactor</a>
 - Eliminating try-catch</li>
<li><a href="/2025/10/five-production-patterns-from-building-llm4s-what-actually-works-in-prod-today/">Production patterns</a>
 - What actually works</li>
</ul>
<h3 id="provider-documentation">Provider documentation</h3>
<ul>
<li><a href="https://platform.openai.com/docs/api-reference" rel="noopener external" target="_blank">OpenAI API Reference</a>
 - OpenAI docs</li>
<li><a href="https://docs.anthropic.com/en/api" rel="noopener external" target="_blank">Anthropic API Reference</a>
 - Anthropic Claude docs</li>
<li><a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/" rel="noopener external" target="_blank">Azure OpenAI Documentation</a>
 - Azure docs</li>
<li><a href="https://github.com/ollama/ollama/blob/main/docs/api.md" rel="noopener external" target="_blank">Ollama Documentation</a>
 - Ollama local models</li>
</ul>
<h3 id="functional-programming-in-scala">Functional programming in scala</h3>
<ul>
<li><a href="https://docs.scala-lang.org/" rel="noopener external" target="_blank">Scala Documentation</a>
 - Official Scala docs</li>
<li><a href="https://www.manning.com/books/functional-programming-in-scala-second-edition" rel="noopener external" target="_blank">Functional Programming in Scala</a>
 - FP book (Manning)</li>
<li><a href="https://rockthejvm.com/courses/scala-essentials" rel="noopener external" target="_blank">Rock the JVM - Scala &amp; Functional Programming Essentials</a>
 - Hands-on Scala 3 course with 3000+ lines of code</li>
<li><a href="https://rockthejvm.com/courses/advanced-scala" rel="noopener external" target="_blank">Rock the JVM - Advanced Scala</a>
 - Advanced FP, type system, asynchronous programming</li>
<li><a href="https://rockthejvm.com/courses" rel="noopener external" target="_blank">Rock the JVM - All useful courses</a>
 - Composable, purely functional applications</li>
</ul>
<hr>
<p><strong>TL;DR</strong></p>
<ul>
<li>llm4s is a production-grade Scala framework for building LLM applications with compile-time safety, functional error handling, and provider abstraction - the first and only mature LLM framework for Scala</li>
<li><strong>Why Scala over Python</strong>: Type safety catches errors at compile time; JVM ecosystem native integration (Kafka, Spark, Akka, ZIO); functional programming with immutable data; scales with team size; production performance</li>
<li><strong>Type safety</strong>: Sealed traits with exhaustive pattern matching catch typos at compile time; <code>ToolFunction[T, R]</code> ensures tool definitions are valid before runtime; invalid states impossible to construct</li>
<li><strong>Error handling</strong>: <code>Result[A] = Either[LLMError, A]</code> makes errors explicit; recoverable vs non-recoverable distinction; composable with for-comprehensions; no exceptions</li>
<li><strong>Provider abstraction</strong>: Same code works with OpenAI, Anthropic, Azure, Ollama, OpenRouter - switch by changing config, zero code changes; LLMClient interface abstracts all differences</li>
<li><strong>Agent framework</strong>: Handles tool calling, conversation management, state tracking (InProgress/WaitingForTools/Complete), tracing, safety limits automatically; tail-recursive execution</li>
<li><strong>Type-safe tool calling</strong>: <code>ToolFunction[T, R]</code> with SchemaDefinition validation; SafeParameterExtractor for safe argument parsing; compile-time guarantees Python can&rsquo;t provide; enhanced error reporting</li>
<li><strong>Context management</strong>: Four-stage compression pipeline (deterministic → tool output → history summarization → LLM-based) keeps conversations under token limits automatically</li>
<li><strong>Secure execution</strong>: Docker-based workspace for tool isolation; prevents system damage from hallucinated commands; MCP (Model Context Protocol) support for context coordination</li>
<li><strong>JVM ecosystem integration</strong>: Native Kafka, Spark, Akka, ZIO integration with zero network overhead; broadcast LLM clients to Spark workers; LLM-powered Akka actors; Python frameworks need REST APIs</li>
<li><strong>Observability</strong>: Langfuse integration with latency breakdown, token usage, cost estimation; multi-backend tracing (langfuse/console/noop modes); TRACING_MODE environment variable</li>
<li><strong>Developer experience</strong>: Giter8 template generates working app in 60 seconds (<code>sbt new llm4s/llm4s.g8</code>); pre-commit hooks, CI/CD, tests all included; no TODOs, actual working code</li>
<li><strong>Production patterns</strong>: Smart constructors prevent invalid states, bridge methods enable migrations, safety utilities eliminate try-catch, resource management with .use, error accumulation with ValidatedNec</li>
<li><strong>Active community</strong>: Weekly dev hours (Sundays 9am London), 4 GSoC contributors, global conference circuit (Bay Area, London, ScalaDays), Discord with responsive maintainers</li>
<li><strong>Real demos</strong>: Szork - AI-powered text adventure game built entirely on llm4s; showcases agent framework, tool calling, streaming, multi-turn conversations; fully open source</li>
<li><strong>Cross-compiled</strong>: Scala 2.13 and 3.x, published to Maven Central: <code>&quot;org.llm4s&quot; %% &quot;core&quot; % &quot;0.9.0&quot;</code>; pre-commit hooks enforce cross-version compatibility</li>
</ul>
<hr>
<p><strong>Series navigation:</strong>
← Previous: <a href="/2025/10/five-production-patterns-from-building-llm4s-what-actually-works-in-prod-today/">Production patterns</a>
 | Next: (Coming soon - Streaming deep-dive)</p>
<p><em>This is the introduction article for the llm4s series. <a href="https://github.com/llm4s/llm4s" rel="noopener external" target="_blank">llm4s</a>
 is maintained by <a href="https://github.com/rorygraves" rel="noopener external" target="_blank">Rory Graves</a>
 and <a href="https://github.com/kannupriyakalra" rel="noopener external" target="_blank">Kannupriya Kalra</a>
. Join the community at <a href="https://discord.gg/4uvTPn6qww" rel="noopener external" target="_blank">discord.gg/4uvTPn6qww</a>
.</em></p>
]]></content:encoded><enclosure url="https://vitthalmirji.com/images/og/2025-11-introducing-llm4s.png" type="image/png"/></item><item><title>Is Hadoop dead? Cloudera-Hortonworks, MapR layoffs, and Hadoop 3.0 reality now</title><link>https://vitthalmirji.com/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/</link><guid isPermaLink="true">https://vitthalmirji.com/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/</guid><pubDate>Mon, 01 Jul 2019 00:00:00 +0000</pubDate><dc:creator>vitthal-mirji</dc:creator><category>aws</category><category>azure</category><category>big data</category><category>cloud</category><category>google cloud</category><category>hive</category><category>linux</category><category>programming</category><category>spark</category><description>Deep-dive into Hadoop's state in 2019: Cloudera+Hortonworks merger, MapR struggles, and what Hadoop 3.0 delivers (GPU scheduling, Docker, Hive ACID). Learn why AWS/GCP/Azure dominate but Hadoop is evolving into hybrid cloud with Spark.</description><content:encoded><![CDATA[<p>You know that question everyone&rsquo;s been asking since 2016: &ldquo;Is Hadoop dead?&rdquo;</p>
<p>Fair question. Look at the headlines:</p>
<ul>
<li><strong>2019:</strong> Cloudera and Hortonworks merge (consolidation usually means struggling)</li>
<li><strong>2019:</strong> MapR cuts jobs, announces intent to sell company</li>
<li><strong>Every quarter:</strong> AWS, Azure, GCP revenue skywards</li>
</ul>
<p>Meanwhile, your on-premise Hadoop cluster sits there, maintained by three overworked engineers, running batch jobs that could probably run on BigQuery for $50/month.</p>
<p>But here&rsquo;s the thing: While everyone was writing Hadoop&rsquo;s obituary, Hadoop 3.0 shipped GPU scheduling, Docker containers, ACID transactions in Hive, and native S3 support. Spark became cloud-agnostic. Hive got 10x faster with LLAP.</p>
<p>This post looks at what actually happened to Hadoop in 2019 - not the hype, not the headlines, but the technical reality. Is it dead? Evolving? Worth investing in?</p>
<p>Spoiler: It&rsquo;s complicated. The answer depends on whether you value cloud lock-in or portable code.</p>
<hr>
<h2 id="why-this-matters">Why this matters</h2>
<p>Here&rsquo;s why the &ldquo;Is Hadoop dead?&rdquo; question actually matters:</p>
<p><strong>If Hadoop is dead</strong>, your organization should:</p>
<ul>
<li>Stop investing in on-premise clusters</li>
<li>Migrate to BigQuery/Redshift/Synapse</li>
<li>Retrain engineers on cloud-native tools</li>
<li>Accept vendor lock-in as the price of convenience</li>
</ul>
<p><strong>If Hadoop is evolving</strong>, you should:</p>
<ul>
<li>Invest in Spark (it runs everywhere)</li>
<li>Consider hybrid cloud approaches</li>
<li>Leverage portable code across providers</li>
<li>Maintain independence from single vendors</li>
</ul>
<p>The difference? Potentially millions in migration costs and strategic lock-in to a single cloud provider.</p>
<p>I started with Hadoop around 2014/2015. Back then, it had things other platforms lacked:</p>
<ul>
<li><strong>Open source</strong> - No vendor lock-in</li>
<li><strong>Beyond MapReduce</strong> - Spark, Hive, real-time with Storm</li>
<li><strong>Runs on anything</strong> - Old hardware, laptops (my 2013 MacBook Pro still runs local HDFS/YARN/Hive)</li>
<li><strong>Enterprise support</strong> - Hortonworks HDP, Cloudera CDH, MapR</li>
</ul>
<p>But it wasn&rsquo;t easy. Configuration, performance tuning, tool selection, ops, and development required deep expertise. One wrong config could tank cluster performance.</p>
<p>Then cloud providers showed up with managed services. Click a button, get a cluster. No ops team needed.</p>
<p>So what happened? Let&rsquo;s look at the data.</p>
<hr>
<h2 id="part-1---the-business-reality-mergers-and-struggles">Part 1 - The business reality: mergers and struggles</h2>
<p>Apache Hadoop, the open source framework for “reliable, scalable, distributed computing”, first saw the light of the day
in 2006, based on Google’s &ldquo;MapReduce: Simplified Data Processing on Large Clusters&rdquo; whitepaper (
available <a href="http://ai.google/research/pubs/pub62" rel="noopener external" target="_blank">here</a>
) from 2003. Over the coming years, more and more tools (such as
Pig by Yahoo) emerge, the major distributions from Hortonworks, Cloudera, and MapR are being released, performance
records are being made (2008/2009), SQL-like support by Apache Hive becomes available in 2010 and schedulers like YARN
become popular (2012/2013).</p>
<p>Around 2014/2015, Hadoop finally had a lot of things going for it which other platforms lacked - it was Open Source,
already moved past the tedious limitations of Java-based Map/Reduce programs, supported both Batch and Real-Time
applications, ran on pretty much every old piece of hardware you could find, could be run by either setting it up
yourself (my 2013 Macbook Pro still has a local HDFS, YARN, and Hive instance running) or as enterprise level solution
by Hortonworks’ HDP, Cloudera’s CDH, or MapR. It enabled companies to ingest, store, and analyze any data and was used
heavily in production across major companies.</p>
<p>A lot of additional tools supported the framework - the below tables gives a rough overview of components we will
mention in this article:</p>
<table>
	<thead>
			<tr>
					<th>Tool</th>
					<th>Description</th>
					<th>First Release</th>
					<th>Latest Release</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><a href="https://hadoop.apache.org" rel="noopener external" target="_blank">YARN</a>
</td>
					<td>Resource Manager &amp; Scheduler</td>
					<td>2006</td>
					<td>2019-02-06</td>
			</tr>
			<tr>
					<td><a href="https://hbase.apache.org/" rel="noopener external" target="_blank">Hbase</a>
</td>
					<td>no-SQL database</td>
					<td>2008</td>
					<td>2019-06-11</td>
			</tr>
			<tr>
					<td><a href="https://hive.apache.org/" rel="noopener external" target="_blank">Hive</a>
</td>
					<td>Data Warehouse and SQL abstraction</td>
					<td>2010</td>
					<td>2019-05-14</td>
			</tr>
			<tr>
					<td><a href="http://sqoop.apache.org" rel="noopener external" target="_blank">Sqoop</a>
</td>
					<td>RDMBS ingestion pipeline</td>
					<td>2009</td>
					<td>2019-01-18</td>
			</tr>
			<tr>
					<td><a href="https://spark.apache.org" rel="noopener external" target="_blank">Spark</a>
</td>
					<td>Data processing framework and compute engine</td>
					<td>2014</td>
					<td>2019-05-08</td>
			</tr>
			<tr>
					<td>Tez</td>
					<td>Execution frameworks for DAGS on Hive or Pig</td>
					<td>2014</td>
					<td>2019-03-29</td>
			</tr>
	</tbody>
</table>
<p>As you can see, all recent releases where within the last 6 months (at the time of writing).</p>
<p>Things were not without their drawbacks, however - like most Open Source software, especially when bundled in a modular
way, running on dozens, hundreds, or thousands of machines is not without challenges. Configuration, performance
optimization, tool selection, maintenance, operations, and development require deep expertise to make any Hadoop
installation run smoothly, as one wrong configuration setting can severely degrade the performance of the overall
system. At the same time, this level of granular control also allows for an unmatched level of flexibility and
adaptability of your tools.</p>
<h2 id="the-emerging-cloud-market">The emerging Cloud Market</h2>
<p><picture><source type="image/avif" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/my_sky_hu_cb2459757cd74ebb.avif 400w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/webp" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/my_sky_hu_94d18a496a541a77.webp 400w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/png" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/my_sky_hu_4c4e182965b672c4.png 400w" sizes="(max-width: 800px) 100vw, 800px"><img src="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/my_sky_hu_5ed16e91a2b91aa.jpg" alt="" loading="lazy" width="800" height="285">
    </picture></p>
<p><a href="https://xkcd.com/1117/" rel="noopener external" target="_blank">https://xkcd.com/1117/</a>
, CC BY-NC 2.5</p>
<p>However, over the past years, more and more companies find their benefits in the major Cloud providers - AWS, Google
Cloud, and Microsoft Azure. Their benefits are many - a massively reduced need for local infrastructure and
administration, flexible scaling from a couple of GB to TB of memory, storage, and CPU, a flexible bill-by-usage model,
out-of-the-box machine learning models, and integration into other, non-”Big Data” tools.</p>
<p>Companies were able to move from needing to maintain expensive, bare-metal boxes in-house that may run idle for 80% of
the day and cause resource constraints and bottlenecks during scheduled batch-runs, limited by tools the organization
had Subject Matter Experts or external support for, to reserving resources for massive jobs that can handle terabytes of
data in minutes or seconds for a couple of $.</p>
<p>So the question stands - what has happened with Hadoop since then - and is there still a need for it?</p>
<h2 id="a-look-at-the-overall-ecosystems-changes">A look at the overall ecosystem’s changes</h2>
<p>Before we dig into the individual components, let’s briefly talk about what happened from a bird’s-eye view.</p>
<p>In early 2019, two of the major providers (Hortonworks and Cloudera) announced a
massive <a href="http://hortonworks.com/blog/welcome-brand-new-cloudera/" rel="noopener external" target="_blank">merger</a>
 of the two companies. The step made sense for
any Software Engineer familiar with the technology - both companies worked on an almost identical tech stack, both were
heavily involved in Open Source software, both offered a supported or managed Hadoop stack with convenient
administration and a multitude of available tools. Cloudera’s focus on Machine Learning and Hortonwork’s focus on data
ingestion and aggregation also provide potential for powerful synergies. Their press release
mentions $760M in TTM revenue and $500M in cash without debts.</p>
<p>One of the key strategic targets of the merger is the focus on Cloud (I quote: “Cloud Everywhere!”) - but a Cloud based
on Open Source technology. The company’s target is to provide customers with the benefits of Hadoop and (F)OSS (see
above), as well as the advantages of Public Cloud providers.</p>
<p>This is not a new development - Hortonwork’s 3.0 release
already <a href="https://docs.hortonworks.com/HDPDocuments/HDP3/HDP-3.0.0/release-notes/hdp-release-notes.pdf" rel="noopener external" target="_blank">included support for storage on all Cloud providers</a>
 (
as opposed to strictly HDFS) in July of 2018.</p>
<p>At the same time, competitor MapR (who focused mostly on proprietary
solutions), <a href="http://siliconangle.com/2019/05/30/mapr-may-shut-investor-pulls-following-extremely-poor-results/" rel="noopener external" target="_blank">announced job cuts in May of 2019</a>

and finally announced the intent
to <a href="https://www.datanami.com/2019/06/18/mapr-says-its-close-to-deal-to-sell-company/" rel="noopener external" target="_blank">sell the company</a>
 in June 2019.
The company struggled with the monetization of the business model and the strong drive towards Cloud native operations.</p>
<p>During all this, the Public Cloud market only knew one
direction: <a href="https://www.skyhighnetworks.com/cloud-security-blog/microsoft-azure-closes-iaas-adoption-gap-with-amazon-aws/" rel="noopener external" target="_blank">Skywards</a>
.
The revenue of AWS, GCP, and Azure provide large portions of the respective companies earnings and seemingly every new
conference provides impressive advancements in the respective technologies and fewer companies rely on their local data
centers.</p>
<p>And <a href="https://www.ciodive.com/news/ibm-still-sees-value-in-hadoop-based-technologies/557326/" rel="noopener external" target="_blank">IBM</a>
 still sees value in
Hadoop.</p>
<h2 id="what-happened-in-the-open-source-space-since-then">What happened in the Open Source space since then?</h2>
<p>While the above certainly doesn’t inspire confidence, we also should take a look at what actually happened over the past
years - while the Cloud providers did show some amazing, easy-to-use products from data ingestion all the way through to
Machine Learning and Analytics use cases, development in the (F)OSS space did not stop.</p>
<h3 id="hadoop-overall">Hadoop Overall</h3>
<p>Hadoop 3.0 made some <a href="https://hadoop.apache.org/old/releases.html" rel="noopener external" target="_blank">huge additions</a>
 to the feature set.</p>
<p>YARN now
supports <a href="https://hadoop.apache.org/docs/r3.1.2/hadoop-yarn/hadoop-yarn-site/DockerContainers.html" rel="noopener external" target="_blank">docker containers</a>
, <a href="https://hadoop.apache.org/docs/r3.1.2/hadoop-yarn/hadoop-yarn-site/UsingGpus.html" rel="noopener external" target="_blank">GPU scheduling</a>

for e.g. TensorFlow, more advanced scheduling features, the overall platform offers native support
for <a href="http://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/index.html" rel="noopener external" target="_blank">AWS S3</a>
.</p>
<p>These changes enable organizations running Hadoop clusters to move away from the traditional approach of running mostly
large Batch jobs on YARN and separate ML jobs on premise to switch to a more modern container-based approach and utilize
GPU-driven Machine Learning and also integrate Cloud providers into either “hybrid” or even native Cloud model.</p>
<h3 id="hbase">HBase</h3>
<p>Apache HBase is one of those things I have a love-hate relationship with - it is very fast, very powerful and can be
even simple to use once you grasp the basics, but can also be a beast to tame once it scales up.</p>
<p>Similar to Spark, Hbase had a major version bump to 2.x., but the changes are less obvious than more end-user facing
tools such as Hive. As a reminder, HBase (out of the box) offers a Ruby-based shell and APIs for various languages and
is rarely used as a standalone tool - with the notable exception of <a href="https://phoenix.apache.org" rel="noopener external" target="_blank">Apache Phoenix</a>
, which
we won’t cover in this article.</p>
<p>You can find those releases notes on the project’s homepage
for <a href="https://apache.org/dist/hbase/2.0.5/RELEASENOTES.md" rel="noopener external" target="_blank">2.0.5</a>
, <a href="https://apache.org/dist/hbase/2.1.5/RELEASENOTES.md" rel="noopener external" target="_blank">2.1.5</a>
, <a href="https://apache.org/dist/hbase/2.2.0/RELEASENOTES.md" rel="noopener external" target="_blank">2.2.0</a>
,
as well as the
project’s <a href="https://issues.apache.org/jira/browse/HBASE-22596?jql=project%20%3D%20HBASE%20AND%20issuetype%20in%20%28Improvement%2C%20%22New%20Feature%22%29%20AND%20status%20in%20%28Resolved%2C%20Closed%29%20AND%20fixVersion%20%3D%203.0.0" rel="noopener external" target="_blank">JIRA</a>
.</p>
<p>Risking to offend some people - Hbase is a project that follows the UNIX philosophy - do one thing and do it right - a
lot more than other projects and hence, it’s improvements over the years are less apparent. Looking at the associated
tools, libraries, and frameworks will give you a better overview.</p>
<p><a href="https://cloud.google.com/bigtable/" rel="noopener external" target="_blank">Google Cloud’s BigTable</a>
 is interoperable with Hbase and hence works with all
existing HBase projects, as a cloud-native, managed service.</p>
<h3 id="hive">Hive</h3>
<p>Hive’s compatibility is usually tied to the <a href="http://hive.apache.org/downloads.html" rel="noopener external" target="_blank">release of Hadoop</a>
 - Hive 3.x works
with Hadoop 3.x, Hive 2.x works with Hadoop 2.x and so on.</p>
<p>Just focussing on
the <a href="https://issues.apache.org/jira/secure/ReleaseNote.jspa?version=12340268&amp;styleName=Text&amp;projectId=12310843" rel="noopener external" target="_blank">3.x release branches</a>
,
Hive went from being a rather limited, not exactly fast, Map-Reduce driven SQL-layer to a low-latency, in-memory driven,
powerful analytics framework.</p>
<p>The introduction of <a href="https://cwiki.apache.org/confluence/display/Hive/LLAP" rel="noopener external" target="_blank">Hive <strong>LLAP</strong></a>
 (low-latency analytical
processing), first introduced in Hive 2.0, provides exactly what the name entails. It runs a daemon service on YARN that
coordinates job runs, where smaller runs are being orchestrated directly by the daemon and larger, more resource
intensive jobs are going through a fully-fledged YARN job. This method allows for much quicker queries, while still
giving users the option to run large jobs that access large volumes of data and hence comes closer to the benefits of a
large RDMBS cluster, such as Postgres.</p>
<p><picture><source type="image/avif" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_cd3149c2d445f49c.avif 400w, /2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_77f25ece2cddd38e.avif 800w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/webp" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_f8c6bb0a7aa4e1ac.webp 400w, /2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_a7d965a8979d2ae2.webp 800w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/png" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_34af17754bdc60af.png 400w, /2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_febec3aedf5da9a9.png 800w" sizes="(max-width: 800px) 100vw, 800px"><img src="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0-1_hu_a46a0d042732a5.jpg" alt="" loading="lazy" width="800" height="402">
    </picture></p>
<p><a href="https://cwiki.apache.org/confluence/display/Hive/LLAP" rel="noopener external" target="_blank">https://cwiki.apache.org/confluence/display/Hive/LLAP</a>
</p>
<p>Furthermore, it also finally allowed support for <a href="https://cwiki.apache.org/confluence/display/Hive/Hive&#43;Transactions" rel="noopener external" target="_blank">**ACID
** transactions,</a>
 a surprisingly new feature for
Hive data. Where the legacy versions of Hive mostly relied on immutable data, where updates could only be realized using
INSERT OVERWRITE or CTAS statements.</p>
<p>While ACID does come with it’s own challenges and limitations, it moves Hive closer and closer to the likes of either a
traditional RDMBS or a Google BigQuery (which has update support, albeit limited).</p>
<h3 id="sqoop">Sqoop</h3>
<p>Sqoop is a powerful tool, as it allows you to ingest data into Hadoop from various RDMBS. While this seems like a
trivial task, it is usually an operation dominated by the likes of Informatica or Pentaho ETL.</p>
<p>Similar to HBase, its improvements are mostly under the hood. See the release notes
of <a href="https://sqoop.apache.org/docs/1.4.7/sqoop-1.4.7.releasenotes.html" rel="noopener external" target="_blank">1.4.7</a>
, currently shipped with HDP 3.1, for
reference.</p>
<p>A special thing to mention here is the lack of comparable tools for most Cloud providers. Sqoop talks to a database,
either via integrated incremental or full loads, or even custom SQL, and stores the data on HDFS (and Hive, if
required). It makes ingesting data from operational source systems that do not take analytical or ETL load
straightforward and easy. As a matter of fact, AWS
EMR <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-sqoop-considerations.html" rel="noopener external" target="_blank">supports Sqoop loads to S3</a>
.</p>
<p>This point might be controversial and I would gladly take insights into other FOSS tools providing similar capabilities
to the big managed SQL-likes of the cloud proviers as well as their storage components (S3, GCS etc.).</p>
<h3 id="spark">Spark</h3>
<p>Apache Spark (which is not strictly tied to Hadoop, more on that later), had a major version change from 1.6.x
to <a href="https://spark.apache.org/releases/spark-release-2-0-0.html" rel="noopener external" target="_blank">2.x</a>
, changing the API and introducing a lot of new
features.</p>
<p>The 2.x and subsequent releases enabled more comprehensive SQL support on various platforms, huge performance increases
on SQL operations on DataFrames/DataSets (2-10X), more support for underlying file formats (ORC, Parquet), native
support for Kafka in 2.1, more advanced and reliable streaming in 2.2, support for Kubernetes, updated History server, a
new data source API (e.g., reading CSV files natively) in 2.3, and more support for advanced execution modes for Machine
Learning / “Deep Learning”, higer order functions and more
in <a href="https://spark.apache.org/releases/spark-release-2-3-0.html" rel="noopener external" target="_blank">2.4</a>
.</p>
<p>Spark is available on Java, Scala, Python, and R and hence provides interfaces for various popular languages an
organization might have SMEs for.</p>
<p>Furthermore, the Spark framework is detached from Hadoop as such and is available
on <a href="https://aws.amazon.com/emr/features/spark/" rel="noopener external" target="_blank">AWS EMR</a>
, Google Cloud <a href="https://cloud.google.com/dataproc/" rel="noopener external" target="_blank">Dataproc</a>
,
and Azure <a href="https://docs.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-overview" rel="noopener external" target="_blank">HDInsights</a>
, allowing
developers to lift-and-shift existing Spark applications (whether a small helper script or a massive, multi-tier
application) to the Cloud on fully-managed services.</p>
<p>This enables companies to not only re-use existing IP, but also to provide a level of independence towards a single,
external provider. Despite my high praises for the likes of GCP in previous publications, this independence can be a
strategic advantage.</p>
<p><picture><source type="image/avif" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0_hu_960b1e64f0496d77.avif 400w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/webp" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0_hu_7acedae1a37f8060.webp 400w" sizes="(max-width: 800px) 100vw, 800px"><source type="image/png" srcset="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0_hu_28a1868e2ffeb0c7.png 400w" sizes="(max-width: 800px) 100vw, 800px"><img src="/2019/07/is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now/images/pasted-image-0_hu_456268df32becd8.jpg" alt="" loading="lazy" width="800" height="652">
    </picture></p>
<p><a href="https://cloud.google.com/dataproc/" rel="noopener external" target="_blank">https://cloud.google.com/dataproc/</a>
</p>
<h3 id="tez">TEZ</h3>
<p>Apache TEZ allows Hive and PIG to run DAGs, as opposed to M/R jobs. While clearly a Hadoop-exclusive component, it is
still worth looking into.</p>
<p>The changes TEZ made are sometimes user facing, like the new TEZ UI
in <a href="http://tez.apache.org/releases/0.9.0/release-notes.txt" rel="noopener external" target="_blank">0.9.0</a>
, but mostly also operate under the hood to provide
better performance and scalability than previous versions. It’s biggest strength is the additional performance and
monitoring capabilities that it offers over M/R jobs.</p>
<h3 id="so-what">So what?</h3>
<p>Now, we’ve talked at length about what happened in some cherry-picked Hadoop and related tools. But what does this mean
for you?</p>
<p>One thing is clear - running an Open Source tech stack on bare metal in your data center has its disadvantages, as well
as clear advantages. You own your data, you own your tech stack, you have the capability to commit back to the ecosystem
by contributing to Open Source. You have the ability to work on the features you need and are not forced to take the
ones offered by third parties.</p>
<p>The independence from Cloud providers gives companies the sovereignty over their data and make them independent of
bandwidth constraints or regulatory issues (not to be confused with “no regulatory compliance necessary on-premise).</p>
<p>Hadoop’s new features and stability improvements make using the platform and it’s tools (including all the ones we
haven’t touched upon in this article) more and more convenient and powerful. The advancements in the ML space,
specifically on Spark(ML) and YARN, also pave the way for more analytics and less aggregation and traditional database
modelling.</p>
<p>The steady rise of Cloud-driven data processing and analytics and
a <a href="https://www.wsj.com/articles/cloudera-struggles-highlight-rapid-rise-of-public-cloud-11559865497" rel="noopener external" target="_blank">lowering interest in Hadoop</a>

might lead to the belief that it’s a “black and white” situation - either move to Cloud or stay on-premise.</p>
<p>I disagree - hybrid approaches are real and can offer the best of both worlds. You can maintain a local Hadoop instance
and combine it with, for instance, a managed Machine Learning service
like <a href="https://cloud.google.com/automl/" rel="noopener external" target="_blank">Google Cloud AutoML</a>
 on BigQuery with a subset of your data, stripped from PII.</p>
<p>You can also move your existing Hadoop workloads to the Cloud with the likes of EMR or Dataproc, taking advantage of the
Cloud’s scabality and cost savings, whilst developing portable software across Cloud providers.</p>
<p>The latter is roughly the route I can see Cloudera/Hortonworks taking in the future - take advantage of FOSS, while
benefiting from the vast amount of proprietary and powerful solutions the Public Cloud offers.</p>
<p>In some instances, moving legacy systems to the Cloud is not a realistic option without a fully-fledged, multi-year
migration effort - for instance, 20, 30 (or even older!) year old database systems that manage a business&rsquo;s daily
operations. However, combining the strength of custom software and Open Source, tailored towards your business needs,
can prove invaluable.</p>
<p>In the end, it depends - Hadoop is certainly not dead, but the continued investment by Amazon, Google, and Microsoft
certainly might change this in the upcoming years.</p>
<hr>
<p><strong>TL;DR</strong></p>
<ul>
<li><strong>The question:</strong> Is Hadoop dead in 2019 with cloud providers dominating?</li>
<li><strong>Business signals:</strong> Cloudera+Hortonworks merged ($760M revenue, &ldquo;Cloud Everywhere!&rdquo; strategy), MapR struggled and sold company, AWS/GCP/Azure revenue soaring</li>
<li><strong>Technical reality:</strong> Hadoop 3.0 shipped major features (GPU scheduling, Docker containers on YARN, native S3 support, Hive LLAP for 10x faster queries, ACID transactions)</li>
<li><strong>Hive improvements:</strong> LLAP low-latency processing, ACID support (finally!), moves closer to RDBMS capabilities</li>
<li><strong>Spark evolution:</strong> Cloud-agnostic (runs on EMR, Dataproc, HDInsights), portable code across providers, 2-10x performance gains in 2.x releases</li>
<li><strong>The hybrid approach:</strong> Run Hadoop on-premise + managed cloud ML (like AutoML on BigQuery), or lift-shift Spark to cloud while keeping code portable</li>
<li><strong>Verdict:</strong> Not dead - evolving toward hybrid cloud and cloud-native Hadoop (Dataproc/EMR) with Open Source foundations</li>
<li><strong>Strategic choice:</strong> Cloud lock-in (faster, easier, managed) vs. portable code (independence, hybrid options, no vendor lock-in)</li>
<li><strong>The future:</strong> Cloudera/Hortonworks betting on FOSS + Cloud hybrid; Spark&rsquo;s portability = strategic advantage; legacy systems + custom FOSS can coexist with cloud</li>
<li><strong>Bottom line:</strong> Hadoop isn&rsquo;t dead - it&rsquo;s adapting. Investment by AWS/Google/MS in Hadoop-compatible services proves the tech stack has value</li>
</ul>
]]></content:encoded><enclosure url="https://vitthalmirji.com/images/og/generated/2019-07-is-hadoop-dead-cloudera-hortonworks-mapr-layoffs-and-hadoop-3.0-reality-now.png" type="image/png"/></item></channel></rss>