Run your own AI router, built into a SQL query engine

Call any model from a SQL query, or from apps and agents through OpenAI- and Anthropic-compatible APIs. Run an isolated router for each app or tenant anywhere: on-prem, in your own cloud, or on Spice Cloud.

Diagram of apps and AI agents calling Spice.ai, which queries PostgreSQL and Databricks and routes to hosted OpenAI and Anthropic or self-hosted models

A model router inside your query engine

Spice routes model calls from apps and agents and runs them inside SQL queries next to your data. Every query and model call is recorded in task history, a table you can query with SQL.

Combine data and AI
in one runtime

Model calls are SQL functions. The engine batches the rows, runs the calls in parallel, and combines the answers with joins, filters, and aggregations over your federated data.

Explore SQL AI functions

One API for
every model

Use an existing OpenAI or Anthropic SDK to call local and hosted models through Spice. If a call fails, Spice tries the next model in the order you set.

Explore models in Spice

An isolated router
for each tenant

Run a router for each app, agent, or tenant, with its own models, keys, and logs. Spice.ai Enterprise adds OIDC sign-in and Cedar policies for datasets, rows, and columns.

Explore authorization policy

Call any model from SQL

Model calls run next to filters, joins, and aggregations. Apps and agents use the same models through the OpenAI-compatible API.

ai() function

ai(): the SQL function for LLMs

Add ai() to any query with a prompt. Spice sends one request for each row, runs them in parallel, and returns each answer as text. To pick a model, pass its name as the second argument.

Explore the ai() function

Call a model from SQL: one query calls ai() with a prompt and the model gpt-6-luna on every row of a reviews table. Spice sends one model call per row, and the calls run in parallel. Each answer returns as text and fills the new summary columnSELECT id, ai('Summarize: ' || review, 'gpt-6-luna') AS summary FROM reviews;idreview101Box was dented102Fits great103Wrong size104Love the colorsummaryDamagePositiveSizing issuePositiveModelgpt-6-lunaOne query calls ai() on every row.Spice sends one model call per row, all at once.Each answer fills the summary column.One model call per row, run in parallel.
Decision functions

Filter, label, and score rows in SQL

Ask a model a typed question about each row. ai_if returns true or false, ai_classify returns one of your labels, and ai_score returns a score. Use them in WHERE, ORDER BY, and SELECT like any SQL function.

Explore decision functions

Text-to-SQL

Native Text-to-SQL generation

Ask a question in plain language through the /v1/nsql API. A model writes the SQL for your datasets, and Spice runs the query and returns the rows.

Explore the text-to-SQL API

Route, govern, and trace every model call

The router runs next to your datasets. SQL queries, model calls, and tool calls share the same API keys and observability.

Routing and fallback

Keep AI features online when a provider fails

In your Spice configuration file (Spicepod), define a worker with several models behind one name. Spice spreads calls across the models by round-robin or by weight, or tries each model in order when a call fails. Apps, agents, and ai() in SQL call the worker by name.

Explore model routing

Keep AI features online when a model fails: an AI agent sends a chat request to the model name router. A Spice worker puts OpenAI, Anthropic, and xAI behind that name in fallback order. OpenAI is rate limited, so Spice sends the call to Anthropic, and the answer goes back to the agentAI agent/v1/chat/completions"model": "router"router1OpenAI2Anthropic3xAIRate limitedAnswerServed byAnthropicAn agent calls one model name: router.A Spice worker puts three models behind it, in order.The first model fails, so Spice tries the next one.The next model answers the same request.Route by order, by weight, or round-robin.
MCP and tool search

Connect agents to your data and tools over MCP

Add MCP servers to your Spicepod as tools. Agents connect to Spice through /v1/mcp and access the MCP server tools alongside the built-in SQL and search tools. Models in Spice call the same tools. With tools: search_registry, a model gets tool_search and tool_invoke, and loads a tool's schema only when the model needs the tool.

Explore MCP in Spice (opens in a new tab)

Tool access and audit

Control and trace every tool call

