Leanpub Header

Skip to main content

Practical Artificial Intelligence With Scala

Practical AI Code in Scala

Practical Artificial Intelligence With Scala
This book is 100% completeLast updated on 2026-09-11

Learn the theory with short Scala code examples.

Minimum price

Free!

$20.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
About

About

About the Book

Practical Artificial Intelligence With Scala is a hands-on guide to building AI systems in Scala 3. Each chapter is a self-contained scala-cli project with complete, runnable code: classical search over graphs, mazes, and game trees; backpropagation neural networks, genetic algorithms, anomaly detection, and a character-level transformer with scalar autograd; probability, Bayesian updating, and symbolic differentiation and integration; and the modern AI stack, with clients for Gemini, OpenAI, Ollama, Anthropic, and other model providers, retrieval-augmented generation, tool-calling agents, prompt caching, the Semantic Web with SPARQL, and an interactive Scala.js web app. The book explains each algorithm and shows the full implementation, so you can read a chapter, run the example, and see the result. If you know Scala and want to understand how AI systems work, this book provides the code and the reasoning to build them.

Share this book

Categories

Author

About the Author

Mark Watson

Mark Watson is a consultant specializing in LLMs, deep learning, machine learning, knowledge graphs, and general artificial intelligence software development. He uses Common Lisp, Clojure, Python, Java, Haskell, and Ruby for development.

He is the author of 20+ published books on Artificial Intelligence, Deep Learning, Java, Ruby, Machine Learning, Common LISP, Clojure, JavaScript, Semantic Web, NLP, C++, Linux, and Scheme. He has 55 US Patents.

Mark's consulting customer list includes: Google, Capital One, Olive AI, CompassLabs, Disney, Sitescout.com, Embed.ly, and Webmind Corporation.

Mark wrote ten traditional published books for McGraw Hill, Springer Verlag, J Wiley, and Morgan Kaufman publishers before adopting the LeanPub self-publishing platform.

The Leanpub Podcast

Podcast

Podcast Episode

Contents

Table of Contents

Cover Material, Copyright, and License

Preface

  1. Who This Book Is For
  2. How To Read This Book
  3. Open Source Example Programs and Manuscript Files
  4. Acknowledgments

Scala 3 Conventions and Tricks Used in This Book

  1. Running an Example with scala-cli
  2. Indentation Instead of Braces
  3. Top-Level Definitions and @main
  4. Case Classes and copy
  5. Enums as Data Types
  6. Pattern Matching
  7. Options and Either
  8. For-Comprehensions
  9. Collections
  10. String Interpolation
  11. Extension Methods, Givens, and Context Parameters
  12. Operator Overloading
  13. Early Exit with boundary and break
  14. inline and @tailrec
  15. A Note on DSLs
  16. Where to Go Next

Search Algorithms

  1. Search as a Formal Problem
  2. Representing Graphs
  3. Depth-First and Breadth-First Graph Search
  4. Maze Generation and Solving
  5. Game Tree Search: Minimax for Tic-Tac-Toe
  6. Running the Search Demos

A Chess Engine and AI Bot

  1. A Short History and the Size of the Problem
  2. Architecture of a Chess Engine
  3. Search Engine: Negamax with Alpha-Beta Pruning
  4. Positional Evaluation
  5. Running the Chess CLI and Perft Tests

Backpropagation Neural Networks from Scratch

  1. A Short History: Why We Need Hidden Layers
  2. Neural Network Representation
  3. Feedforward Pass
  4. Backpropagation and Weight Updates
  5. Demo: Learning the XOR Gate

Genetic Algorithms

  1. Evolutionary Computation and When to Reach for It
  2. Chromosomes and the Genetic Representation
  3. The Genetic Algorithm Engine
  4. A Simple Example: Maximizing a Complex Function
  5. Running the Optimization

Anomaly Detection

  1. Why Anomaly Detection, Not Classification
  2. How Gaussian Anomaly Detection Works
  3. Preprocessing the Data
  4. Implementing Anomaly Detection
  5. Running the Anomaly Detector

Natural Language Processing

  1. The Classic NLP Pipeline
  2. Tokenization
  3. Part-of-Speech Tagging
  4. Named Entity Extraction
  5. Running the NLP Demo

Semantic Web and SPARQL

  1. From a Web of Documents to a Web of Data
  2. The Apache Jena Integration
  3. Local Ontological Reasoning and RDFS
  4. Local and Remote Queries
  5. Running the Semantic Web Demo

Knowledge Graph Navigator (KGN)

  1. The Grounding Problem and Entity Linking
  2. How KGN Works
  3. Extracting and Resolving Entities
  4. Fetching Entity Details with SPARQL Templates
  5. Discovering Semantic Relationships
  6. Running the KGN Shell

Integrating Google Gemini

  1. How Large Language Models Work
  2. Project Setup and Dependencies
  3. Implementing the Gemini Client
  4. Running the Demos

