Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/alien-cli/src/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TemplateInfo> {
Expand Down
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions examples/ai-chatbot-ts/.dockerignore
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
18 changes: 18 additions & 0 deletions examples/ai-chatbot-ts/.gitignore
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
24 changes: 24 additions & 0 deletions examples/ai-chatbot-ts/Dockerfile
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
Comment thread
greptile-apps[bot] marked this conversation as resolved.
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"]
Comment thread
greptile-apps[bot] marked this conversation as resolved.
52 changes: 52 additions & 0 deletions examples/ai-chatbot-ts/README.md
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)
38 changes: 38 additions & 0 deletions examples/ai-chatbot-ts/alien.ts
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()
74 changes: 74 additions & 0 deletions examples/ai-chatbot-ts/app/api/chat/route.ts
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) {
Comment thread
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()
}
6 changes: 6 additions & 0 deletions examples/ai-chatbot-ts/app/api/models/route.ts
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) })
}
21 changes: 21 additions & 0 deletions examples/ai-chatbot-ts/app/api/tables/route.ts
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 })
}
Loading
Loading