Choose which tools each model can call with the tools parameter, and cap how many rounds of tool calls one request can make with tool_recursion_limit. Task history records each model call, tool call, and SQL query.

Explore observability

AI sandboxing

AI sandboxing for least-privilege access

Run Spice between models and production databases. A model can query only the datasets, views, and catalogs that your Spicepod defines, with a Spice API key in place of database credentials. In Spice.ai Enterprise, Cedar policies filter rows and mask columns for each user and role.

Explore secure AI sandboxing

Call models from SQL and apps in three steps

An example that labels and summarizes support tickets in one SQL query.

# spicepod.yamlmodels:  - from: openai:gpt-6-luna    name: gpt-6-luna    params:      openai_api_key: ${secrets:OPENAI_API_KEY}datasets:  - from: postgres:public.tickets    name: tickets    params:      pg_host: ${secrets:PG_HOST}      pg_db: support      pg_user: ${secrets:PG_USER}      pg_pass: ${secrets:PG_PASS}sql> SELECT id,            ai_classify(body, ['billing', 'technical', 'other']) AS team,            ai('Summarize in 8 words: ' || body) AS summary     FROM tickets LIMIT 3;# example output101  billing    Customer wants a refund for a double charge102  technical  Login page shows an error after the update103  other      Customer asks how to add a teammate
  1. Add models

    In spicepod.yaml, add a model for each provider, such as openai:gpt-6-luna and anthropic:claude-sonnet-5-5. Spice reads each API key from a secret.

  2. Connect data and route

    Add datasets for the tables that models work on. Add a worker that puts the models behind one name, in fallback order.

  3. Call from SQL or an SDK

    Start Spice with spice run. Call ai() and ai_classify in SQL, or send the worker name as model from an OpenAI or Anthropic SDK.

  1. /plugin marketplace add spiceai/skills
  2. /plugin install spiceai@spiceai

Connect the clients, SDKs, and agents you already use

SQL clients call models in the queries that they send. Apps and agents call the same models through the API, the SDKs, or MCP.

SQL clients
and BI tools

Power BI, Tableau, Apache Superset, DBeaver, and DataGrip connect over Arrow Flight SQL, ADBC, JDBC, or ODBC. The SQL that they send can call ai() and the decision functions.

Explore clients and tools

SDKs for
your apps

Query from code with the Spice SDKs for Python, JavaScript, Go, Rust, Java, and .NET. Call models with the OpenAI or Anthropic SDK, or with the Spice provider for the Vercel AI SDK.

Explore the SDKs

Agents and
coding tools

Connect agents to /v1/mcp for tools and data. Run Claude Code, Codex CLI, GitHub Copilot CLI, or OpenCode on Spice models with spice claude, spice codex, and the other agent commands.

Explore coding agents

Run coding agents on your own router

Claude Code example

An example that runs Claude Code on a router with a hosted model and a local fallback.

# spicepod.yamlmodels:  - from: anthropic:claude-sonnet-5-5    name: claude-sonnet    params:      anthropic_api_key: ${secrets:ANTHROPIC_API_KEY}  - from: huggingface:huggingface.co/mradermacher/Qwen3.8-Flash-Next-GGUF    name: qwen-local  # runs on your hardware with llama.cpp    files:      - path: Qwen3.8-Flash-Next.Q2_K.ggufworkers:  - name: router    load_balance:      routing:        - from: claude-sonnet          order: 1        - from: qwen-local          order: 2  # used when Anthropic fails$ spice claude --model router# Claude Code starts with Spice as its model backend.# Each request goes to /v1/messages on the router worker.
  1. Add models

    Add the models that your coding agents can use, such as anthropic:claude-sonnet-5-5 and a GGUF model from Hugging Face that runs on your own hardware.

  2. Route between them

    Put the models behind a worker. The agent calls router, and Spice sends the request to the local model when Anthropic fails.

  3. Start the agent

    Run spice claude, spice codex, spice copilot, spice opencode, or another agent command. The agent talks to Spice, and the provider keys stay in Spice.

Trusted by developers building production AI

Teams use Spice to add AI to their SQL workflows. They ship faster and run fewer pipelines.

