-
Notifications
You must be signed in to change notification settings - Fork 8
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
Open
ItamarZand88
wants to merge
8
commits into
main
Choose a base branch
from
itamar/alien-41-example-project-ai-chatbot
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7ef5c4d
feat(examples): add an AI chatbot example over a private Postgres
ItamarZand88 66a8c7c
feat(examples): let the chatbot use Claude models too
ItamarZand88 4682674
fix(examples): bound the chatbot's database access and seed without a…
ItamarZand88 1356dbb
feat(examples): show the chatbot's underlying tables in the UI
ItamarZand88 f4a56da
fix(examples): harden the chatbot's container and seeding
ItamarZand88 fba9011
fix(examples): run the model's SQL in a read-only transaction
ItamarZand88 4c07f49
refactor(examples): give the chatbot fixed queries instead of free SQL
ItamarZand88 9b3ad76
docs(examples): list the AI templates in the examples README
ItamarZand88 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) { | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| 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() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() { | ||
| 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 }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.