सामग्री पर जाएं
AIAn Alian Software company

Snippets

Copy-paste snippets for the common stuff.

Calling our APIs, consuming SSE streams, wiring patterns from the playbooks into your stack. Curl, TypeScript, Python.

Call the Live Problem Solver from curl

bash

Stream a tailored AI solution for a one-line problem statement.

curl -N -X POST https://aliansoftware.net/api/solve \
  -H "content-type: application/json" \
  -d '{"problem":"We get 800 leads a month and cant follow up fast enough"}'

Consume the SSE stream in TypeScript

ts

Parse Server-Sent Events from /api/solve as they arrive. Same pattern works for /api/chat.

async function streamSolve(problem: string) {
  const res = await fetch("/api/solve", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ problem }),
  });

  const reader = res.body!.getReader();
  const decoder = new TextDecoder();
  let buffer = "";

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    let sep: number;
    while ((sep = buffer.indexOf("\n\n")) !== -1) {
      const raw = buffer.slice(0, sep);
      buffer = buffer.slice(sep + 2);
      let event = "message";
      const dataLines: string[] = [];
      for (const line of raw.split("\n")) {
        if (line.startsWith("event:")) event = line.slice(6).trim();
        else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
      }
      if (event === "delta") {
        const { text } = JSON.parse(dataLines.join("\n"));
        process.stdout.write(text);
      } else if (event === "done") {
        const final = JSON.parse(dataLines.join("\n"));
        console.log("\n\nDone:", final);
        return final;
      }
    }
  }
}

await streamSolve("Our support team is buried in tickets");

Stream Anthropic Claude in a Next.js route handler

ts

The pattern we use in /api/solve. Anthropic SDK with streaming, SSE response, post-stream Postgres logging.

import Anthropic from "@anthropic-ai/sdk";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const { problem } = await req.json();
  const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! });
  const encoder = new TextEncoder();

  const stream = new ReadableStream<Uint8Array>({
    async start(controller) {
      const send = (event: string, data: unknown) =>
        controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));

      try {
        const response = await client.messages.stream({
          model: "claude-sonnet-4-6",
          max_tokens: 400,
          system: "You are a solution architect...",
          messages: [{ role: "user", content: problem }],
        });

        let full = "";
        for await (const event of response) {
          if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
            full += event.delta.text;
            send("delta", { text: event.delta.text, total: full });
          }
        }
        send("done", JSON.parse(full));
      } catch (err) {
        send("error", { message: "Briefly unavailable" });
      } finally {
        controller.close();
      }
    },
  });

  return new Response(stream, {
    headers: {
      "content-type": "text/event-stream; charset=utf-8",
      "cache-control": "no-cache, no-transform",
    },
  });
}

Citation-required RAG pattern in Python

python

The minimal RAG generation step with hybrid search, reranking, and citation-required prompting.

from anthropic import Anthropic

def generate_with_citations(question, retrieved_chunks):
    numbered = "\n\n".join(
        f"[{i + 1}] {chunk.title}\n{chunk.text}"
        for i, chunk in enumerate(retrieved_chunks)
    )

    system = (
        "You are answering a user question using ONLY the retrieved context. "
        "Every factual claim must cite a numbered source like [1] or [2]. "
        "If the context doesn't contain enough information, refuse politely."
    )

    user = f"""# Retrieved context

{numbered}

# Question
{question}

# Answer (cite sources inline, end with a Sources block)"""

    client = Anthropic()
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1000,
        system=system,
        messages=[{"role": "user", "content": user}],
    )
    return response.content[0].text

Embed the OG image generator into a share button

ts

Generate brand-styled share cards on demand using /api/og.

function getOgUrl(title: string, subtitle?: string) {
  const params = new URLSearchParams({ title });
  if (subtitle) params.set("subtitle", subtitle);
  return `https://aliansoftware.net/api/og?${params.toString()}`;
}

// Use in OG meta tags
export const metadata = {
  openGraph: {
    images: [
      {
        url: getOgUrl("AI agents for finance", "Audit-traceable. Compliance-grade."),
        width: 1200,
        height: 630,
      },
    ],
  },
};

Check status endpoint in a health-check loop

ts

Use /api/status to power your own uptime probe or runtime feature-flag system.

async function checkHealth() {
  const res = await fetch("https://aliansoftware.net/api/status", {
    cache: "no-store",
  });
  if (!res.ok) return { overall: "down", checks: [] };
  return res.json();
}

// Use in your monitoring loop
setInterval(async () => {
  const status = await checkHealth();
  if (status.overall !== "operational") {
    notifyOnCall(status);
  }
}, 60_000);

Send a contact form submission programmatically

ts

Useful when integrating from another front-end or a partner site.

await fetch("https://aliansoftware.net/api/contact", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({
    name: "Jane Doe",
    email: "jane@company.com",
    company: "Acme",
    intent: "discovery",
    problem: "We want to scope an AI assistant for support tier-1.",
  }),
});

Need a snippet for your stack?

Tell us what you're trying to wire up — we'll add it here.