Ramachandra Ramarathinam

“Spice is the data plane behind Summation. Every connector we ship, from Snowflake to a generic REST-as-a-table, collapses into one SQL surface, which is what makes our AI agents portable across a customer's stack.”

Ramachandra Ramarathinam

CTO, Summation

Tim Ottersburg

“Partnering with Spice AI has transformed how NRC Health delivers AI-driven insights. By unifying siloed data across systems, we accelerated AI feature development, reducing time-to-market from months to weeks - and sometimes days. With predictable costs and faster innovation, Spice isn't just solving some of our data and AI challenges - it's helping us redefine personalized healthcare.”

Tim Ottersburg

VP of Technology, NRC Health

FAQs

Answers to common questions about calling LLMs from SQL and about the AI router in Spice

The ai() function is a built-in Spice SQL function that sends a prompt to a chat model and returns the answer as text. Give a model or worker name from your Spicepod as the second argument, such as ai(body, 'gpt-6-luna'). You can omit the name only when the Spicepod has exactly one model. To change the provider, change the model in the Spicepod, and your SQL stays the same. Read the ai() function reference.

Use the decision functions, which return typed values instead of free text. The ai_if function returns a boolean, ai_classify returns one of your labels, and ai_score returns a number on your scale of levels. The ai_probability function returns a probability, and ai_decide answers several questions in one call. These functions take a model name, not a worker. Only TypeSafe decision models, such as Jev, return calibrated probabilities.

Send a question in plain language to the /v1/nsql HTTP API. Spice gives the model the schemas of your datasets, and the model writes a SQL query. Spice runs the query read-only, so the generated SQL cannot change data. The response has the query rows. Send the header Accept: application/sql to get only the SQL.

No. With ai() and the decision functions, the model gets only the input that your query sends. With text-to-SQL, the model gets the schemas of your datasets. It gets sample rows only when you set sample_data_enabled to true. Add only the datasets that a model needs to the Spicepod. Read about secure AI sandboxing.

An AI router, also called an AI gateway, is one API between your apps and many model providers. It sends each call to a model, tries another model when a call fails, and records each call. A self-hosted router runs in your own environment, so provider keys, routing rules, and call records stay there. Spice runs its router inside a SQL query engine, so SQL queries can call the same models.

Yes. Spice gives apps one API for many models, as OpenRouter does, but Spice runs in your own environment. OpenRouter is a hosted service, so apps send each request to the OpenRouter API, which sends it to a model provider. Spice calls the providers that you choose, or models on your own hardware, from your cloud or data center. Both try the next model when a call fails, and Spice also runs model calls inside SQL queries.

Any SQL client that connects over Arrow Flight SQL, ADBC, JDBC, ODBC, or HTTP can call ai() in a query. Apps call /v1/chat/completions and the other OpenAI-compatible APIs with an OpenAI SDK, or with the Vercel AI SDK through the Spice provider. Spice v2.5 adds the Anthropic Messages API on /v1/messages, so Anthropic SDKs and the Claude Agent SDK work with any chat model. The spice claude and spice codex commands run coding agents with Spice as the model backend.

Define a worker in the Spicepod, and list its models under load_balance.routing. Give each model an order for fallback, a weight for weighted routing, or neither for round-robin. With fallback, Spice tries the next model when a call fails, for example on a rate limit. Clients call the worker by its name, as the workers docs show.

Spice reads provider keys from a secret store, such as environment variables, AWS Secrets Manager, or Kubernetes secrets. Clients send Spice API keys, and Spice does not forward those keys to a model provider. Spice.ai Enterprise adds OIDC sign-in (in preview) and Cedar policies. A policy sets which datasets each user or role can query, and it can filter rows and mask columns.

Set tools: search_registry on the model, and add an embedding model to the Spicepod. The model then gets tool_search, tool_invoke, and list_datasets, not the schema of every tool. It searches the registry for the tools that it needs and loads only their schemas. The registry indexes built-in tools, MCP tools, and Spicepod functions, as the tool registry docs describe.