Integrating OpenAI

  1. The Chat Completions Format
  2. The OpenAI REST Client
  3. Beyond Chat: Embeddings
  4. Running the OpenAI Demo

Local LLMs with Ollama

  1. Why Run a Model Locally
  2. The Ollama REST Client
  3. Running the Ollama Demo

An Interactive Text Adventure Game with Ollama

  1. From Generate to Chat
  2. The Story Prompt as Data
  3. The Data Model: Roles and Messages
  4. The Ollama Chat Client
  5. The Game Loop
  6. A Connection Test Entry Point
  7. Building and Running
  8. Interpreting the Results
  9. Wrap Up
  10. Optional Practice Problems

Autonomous Agents with AgentScope

  1. From Text Generator to Agent
  2. Project Configuration
  3. Creating a Conversational Agent
  4. Equipping Agents with Custom Tools
  5. Running the Agent Demo

Building a Neural-Symbolic Knowledge Graph Engine in Scala

  1. What we are going to build
  2. Background: three ideas you need first
  3. How the pieces connect
  4. The build file
  5. The data model: terms and triples
  6. Unification
  7. The triplestore
  8. The reader
  9. The query engine
  10. The neural layer
  11. Supporting infrastructure
  12. The embedded DSL: recreating reader macros in Scala
  13. Running the engine
  14. Testing
  15. Interpreting the results
  16. Wrap Up
  17. Optional Practice Problems

Probability: Bayes, Base Rates, and Tests

  1. Two Ways to Read a Probability
  2. Bayes Theorem
  3. Bayes in Seven Lines
  4. The Medical Test That Fools Doctors
  5. Frequentist Checks: z, Chi-Squared, Wilson
  6. Correlation in Nine Lines
  7. The Test Suite
  8. Running the Examples
  9. Interpreting the Output
  10. Wrap Up
  11. Optional Practice Problems

Symbolic Math: Differentiate and Integrate

  1. Two Ways to Do Calculus on a Computer
  2. Terms and Polynomials as Data
  3. Differentiation: The Power Rule and Linearity
  4. Integration: The Reverse Power Rule and the Fundamental Theorem
  5. The Demo
  6. The Test Suite
  7. Interpreting the Output
  8. What This Core Does Not Do
  9. Wrap Up
  10. Optional Practice Problems

Agentic RAG with Local Docs

  1. The RAG Pipeline
  2. Lexical and Dense Retrieval
  3. Chunking Long Documents
  4. Ranking with TF-IDF and BM25
  5. Rewriting and Fanning Out Queries
  6. Building the Grounded Prompt
  7. Answering with Local Ollama
  8. Loading the Docs and Running the Demo
  9. Offline Checks
  10. Extending the Pipeline

Brave Web Search for Agents and RAG

  1. Getting a Key and the Request Shape
  2. Reading the Reply
  3. The Client
  4. Parsing the Reply
  5. Running a Search
  6. Wiring It to RAG and Tools
  7. Demo and Checks
  8. Extending the Client

LLM Tool Use Without a Framework

  1. What Tool Use Actually Is
  2. A Tool Registry in Thirty Lines
  3. Three Safe Builtins
  4. The CALL and FINAL Loop
  5. The Demo
  6. Offline Tests
  7. Wrap Up
  8. Optional Practice Problems

A SQLite Cache for LLM Calls

  1. Why Cache Model Calls
  2. Four Places to Cache
  3. Exact Keys Versus Term Matching
  4. What Belongs in a Cache Key
  5. Opening the Store
  6. Writing Rows Safely
  7. Looking Up by Terms
  8. Managing the Data Store
  9. Demo and Its Output
  10. Cache First, Model Second
  11. Safety, Staleness, and Cost
  12. Offline Checks
  13. Extending the Cache

More Hosted Models: Anthropic, Mistral, Groq, Moonshot, Perplexity, Hugging Face

  1. One Record for Six Vendors
  2. The Odd Two: Anthropic and Hugging Face
  3. One Send for All
  4. Demo and Its Output
  5. Parsers You Can Test Offline

Ollama Vision: Read Text from Images

  1. How a Vision Model Sees
  2. What Ollama Expects
  3. The Client
  4. Request and Response in Full
  5. The Demo
  6. Running the Demo
  7. Interpreting the Output
  8. Offline Tests
  9. Practical Limits
  10. Wrap Up
  11. Optional Practice Problems

A Tiny Transformer from Scratch

  1. Why Attention Replaced Recurrence
  2. A Tiny Corpus and Character Tokens
  3. The Autograd Engine
  4. The Transformer Block
  5. Loss and a Training Step
  6. Greedy Generation
  7. The Demo and Its Output
  8. Tests That Pin Learning
  9. Wrap Up
  10. Optional Practice Problems

Interactive Web Widgets with Laminar

  1. Why Laminar Fits This Book
  2. Widget One: Bayes Sliders
  3. Widget Two: Doc Search
  4. What the Reader Sees
  5. Build and Open

Also by the Author

Also by the Author

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub