Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 9
feat(examples): add an AI chatbot example over a private Postgres#271
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
387c6521a330e81b42749eba824803af8c914cfcfb5b3ccf7c790edafd8d43647ff8a611615e0File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -56,5 +56,10 @@ | ||
| "formatter": { | ||
| "trailingCommas": "none" | ||
| } | ||
| }, | ||
| "css": { | ||
| "parser": { | ||
| "tailwindDirectives": true | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| node_modules | ||
| .next | ||
| .git | ||
| .alien | ||
| alien.ts | ||
| template.toml | ||
| README.md | ||
| .env*.local |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"] | ||
greptile-apps[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| 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) | ||
| // Unauthenticated on purpose, which is what makes the demo clickable; see the note | ||
| // above POST in app/api/chat/route.ts for what a real deployment owes this endpoint. | ||
| .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() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import { createAnthropic } from "@ai-sdk/anthropic" | ||
| import { createOpenAICompatible } from "@ai-sdk/openai-compatible" | ||
| import { type AiConnection, ai, getAiConnection } from "@alienplatform/sdk" | ||
| import { convertToModelMessages, stepCountIs, streamText, tool, type UIMessage } 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 } | ||
| }, | ||
| }) | ||
| // Open on purpose: clicking the deployed URL and asking a question is the example. The cost is | ||
| // that anyone holding the URL spends the deployment's model quota, so a real app puts | ||
| // authentication and a per-caller rate limit here. README, "Deploying". | ||
| export async function POST(req: Request) { | ||
greptile-apps[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| 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() | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) }) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() { | ||
ItamarZand88 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| 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 }) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.