Spice gives you two ways to use an LLM with your data. The ai() SQL function sends text to a model and returns the answer as a column. The /v1/nsql API turns a question in plain language into SQL and runs it. Both use the models in your spicepod.yaml file:

  1. Add a model: list a chat model under models. The from value names the provider and the model, such as openai:gpt-6-luna.
  2. Add data: list the datasets that the model can use under datasets.
  3. Call the model: use ai() or a decision function in a SQL query, or send a question to /v1/nsql.

The following Spicepod adds an OpenAI model and a table of support tickets from PostgreSQL:

version: v1
kind: Spicepod
name: support-insights

models:
  - from: openai:gpt-6-luna
    name: gpt-6-luna
    params:
      openai_api_key: ${secrets:OPENAI_API_KEY}

datasets:
  - from: postgres:public.tickets
    name: tickets
    params:
      pg_host: ${secrets:PG_HOST}
      pg_db: support
      pg_user: ${secrets:PG_USER}
      pg_pass: ${secrets:PG_PASS}

Start the runtime with spice run. Then summarize and label each new ticket in one query:

SELECT id,
       ai('Summarize this ticket in one sentence: ' || body) AS summary,
       ai_classify(body, ['billing', 'bug', 'question']) AS category
FROM tickets
WHERE created_at > now() - INTERVAL '1 day';

Or ask a question in plain language:

curl http://localhost:8090/v1/nsql \
  -H 'Content-Type: application/json' \
  -d '{"query": "How many tickets were opened each day last week?"}'

Read the ai() function reference and the /v1/nsql API reference for all options.

Questionai() SQL functionText-to-SQL (/v1/nsql)
What is the input?A SQL query that calls ai(prompt) or ai(prompt, model)A question in plain language
What does the model do?Answers the prompt for each rowWrites one SQL query
What do you get back?A text column in the query resultThe query rows, or the SQL only
Where do you call it?Any Spice SQL interface, such as HTTP, Arrow Flight SQL, or ADBCThe HTTP API on port 8090
When do you use it?Summaries, labels, translations, and extractionQuestions from people who do not write SQL

To get only the generated SQL from /v1/nsql, send the header Accept: application/sql.

You can call any model that you add to the models section of your Spicepod, through the API or from SQL. The ai() function needs a chat model, and the decision functions take a chat model or a TypeSafe decision model. Set the provider with the prefix of the from value in each model:

PrefixProvider
openaiOpenAI, or an OpenAI-compatible server such as vLLM, Groq, or NVIDIA NIM
azureAzure OpenAI
anthropicAnthropic
bedrockAmazon Bedrock
googleGemini models on Google Vertex AI
xaixAI
databricksDatabricks model serving
spice.aiThe Spice.ai Cloud Platform, or another Spice runtime
huggingfaceModels from Hugging Face that run in the Spice runtime
fileModel files on local disk that run in the Spice runtime
typesafeTypeSafe decision models, such as Jev

To use an OpenAI-compatible server, set the endpoint parameter of an openai model to that server. Spice v2.5 serves local GGUF models with llama.cpp. Read the models guide for the parameters of each provider, and the AI model serving page.

Spice calls the model one time for each row that ai() gets with a prompt that is not NULL. It runs the calls in parallel and returns the answers in row order. Know these limits before you run ai() on a large table:

  • Batches: Spice splits the input into batches of up to 1,000 rows, so a query can process any number of rows. A LIMIT stops model calls only between batches, so use a filter to limit the rows that a query sends.
  • Message size: one message can be a maximum of 1 MB.
  • NULL input: a NULL prompt returns NULL, and Spice does not call the model.
  • Errors: if one model call fails, the full query fails. The decision functions accept on_error => 'null' to return NULL for that row instead.

A hosted provider, such as OpenAI, can charge for the tokens of each call. A local Hugging Face or file model uses the compute of the Spice runtime. Test a prompt on a small, filtered set of rows before you run it on a full table.

See Spice in action

Walk through your use case with an engineer and see how Spice handles federation, acceleration, and AI integration for production workloads.

Talk to an engineer (opens in a new tab)