diff --git a/crates/alien-cli/src/commands/init.rs b/crates/alien-cli/src/commands/init.rs index e229d7766..f7079e42f 100644 --- a/crates/alien-cli/src/commands/init.rs +++ b/crates/alien-cli/src/commands/init.rs @@ -66,6 +66,10 @@ const KNOWN_TEMPLATES: &[(&str, &str)] = &[ "ai-quickstart-ts", "The smallest AI setup: one worker calling cloud LLMs, no API keys, no database.", ), + ( + "ai-chatbot-ts", + "A streaming AI chatbot that answers questions about a private Postgres.", + ), ]; fn fallback_templates() -> Vec { diff --git a/examples/README.md b/examples/README.md index 19a612e0a..b08165d80 100644 --- a/examples/README.md +++ b/examples/README.md @@ -12,6 +12,8 @@ Each example is a self-contained template you can initialize with `alien init`. | [event-pipeline-ts](./event-pipeline-ts) | Process events from queues, storage changes, and cron schedules. | TypeScript | | [webhook-api-ts](./webhook-api-ts) | Receive webhooks and expose an API inside the customer's cloud. | TypeScript | | [nextjs-app](./nextjs-app) | Deploy a Next.js app as a single container in the customer's cloud. | TypeScript | +| [ai-quickstart-ts](./ai-quickstart-ts) | The smallest AI setup: one worker calling cloud LLMs, no API keys, no database. | TypeScript | +| [ai-chatbot-ts](./ai-chatbot-ts) | A streaming AI chatbot that answers questions about a private Postgres. | TypeScript | ## Getting started diff --git a/examples/ai-chatbot-ts/.dockerignore b/examples/ai-chatbot-ts/.dockerignore new file mode 100644 index 000000000..c4946c1ae --- /dev/null +++ b/examples/ai-chatbot-ts/.dockerignore @@ -0,0 +1,8 @@ +node_modules +.next +.git +.alien +alien.ts +template.toml +README.md +.env*.local diff --git a/examples/ai-chatbot-ts/.gitignore b/examples/ai-chatbot-ts/.gitignore new file mode 100644 index 000000000..330682341 --- /dev/null +++ b/examples/ai-chatbot-ts/.gitignore @@ -0,0 +1,18 @@ +# Node +node_modules/ +package-lock.json +pnpm-lock.yaml + +# Next.js +.next/ +next-env.d.ts +*.tsbuildinfo + +# Alien +.alien/ + +# Env +.env*.local + +# OS +.DS_Store diff --git a/examples/ai-chatbot-ts/Dockerfile b/examples/ai-chatbot-ts/Dockerfile new file mode 100644 index 000000000..f61d94ae6 --- /dev/null +++ b/examples/ai-chatbot-ts/Dockerfile @@ -0,0 +1,24 @@ +# The bindings addon ships glibc-only prebuilds built against glibc 2.39, so the +# base must be glibc >= 2.39 in both stages: alpine (musl) cannot install them and +# bookworm (2.36) cannot load them. +FROM node:22-trixie-slim AS build +WORKDIR /app +COPY package.json package-lock.json* ./ +RUN npm install +COPY . . +RUN npm run build + +FROM node:22-trixie-slim +WORKDIR /app +ENV NODE_ENV=production +# .next/static and public are not part of the standalone output and must be +# copied alongside it for server.js to serve them. +COPY --from=build --chown=node:node /app/.next/standalone ./ +COPY --from=build --chown=node:node /app/.next/static ./.next/static +COPY --from=build --chown=node:node /app/public ./public +# The base image's unprivileged account, so a compromised server is not root. +USER node +ENV HOSTNAME=0.0.0.0 +ENV PORT=3000 +EXPOSE 3000 +CMD ["node", "server.js"] diff --git a/examples/ai-chatbot-ts/README.md b/examples/ai-chatbot-ts/README.md new file mode 100644 index 000000000..638ad81e7 --- /dev/null +++ b/examples/ai-chatbot-ts/README.md @@ -0,0 +1,52 @@ +# AI Chatbot + +A streaming chatbot that answers questions about a private Postgres through a tool. The model is served by the deployment's own cloud and the database is reachable only from inside the stack, so there are no API keys and no database credentials in the app. + +The app builds with the included Dockerfile (Next.js [standalone output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output)) and runs as a single container behind an HTTPS load balancer. + +## What's included + +| Resource | Type | Description | +|----------|------|-------------| +| `app` | Container | The Next.js chat app, built from the Dockerfile and exposed over HTTP | +| `llm` | AI (live) | Model-less AI resource; the gateway serves it from the deployment's cloud | +| `db` | Postgres (live) | Private database, reachable only from same-stack workloads | + +## How it works + +- `alien.ts` links both resources to the container, so Alien grants the workload `ai/invoke` and `postgres/data-access` and injects `ALIEN_LLM_BINDING` and `ALIEN_DB_BINDING`. +- `app/api/chat/route.ts` resolves the model endpoint with `getAiConnection("llm")` and streams with the Vercel AI SDK. On a cloud the binding routes through Alien's embedded gateway, which injects the workload's ambient credential; on `alien dev` it carries your own provider key and the app calls the provider directly. +- The gateway forwards each model to its own upstream wire format instead of translating, so the route picks the client to match: Claude models get the Anthropic client, everything else the OpenAI-compatible one. Both take the same `baseURL` and the same binding. +- The `queryDatabase` tool takes a question name and a few filters, never SQL. `app/queries.ts` holds the seven statements it can run and binds the model's arguments as parameters, so the model chooses *which* question to ask and the app owns what actually reaches the database. It reads the connection with `postgres("db").connection()`, which resolves the password at runtime under the workload's own identity. +- `app/api/models/route.ts` calls `ai("llm").getAvailableModels()`, so the picker lists only the models this cloud has enabled. +- **See the data** in the header opens a drawer over the chat with the demo tables, read through the same read-only pool, so an answer can be checked against the rows it came from. + +## Local development + +Bring your own provider key -- locally there is no cloud identity, so the SDK uses the key directly (a BYO-key binding) instead of the gateway: + +```bash +OPENAI_API_KEY=sk-... alien dev +``` + +Open the printed URL and ask a data question, e.g. *"How many enterprise customers do we have and what's the total MRR?"* The model calls `queryDatabase` and summarizes the result. The demo tables are created and filled on the first question, so there is nothing to seed by hand. + +## Deploying + +```bash +alien deploy production --platform aws # or gcp / azure +``` + +Alien builds the container image from the Dockerfile, pushes it, and provisions the compute, the database, and the load balancer. The deploy output prints the public URL. + +That URL is open, so anyone who has it can ask questions and spend model quota. It is what makes the example something you can click and try, but a real deployment should put authentication and a per-caller rate limit in front of `/api/chat`. + +## Model availability + +`getAvailableModels()` returns what is enabled on your deployment's cloud right now. Open-weight models work out of the box; Claude needs a one-time activation first -- the Anthropic use-case form on AWS Bedrock, Model Garden on GCP Vertex, or Marketplace terms on Azure AI Foundry. Until then it simply does not appear in the picker, and every other model keeps working. + +## Learn more + +- [Postgres reference](https://alien.dev/docs/infrastructure/postgres) +- [Container reference](https://alien.dev/docs/infrastructure/container) +- [Stacks](https://alien.dev/docs/stacks) diff --git a/examples/ai-chatbot-ts/alien.ts b/examples/ai-chatbot-ts/alien.ts new file mode 100644 index 000000000..40f712ddd --- /dev/null +++ b/examples/ai-chatbot-ts/alien.ts @@ -0,0 +1,38 @@ +import * as alien from "@alienplatform/core" + +// A model-less AI resource. The customer's cloud serves the inference; the +// embedded gateway injects the workload's ambient identity, so no API keys. +const llm = new alien.AI("llm").build() + +// A private Postgres, reachable only from same-stack workloads; the app resolves +// its connection at runtime from the binding, never from a checked-in secret. +const db = new alien.Postgres("db").build() + +const app = new alien.Container("app") + .code({ type: "source", src: ".", toolchain: { type: "docker", dockerfile: "Dockerfile" } }) + .cpu(0.5) + .memory("512Mi") + .port(3000) + .publicEndpoint("web", 3000, "http") + // Next's standalone server reads these; HOSTNAME=0.0.0.0 binds all interfaces. + .environment({ PORT: "3000", HOSTNAME: "0.0.0.0" }) + // Linking injects ALIEN_LLM_BINDING (and starts the gateway, exposed as + // ALIEN_AI_GATEWAY_URL) and ALIEN_DB_BINDING (the Postgres connection). + .link(llm) + .link(db) + .permissions("app") + .build() + +export default new alien.Stack("ai-chatbot") + .platforms(["aws", "gcp", "azure"]) + .add(llm, "live") + .add(db, "live") + .add(app, "live") + .permissions({ + profiles: { + app: { + "*": ["ai/invoke", "postgres/data-access"], + }, + }, + }) + .build() diff --git a/examples/ai-chatbot-ts/app/api/chat/route.ts b/examples/ai-chatbot-ts/app/api/chat/route.ts new file mode 100644 index 000000000..29d076983 --- /dev/null +++ b/examples/ai-chatbot-ts/app/api/chat/route.ts @@ -0,0 +1,74 @@ +import { createAnthropic } from "@ai-sdk/anthropic" +import { createOpenAICompatible } from "@ai-sdk/openai-compatible" +import { type AiConnection, ai, getAiConnection } from "@alienplatform/sdk" +import { type UIMessage, convertToModelMessages, stepCountIs, streamText, tool } from "ai" +import { query } from "../../db" +import { type Ask, askSchema, plan, supportedFilters, unsupportedFilters } from "../../queries" +import { ensureSeeded } from "../../seed" + +// The gateway forwards each model to its own upstream wire format rather than +// translating, so Claude needs the Anthropic client and everything else OpenAI. +// The catalog (alien-core's ai_catalog.rs) owns which is which. +function modelFor(modelId: string, connection: AiConnection) { + if (modelId.startsWith("claude")) { + const anthropic = createAnthropic({ + baseURL: connection.baseURL, + // An ambient binding has no client key — the gateway signs with the workload's + // own credential — and the empty string also keeps a stray ANTHROPIC_API_KEY in + // the environment from being picked up and sent to it. + apiKey: connection.apiKey ?? "", + }) + return anthropic(modelId) + } + return createOpenAICompatible({ name: "alien", ...connection })(modelId) +} + +const queryDatabase = tool({ + description: + "Answer a question about the company's Postgres data. Pick the question that fits and " + + "narrow it with the optional filters. Data: customers (name, plan, country, monthly " + + "recurring revenue) and their orders (amount, status, date).", + inputSchema: askSchema, + execute: async (ask: Ask) => { + const ignored = unsupportedFilters(ask) + if (ignored.length > 0) { + const takes = supportedFilters(ask.question) + return { + error: `${ask.question} does not take ${ignored.join(" or ")}; it takes ${ + takes.length > 0 ? takes.join(" and ") : "no filters" + }`, + } + } + await ensureSeeded() + const { text, values } = plan(ask) + const { rows } = await query(text, values) + return { question: ask.question, rows, rowCount: rows.length } + }, +}) + +export async function POST(req: Request) { + const { messages, model }: { messages: UIMessage[]; model?: string } = await req.json() + + // Model ids differ per cloud, so the fallback is the binding's first model, not a hardcoded id. + const modelId = model || (await ai("llm").getAvailableModels())[0]?.id + if (!modelId) { + return Response.json({ error: "the AI binding exposes no models" }, { status: 503 }) + } + + // Resolved per request: the binding env exists only in the running workload, not at build. + const connection = await getAiConnection("llm") + + const result = streamText({ + model: modelFor(modelId, connection), + system: + "You answer questions about the company's data. When a question needs data, call the " + + "queryDatabase tool and summarize what comes back in plain English. If no question in " + + "the tool covers what was asked, say what the data can and cannot answer.", + messages: await convertToModelMessages(messages), + // Without a stop condition the model never streams the answer after the tool result. + stopWhen: stepCountIs(6), + tools: { queryDatabase }, + }) + + return result.toUIMessageStreamResponse() +} diff --git a/examples/ai-chatbot-ts/app/api/models/route.ts b/examples/ai-chatbot-ts/app/api/models/route.ts new file mode 100644 index 000000000..da57ccb04 --- /dev/null +++ b/examples/ai-chatbot-ts/app/api/models/route.ts @@ -0,0 +1,6 @@ +import { ai } from "@alienplatform/sdk" + +export async function GET() { + const models = await ai("llm").getAvailableModels() + return Response.json({ models: models.map(m => m.id) }) +} diff --git a/examples/ai-chatbot-ts/app/api/tables/route.ts b/examples/ai-chatbot-ts/app/api/tables/route.ts new file mode 100644 index 000000000..cf5f49427 --- /dev/null +++ b/examples/ai-chatbot-ts/app/api/tables/route.ts @@ -0,0 +1,21 @@ +import { query } from "../../db" +import { ensureSeeded } from "../../seed" + +const TABLES = ["customers", "orders"] as const +const PREVIEW_ROWS = 8 + +/** The demo tables behind the chat, so the answers can be checked against the data. */ +export async function GET() { + await ensureSeeded() + + const tables = await Promise.all( + TABLES.map(async name => { + // The identifiers are this module's own constants, never request input. + const rows = await query(`select * from ${name} order by id limit ${PREVIEW_ROWS}`) + const total = await query(`select count(*)::int as count from ${name}`) + return { name, rows: rows.rows, total: total.rows[0].count as number } + }), + ) + + return Response.json({ tables }) +} diff --git a/examples/ai-chatbot-ts/app/components/data-drawer.tsx b/examples/ai-chatbot-ts/app/components/data-drawer.tsx new file mode 100644 index 000000000..ecce015da --- /dev/null +++ b/examples/ai-chatbot-ts/app/components/data-drawer.tsx @@ -0,0 +1,171 @@ +"use client" + +import { useEffect, useRef, useState } from "react" +import { Spinner } from "./spinner" + +type Table = { name: string; rows: Record[]; total: number } + +/** The tables the model queries, so an answer can be checked against the data. */ +export function DataDrawer() { + const [open, setOpen] = useState(false) + const [tables, setTables] = useState(null) + const [failed, setFailed] = useState(false) + + useEffect(() => { + if (!open || tables || failed) return + fetch("/api/tables") + .then(r => r.json()) + .then((d: { tables: Table[] }) => setTables(d.tables)) + .catch(() => setFailed(true)) + }, [open, tables, failed]) + + // showModal() is what puts the dialog in the top layer, above every stacking + // context on the page, and brings Escape and the backdrop with it. + const dialogRef = useRef(null) + useEffect(() => { + const dialog = dialogRef.current + if (!dialog) return + if (open && !dialog.open) dialog.showModal() + if (!open && dialog.open) dialog.close() + }, [open]) + + return ( + <> + + + {/* biome-ignore lint/a11y/useKeyWithClickEvents: Escape is the keyboard path, via onCancel */} + setOpen(false)} + onCancel={() => setOpen(false)} + // The backdrop belongs to the dialog, so a click on it targets the dialog + // itself; anything inside targets a child. + onClick={e => e.target === dialogRef.current && setOpen(false)} + className="my-0 ml-auto mr-0 h-dvh max-h-none w-full max-w-lg bg-transparent p-0 backdrop:bg-black/60 backdrop:backdrop-blur-[2px] open:motion-safe:animate-[slide-in_220ms_cubic-bezier(0.32,0.72,0,1)]" + > + {open && ( +
+
+
+

+ The data behind the answers +

+

+ Read from the stack's private Postgres through the same read-only connection the + model's tool uses. +

+
+ +
+ +
+ {failed && ( +

Could not read the tables.

+ )} + {!tables && !failed && ( +
+ + Reading +
+ )} + {tables?.map(table => ( + + ))} +
+
+ )} +
+ + ) +} + +// A `date` column arrives as a full ISO timestamp once it has been through JSON; +// the day is the only part the demo data carries. +function cell(value: unknown): string { + const text = String(value ?? "") + return /^\d{4}-\d{2}-\d{2}T00:00:00/.test(text) ? text.slice(0, 10) : text +} + +function TableCard({ table }: { table: Table }) { + const columns = table.rows.length > 0 ? Object.keys(table.rows[0]) : [] + const numeric = new Set(columns.filter(c => typeof table.rows[0]?.[c] === "number")) + + return ( +
+
+ + {table.name} + + + {table.total} {table.total === 1 ? "row" : "rows"} + +
+
+ + + + {columns.map(column => ( + + ))} + + + + {table.rows.map(row => ( + + {columns.map(column => ( + + ))} + + ))} + +
+ {column} +
+ {cell(row[column])} +
+ {table.total > table.rows.length && ( +
+ +{table.total - table.rows.length} more +
+ )} +
+
+ ) +} + +function CloseIcon() { + return ( + + ) +} diff --git a/examples/ai-chatbot-ts/app/components/grain-background.tsx b/examples/ai-chatbot-ts/app/components/grain-background.tsx new file mode 100644 index 000000000..bf9c9e00c --- /dev/null +++ b/examples/ai-chatbot-ts/app/components/grain-background.tsx @@ -0,0 +1,37 @@ +"use client" + +import dynamic from "next/dynamic" + +const GrainGradient = dynamic( + () => import("@paper-design/shaders-react").then(mod => mod.GrainGradient), + { ssr: false, loading: () => }, +) + +export function GrainBackground() { + return ( +
+ + +
+ ) +} + +function Fallback() { + return ( +
+ ) +} diff --git a/examples/ai-chatbot-ts/app/components/message.tsx b/examples/ai-chatbot-ts/app/components/message.tsx new file mode 100644 index 000000000..61611c89e --- /dev/null +++ b/examples/ai-chatbot-ts/app/components/message.tsx @@ -0,0 +1,59 @@ +"use client" + +import type { UIMessage } from "ai" +import ReactMarkdown from "react-markdown" +import remarkGfm from "remark-gfm" +import { QueryCard, type QueryInput, type QueryOutput } from "./query-card" + +type QueryToolPart = { + type: "tool-queryDatabase" + toolCallId: string + state: "input-streaming" | "input-available" | "output-available" | "output-error" + input?: QueryInput + output?: QueryOutput + errorText?: string +} + +export function Message({ message }: { message: UIMessage }) { + if (message.role === "user") { + const text = message.parts.map(part => (part.type === "text" ? part.text : "")).join("") + return ( +
+
+ {text} +
+
+ ) + } + + return ( +
+ {message.parts.map((part, i) => { + const key = `${message.id}-${i}` + if (part.type === "text") { + return ( +
+ {part.text} +
+ ) + } + if (part.type === "tool-queryDatabase") { + const tool = part as unknown as QueryToolPart + return ( + + ) + } + return null + })} +
+ ) +} diff --git a/examples/ai-chatbot-ts/app/components/query-card.tsx b/examples/ai-chatbot-ts/app/components/query-card.tsx new file mode 100644 index 000000000..e9804fe23 --- /dev/null +++ b/examples/ai-chatbot-ts/app/components/query-card.tsx @@ -0,0 +1,124 @@ +"use client" + +import { Spinner } from "./spinner" + +const PREVIEW_ROWS = 5 + +export type QueryInput = { question?: string; plan?: string; status?: string } +export type QueryOutput = { + rowCount?: number | null + rows?: Record[] + error?: string +} + +export function QueryCard({ + state, + input, + output, + errorText, +}: { + state: "input-streaming" | "input-available" | "output-available" | "output-error" + input?: QueryInput + output?: QueryOutput + errorText?: string +}) { + const running = state === "input-streaming" || state === "input-available" + const failure = + state === "output-error" ? (errorText ?? "The query could not be run.") : output?.error + const call = input?.question && describe(input) + const rows = output?.rows ?? [] + const columns = rows.length > 0 ? Object.keys(rows[0]) : [] + const numeric = new Set(columns.filter(column => typeof rows[0]?.[column] === "number")) + + return ( +
+
+ + + {running ? "Querying the database" : failure ? "Query failed" : "Queried the database"} + + {running && } + {typeof output?.rowCount === "number" && ( + + {output.rowCount} {output.rowCount === 1 ? "row" : "rows"} + + )} +
+ + {call && ( +
+          {call}
+        
+ )} + + {failure &&
{failure}
} + + {columns.length > 0 && ( +
+ + + + {columns.map(column => ( + + ))} + + + + {rows.slice(0, PREVIEW_ROWS).map((row, i) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: static preview slice with no stable row id + + {columns.map(column => ( + + ))} + + ))} + +
+ {column} +
+ {String(row[column] ?? "")} +
+ {rows.length > PREVIEW_ROWS && ( +
+ +{rows.length - PREVIEW_ROWS} more +
+ )} +
+ )} +
+ ) +} + +function describe({ question, plan, status }: QueryInput): string { + const filters = [plan && `plan=${plan}`, status && `status=${status}`].filter(Boolean) + return [question, ...filters].join(" · ") +} + +function DatabaseIcon() { + return ( + + ) +} diff --git a/examples/ai-chatbot-ts/app/components/spinner.tsx b/examples/ai-chatbot-ts/app/components/spinner.tsx new file mode 100644 index 000000000..cd8c05e91 --- /dev/null +++ b/examples/ai-chatbot-ts/app/components/spinner.tsx @@ -0,0 +1,18 @@ +"use client" + +import { useEffect, useState } from "react" + +const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] + +export function Spinner({ className }: { className?: string }) { + const [frame, setFrame] = useState(0) + useEffect(() => { + const timer = setInterval(() => setFrame(f => (f + 1) % FRAMES.length), 80) + return () => clearInterval(timer) + }, []) + return ( + + ) +} diff --git a/examples/ai-chatbot-ts/app/db.ts b/examples/ai-chatbot-ts/app/db.ts new file mode 100644 index 000000000..ae24886a3 --- /dev/null +++ b/examples/ai-chatbot-ts/app/db.ts @@ -0,0 +1,44 @@ +import { postgres } from "@alienplatform/sdk" +import { Pool, type QueryResult } from "pg" +import { ensureSeeded, forgetSeeded } from "./seed" + +const UNDEFINED_TABLE = "42P01" + +let pool: Promise | undefined + +export async function query(text: string, values: unknown[] = []): Promise { + const run = async () => (await queryPool()).query(text, values) + try { + return await run() + } catch (err) { + if ((err as { code?: string }).code !== UNDEFINED_TABLE) throw err + forgetSeeded() + await ensureSeeded() + return run() + } +} + +/** The read-only pool every query in the app goes through. */ +export function queryPool(): Promise { + if (!pool) { + pool = (async () => { + const conn = await postgres("db").connection() + // Field style + conn.ssl, NOT conn.connectionString: node-postgres parses the + // URL's sslmode and overrides ssl, which breaks the managed-cloud cert path. + return new Pool({ + host: conn.host, + port: conn.port, + database: conn.database, + user: conn.username, + password: conn.password, + ssl: conn.ssl, + options: "-c default_transaction_read_only=on -c statement_timeout=10000", + }) + })().catch(err => { + // Don't cache a failed resolution; let the next request retry. + pool = undefined + throw err + }) + } + return pool +} diff --git a/examples/ai-chatbot-ts/app/globals.css b/examples/ai-chatbot-ts/app/globals.css new file mode 100644 index 000000000..2315351cb --- /dev/null +++ b/examples/ai-chatbot-ts/app/globals.css @@ -0,0 +1,27 @@ +@import "tailwindcss"; +@plugin "@tailwindcss/typography"; + +@theme { + --font-sans: var(--font-geist-sans); + --font-mono: var(--font-geist-mono); + --color-brand: #5aff75; + --color-brand-200: #7dff93; + --color-brand-foreground: #021a06; + --color-landing-foreground: #d0e4d3; + --color-landing-foreground-200: #7eb78a; + --color-card: color-mix(in oklab, #27272a 55%, #000); + --color-edge: rgb(255 255 255 / 7.5%); +} + +/* The data drawer's entrance; Tailwind ships no slide-from-edge keyframe. */ +@keyframes slide-in { + from { + transform: translateX(100%); + } +} + +@keyframes fade-in { + from { + opacity: 0; + } +} diff --git a/examples/ai-chatbot-ts/app/layout.tsx b/examples/ai-chatbot-ts/app/layout.tsx new file mode 100644 index 000000000..4050f81de --- /dev/null +++ b/examples/ai-chatbot-ts/app/layout.tsx @@ -0,0 +1,18 @@ +import { GeistMono } from "geist/font/mono" +import { GeistSans } from "geist/font/sans" +import type { Metadata } from "next" +import type { ReactNode } from "react" +import "./globals.css" + +export const metadata: Metadata = { + title: "AI chatbot on Alien", + description: "A streaming chatbot that talks to cloud LLMs through the Alien AI gateway.", +} + +export default function RootLayout({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} diff --git a/examples/ai-chatbot-ts/app/page.tsx b/examples/ai-chatbot-ts/app/page.tsx new file mode 100644 index 000000000..c27ca8e78 --- /dev/null +++ b/examples/ai-chatbot-ts/app/page.tsx @@ -0,0 +1,211 @@ +"use client" + +import { useChat } from "@ai-sdk/react" +import { useEffect, useRef, useState } from "react" +import { DataDrawer } from "./components/data-drawer" +import { GrainBackground } from "./components/grain-background" +import { Message } from "./components/message" +import { Spinner } from "./components/spinner" + +// Matched to the seeded dataset so first-run questions land. +const SUGGESTIONS = [ + "How many enterprise customers do we have and what's their total MRR?", + "Who are our top 5 customers by MRR?", + "How many orders are pending, and what are they worth?", + "Break down our customers by country.", +] + +export default function Chat() { + const [input, setInput] = useState("") + const [models, setModels] = useState([]) + const [model, setModel] = useState("") + const { messages, sendMessage, status, stop, error, regenerate } = useChat() + const bottomRef = useRef(null) + const composerRef = useRef(null) + + const busy = status === "submitted" || status === "streaming" + + useEffect(() => { + fetch("/api/models") + .then(r => r.json()) + .then((d: { models: string[] }) => { + setModels(d.models) + if (d.models[0]) setModel(d.models[0]) + }) + .catch(() => {}) + }, []) + + // biome-ignore lint/correctness/useExhaustiveDependencies: scroll on every stream update + useEffect(() => { + bottomRef.current?.scrollIntoView({ behavior: "smooth" }) + }, [messages]) + + function ask(text: string) { + // Before the picker loads, omit the field and let the server pick a default. + sendMessage({ text }, { body: { model: model || undefined } }) + composerRef.current?.focus() + } + + function submit() { + const text = input.trim() + if (!text || busy) return + ask(text) + setInput("") + } + + return ( +
+ +
+
+ +
+
+ {messages.length === 0 ? ( +
+
+
+ LIVE + AI connected to a private Postgres +
+

+ Ask your data anything. +

+

+ Answers come from live SQL against the stack's private Postgres, with no + credentials in the app. +

+
+
+ {SUGGESTIONS.map(suggestion => ( + + ))} +
+
+ ) : ( +
+ {messages.map(message => ( + + ))} + {status === "submitted" && ( +
+ + Thinking +
+ )} + {error && ( +
+ Something went wrong.{" "} + +
+ )} +
+ )} +
+
+
+ +