Lakebase Postgres is built on object storage, but 99.99999% of reads are served from high-performance local caches
Function templates

TanStack AI on AI Gateway

Streaming chat with tool calling, structured extraction, and summaries with TanStack AI on Neon AI Gateway.

About this template

This Neon Function runs TanStack AI on Neon AI Gateway. The @tanstack/ai-neon adapter reaches every model in the gateway catalog with the branch's own credentials, so you don't need a provider API key.

  • Stream a chatRecommended

    POST the AG-UI body that useChat sends to stream a reply over SSE, with a sample server tool.

    /chat

  • Extract structured dataRecommended

    POST text to get a typed JSON object validated against a Zod schema.

    /extract

  • Summarize text

    POST text and an optional style and maxLength to get a summary.

    /summarize

Scaffold it

Install the latest Neon CLI, then create the function from the registry:

npm install -g neon@latest
neon login
neon link
neon functions new tanstack-ai

The CLI asks which routes to include, and --all-operations includes /summarize too. It writes the modules and a router index.ts to functions/tanstackai/ and declares the function in neon.ts.

Enable AI Gateway on the linked branch:

neon config add ai-gateway

You can also set aiGateway: true in neon.ts. AI Gateway requires a paid Neon plan with prepaid credits and a project in a supported region. See the AI Gateway quickstart.

Function URLs are public, so every route requires a bearer token. Generate one and add it to .env.local:

echo "TANSTACK_AI_FUNCTION_TOKEN=$(openssl rand -hex 32)" >> .env.local
VariableDescription
TANSTACK_AI_FUNCTION_TOKENRandom token (at least 32 characters, for example from openssl rand -hex 32) callers send as Authorization: Bearer <token>; required because Neon Function URLs are public.

Deploy once so Neon provisions the gateway and pulls NEON_AI_GATEWAY_BASE_URL and NEON_AI_GATEWAY_TOKEN into .env.local:

neon deploy --env .env.local

Run locally

neon dev

neon dev loads .env.local, injects the branch's AI Gateway credentials, and prints the URL to call. The examples below use $URL for that URL and $TOKEN for your TANSTACK_AI_FUNCTION_TOKEN.

Chat

/chat takes an AG-UI RunAgentInput body with threadId, runId, messages, tools, and context. useChat sends this body for you, and with curl it looks like this:

curl -N "$URL/chat" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "threadId": "thread-1",
    "runId": "run-1",
    "messages": [{ "id": "m1", "role": "user", "content": "What time is it in Berlin?" }],
    "tools": [],
    "context": []
  }'

The response is a stream of AG-UI events (RUN_STARTED, TOOL_CALL_START, TOOL_CALL_RESULT, TEXT_MESSAGE_CONTENT, RUN_FINISHED, and so on).

From a React app, point useChat at the route:

import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";

const { messages, sendMessage } = useChat({
  threadId: "thread-1",
  connection: fetchServerSentEvents(`${FUNCTION_URL}/chat`, async () => ({
    headers: { Authorization: `Bearer ${await getToken()}` },
  })),
});

/chat answers CORS preflight requests from any origin, because the bearer token grants access whatever the origin.

Extract

curl "$URL/extract" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "text": "Ada Lovelace joined Neon in London on March 3, 2026. Great news!" }'

Example response:

{
  "data": {
    "title": "Ada Lovelace joins Neon",
    "people": ["Ada Lovelace"],
    "organizations": ["Neon"],
    "locations": ["London"],
    "dates": ["March 3, 2026"],
    "sentiment": "positive"
  },
  "model": "claude-haiku-5-5"
}

text can be up to 20,000 characters. Change ExtractionSchema in extract.ts to extract the fields your app needs.

Summarize

curl "$URL/summarize" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "text": "...", "style": "bullet-points", "maxLength": 300 }'

style is paragraph (the default), bullet-points, or concise. maxLength is the token budget the function asks the model to stay under, from 100 to 2,000, with a default of 300. Models often run a little over it, so the hard output limit is twice maxLength, and a summary cut off at that limit returns 502. The response is { "summary", "model", "usage" }.

Errors

StatusMeaning
400The body is not JSON or fails validation.
401The bearer token is missing or wrong.
405The method is not POST.
429AI Gateway rate limit or daily spend cap reached.
502The model request failed, or AI Gateway rejected the branch credentials.
503TANSTACK_AI_FUNCTION_TOKEN is unset or shorter than 32 characters, or AI Gateway is not enabled.

/chat returns 200 as soon as the stream starts. A model error after that arrives as a RUN_ERROR event in the stream, which useChat exposes as error.

Customize

  • Model. Every module sets MODEL = "claude-haiku-5-5". You can use any text model from the AI Gateway catalog, and the adapter picks the gateway route for it. Claude 5.5 models reject temperature and topP, so the template doesn't set them.
  • Prompt and tools. Edit SYSTEM_PROMPT and the tools array in chat.ts. Each tool is a toolDefinition() with a Zod input schema and a .server() implementation that runs inside the function. See TanStack AI tools.
  • Auth. The shared token is for scripts and backend callers and doesn't belong in a browser bundle. For browser apps, verify a short-lived Neon Auth JWT instead. fetchServerSentEvents takes an async options function, so the client can fetch a fresh token for each request.