182 lines
14 KiB
Plaintext
182 lines
14 KiB
Plaintext
page wrnexusai {
|
|
seo {
|
|
title = "@wrnexus/ai"
|
|
description = "Server-side Anthropic client with generation and streaming."
|
|
}
|
|
|
|
view {
|
|
<div class="docs-shell">
|
|
<header class="topbar">
|
|
<a class="brand" href="/"><span>W</span> WRNexusJS</a>
|
|
<nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
|
|
<button data-wire-theme-toggle class="theme-button" aria-label="Toggle theme">Theme</button>
|
|
</header>
|
|
<main class="page package-page">
|
|
<aside class="sidebar"><a href="/packages">← All packages</a><span class="category">AI</span><h1>@wrnexus/ai</h1><p>Server-side Anthropic client with generation and streaming.</p><code>bun add @wrnexus/ai@0.2.12</code><nav><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
|
|
<article class="documentation"><section class="doc-intro"><span class="eyebrow">AI</span><h1>@wrnexus/ai</h1><p>Server-side Anthropic client with generation and streaming.</p><pre><code>bun add @wrnexus/ai@0.2.12</code></pre></section><section id="guide" class="prose"><blockquote>A tiny, zero-dependency Claude (Anthropic) client for WRNexusJS apps — generate and stream text with Claude from any server-side code.</blockquote>
|
|
<p>Part of the <strong>WRNexusJS</strong> framework — an SSR-first, Bun-native full-stack web framework.</p>
|
|
<h3 id="overview">Overview</h3>
|
|
<p><code>@wrnexus/ai</code> is a thin, dependency-free wrapper over the Anthropic <strong>Messages API</strong>, built on <code>fetch</code> (Bun-native, no SDK). Use it in API routes, jobs, or middleware to call Claude. It defaults to the most capable model, <strong><code>claude-opus-4-8</code></strong>, reads your key from <code>ANTHROPIC_API_KEY</code>, and supports both one-shot generation and streaming.</p>
|
|
<h3 id="installation">Installation</h3>
|
|
<pre data-language="bash"><code>bun add @wrnexus/ai</code></pre>
|
|
<blockquote>Private package — the machine must be authenticated to the <code>wrnexus</code> npm org</blockquote>
|
|
<blockquote>(a read token in <code>~/.npmrc</code>). Requires <strong>Bun</strong> (Node is not supported).</blockquote>
|
|
<p>Set your key in the environment (e.g. <code>.env</code>):</p>
|
|
<pre data-language=""><code>ANTHROPIC_API_KEY=sk-ant-...</code></pre>
|
|
<h3 id="api">API</h3>
|
|
<h4 id="createai-config"><code>createAI(config?)</code></h4>
|
|
<p>Creates a client. The key is read at call time, so it's safe to create at import.</p>
|
|
<pre data-language="ts"><code>import { createAI } from "@wrnexus/ai";
|
|
const ai = createAI(); // or createAI({ apiKey, model, maxTokens, baseURL, version })</code></pre>
|
|
<p><code>AIConfig</code> fields (all optional):</p>
|
|
<div class="table-wrap"><table>
|
|
<thead><tr><th>Field</th><th>Default</th><th>Description</th></tr></thead>
|
|
<tbody><tr><td><code>apiKey</code></td><td><code>ANTHROPIC_API_KEY</code></td><td>Anthropic API key</td></tr><tr><td><code>model</code></td><td><code>"claude-opus-4-8"</code></td><td>Model id</td></tr><tr><td><code>maxTokens</code></td><td><code>4096</code></td><td>Default max output tokens</td></tr><tr><td><code>baseURL</code></td><td><code>https://api.anthropic.com</code></td><td>API base URL</td></tr><tr><td><code>version</code></td><td><code>"2023-06-01"</code></td><td><code>anthropic-version</code> header</td></tr></tbody></table></div>
|
|
<h4 id="ai-generate-prompt-opts-promise-string"><code>ai.generate(prompt, opts?): Promise<string></code></h4>
|
|
<p>One-shot text generation. <code>prompt</code> is a string or a <code>Message[]</code> history.</p>
|
|
<pre data-language="ts"><code>const text = await ai.generate("Write a haiku about Bun.");
|
|
|
|
const reply = await ai.generate(
|
|
[
|
|
{ role: "user", content: "My name is Ada." },
|
|
{ role: "assistant", content: "Hi Ada!" },
|
|
{ role: "user", content: "What's my name?" },
|
|
],
|
|
{ system: "You are concise." },
|
|
);</code></pre>
|
|
<h4 id="ai-stream-prompt-opts-asyncgenerator-string"><code>ai.stream(prompt, opts?): AsyncGenerator<string></code></h4>
|
|
<p>Yields text deltas as they arrive.</p>
|
|
<pre data-language="ts"><code>for await (const chunk of ai.stream("Tell me a story.")) {
|
|
process.stdout.write(chunk);
|
|
}</code></pre>
|
|
<h4 id="ai-streamresponse-prompt-opts-response"><code>ai.streamResponse(prompt, opts?): Response</code></h4>
|
|
<p>Returns a streaming <code>text/plain</code> <code>Response</code> — drop it straight into an API route.</p>
|
|
<pre data-language="ts"><code>// app/api/chat.ts
|
|
import { createAI } from "@wrnexus/ai";
|
|
const ai = createAI();
|
|
|
|
export const POST = async (ctx) => {
|
|
const { prompt } = await ctx.req.json();
|
|
return ai.streamResponse(prompt);
|
|
};</code></pre>
|
|
<h4 id="generateoptions"><code>GenerateOptions</code></h4>
|
|
<div class="table-wrap"><table>
|
|
<thead><tr><th>Option</th><th>Type</th><th>Description</th></tr></thead>
|
|
<tbody><tr><td><code>system</code></td><td><code>string</code></td><td>System prompt</td></tr><tr><td><code>model</code></td><td><code>string</code></td><td>Override the model for this call</td></tr><tr><td><code>maxTokens</code></td><td><code>number</code></td><td>Override max output tokens</td></tr><tr><td><code>thinking</code></td><td><code>boolean</code></td><td>Enable adaptive extended thinking (deeper reasoning)</td></tr><tr><td><code>effort</code></td><td>`"low" \</td><td>"medium" \</td><td>"high" \</td><td>"xhigh" \</td><td>"max"`</td><td>Reasoning effort / token spend</td></tr><tr><td><code>messages</code></td><td><code>Message[]</code></td><td>Full history — supersedes <code>prompt</code></td></tr><tr><td><code>signal</code></td><td><code>AbortSignal</code></td><td>Cancel the request</td></tr></tbody></table></div>
|
|
<blockquote><code>temperature</code> / <code>top_p</code> are intentionally <strong>not</strong> exposed — the current Claude</blockquote>
|
|
<blockquote>models reject them (400). Steer output with prompting instead.</blockquote>
|
|
<h4 id="aierror"><code>AIError</code></h4>
|
|
<p>Thrown on non-2xx responses or a model refusal. Carries <code>.status</code> and <code>.type</code> (e.g. <code>"authentication_error"</code>, <code>"rate_limit_error"</code>, <code>"refusal"</code>).</p>
|
|
<pre data-language="ts"><code>import { AIError } from "@wrnexus/ai";
|
|
try {
|
|
await ai.generate("...");
|
|
} catch (e) {
|
|
if (e instanceof AIError && e.type === "rate_limit_error") {
|
|
/* back off */
|
|
}
|
|
}</code></pre>
|
|
<h3 id="usage">Usage</h3>
|
|
<pre data-language="ts"><code>// app/api/summarize.ts — summarize posted text
|
|
import { createAI } from "@wrnexus/ai";
|
|
const ai = createAI();
|
|
|
|
export const POST = async (ctx) => {
|
|
const { text } = await ctx.req.json().catch(() => ({}));
|
|
if (!text) return Response.json({ error: "Provide 'text'." }, { status: 400 });
|
|
const summary = await ai.generate(`Summarize in one sentence:\n\n${text}`, {
|
|
system: "You are a precise summarizer.",
|
|
});
|
|
return Response.json({ summary });
|
|
};</code></pre>
|
|
<h3 id="requirements-notes">Requirements / Notes</h3>
|
|
<ul>
|
|
<li><strong>Bun-only.</strong> Uses <code>fetch</code>, <code>ReadableStream</code>, <code>TextDecoder</code>/<code>TextEncoder</code>, and</li>
|
|
<p>reads <code>ANTHROPIC_API_KEY</code> from <code>Bun.env</code> (falls back to <code>process.env</code>).</p>
|
|
<li><strong>Zero dependencies</strong> — no <code>@anthropic-ai/sdk</code>; talks to the Messages API directly.</li>
|
|
<li>Defaults to <code>claude-opus-4-8</code>. Pass <code>{ model }</code> for a different model (e.g.</li>
|
|
<p><code>"claude-sonnet-5"</code> for speed/cost, <code>"claude-haiku-4-5"</code> for the fastest).</p>
|
|
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>/**
|
|
* @wrnexus/ai — a tiny, zero-dependency Claude (Anthropic) client for WRNexusJS apps.
|
|
*
|
|
* Use it in API routes, jobs, or anywhere server-side to generate text with Claude.
|
|
* It talks to the Anthropic Messages API over `fetch` (no SDK dependency, Bun-native),
|
|
* and defaults to the most capable model, `claude-opus-4-8`.
|
|
*
|
|
* import { createAI } from "@wrnexus/ai";
|
|
* const ai = createAI(); // reads ANTHROPIC_API_KEY
|
|
* const text = await ai.generate("Write a haiku about Bun.");
|
|
*
|
|
* Streaming (great for API routes):
|
|
* export const POST = async (ctx) => ai.streamResponse(await ctx.req.text());
|
|
*/
|
|
type Role = "user" | "assistant";
|
|
interface Message {
|
|
role: Role;
|
|
content: string;
|
|
}
|
|
/** Reasoning effort — higher means deeper thinking + more tokens. */
|
|
type Effort = "low" | "medium" | "high" | "xhigh" | "max";
|
|
interface AIConfig {
|
|
/** Anthropic API key. Default: `ANTHROPIC_API_KEY` from the environment. */
|
|
apiKey?: string;
|
|
/** Model id. Default: `claude-opus-4-8` (the most capable Claude model). */
|
|
model?: string;
|
|
/** Default max output tokens. Default: 4096. */
|
|
maxTokens?: number;
|
|
/** API base URL. Default: `https://api.anthropic.com`. */
|
|
baseURL?: string;
|
|
/** `anthropic-version` header. Default: `2023-06-01`. */
|
|
version?: string;
|
|
}
|
|
interface GenerateOptions {
|
|
/** System prompt — sets the assistant's role/behavior. */
|
|
system?: string;
|
|
/** Override the model for this call. */
|
|
model?: string;
|
|
/** Override max output tokens for this call. */
|
|
maxTokens?: number;
|
|
/** Enable adaptive extended thinking (slower, deeper reasoning). */
|
|
thinking?: boolean;
|
|
/** Reasoning effort / token spend (`output_config.effort`). */
|
|
effort?: Effort;
|
|
/** Full message history — supersedes the `prompt` argument when provided. */
|
|
messages?: Message[];
|
|
/** Abort the request. */
|
|
signal?: AbortSignal;
|
|
}
|
|
/** Thrown when the API returns a non-2xx response or refuses the request. */
|
|
declare class AIError extends Error {
|
|
readonly status: number;
|
|
readonly type: string;
|
|
constructor(message: string, status?: number, type?: string);
|
|
}
|
|
interface AI {
|
|
/** Generate a full text response (non-streaming). */
|
|
generate(prompt: string | Message[], opts?: GenerateOptions): Promise<string>;
|
|
/** Stream the response as text deltas, as they arrive. */
|
|
stream(prompt: string | Message[], opts?: GenerateOptions): AsyncGenerator<string, void, unknown>;
|
|
/** Stream straight to a `Response` (text/plain) — drop-in for an API route return. */
|
|
streamResponse(prompt: string | Message[], opts?: GenerateOptions): Response;
|
|
}
|
|
/** Create a Claude client. Reads `ANTHROPIC_API_KEY` from the environment by default. */
|
|
declare function createAI(config?: AIConfig): AI;
|
|
|
|
export { type AI, type AIConfig, AIError, type Effort, type GenerateOptions, type Message, type Role, createAI };
|
|
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Copy-ready examples taken from this package's published documentation.</p><div class="example-grid"><article class="example-card"><h3>Example 1</h3><pre data-language="bash"><code>bun add @wrnexus/ai</code></pre></article><article class="example-card"><h3>Example 2</h3><pre data-language="text"><code>ANTHROPIC_API_KEY=sk-ant-...</code></pre></article><article class="example-card"><h3>Example 3</h3><pre data-language="ts"><code>import { createAI } from "@wrnexus/ai";
|
|
const ai = createAI(); // or createAI({ apiKey, model, maxTokens, baseURL, version })</code></pre></article><article class="example-card"><h3>Example 4</h3><pre data-language="ts"><code>const text = await ai.generate("Write a haiku about Bun.");
|
|
|
|
const reply = await ai.generate(
|
|
[
|
|
{ role: "user", content: "My name is Ada." },
|
|
{ role: "assistant", content: "Hi Ada!" },
|
|
{ role: "user", content: "What's my name?" },
|
|
],
|
|
{ system: "You are concise." },
|
|
);</code></pre></article></div></section></article>
|
|
<aside class="on-this-page"><h2>On this page</h2><nav><a class="toc-level-2" href="#guide">Guide</a><a class="toc-level-3" href="#overview">Overview</a><a class="toc-level-3" href="#installation">Installation</a><a class="toc-level-3" href="#api">API</a><a class="toc-level-4" href="#createai-config">createAI(config?)</a><a class="toc-level-4" href="#ai-generate-prompt-opts-promise-string">ai.generate(prompt, opts?): Promise<string></a><a class="toc-level-4" href="#ai-stream-prompt-opts-asyncgenerator-string">ai.stream(prompt, opts?): AsyncGenerator<string></a><a class="toc-level-4" href="#ai-streamresponse-prompt-opts-response">ai.streamResponse(prompt, opts?): Response</a><a class="toc-level-4" href="#generateoptions">GenerateOptions</a><a class="toc-level-4" href="#aierror">AIError</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-3" href="#requirements-notes">Requirements / Notes</a><a class="toc-level-2" href="#api">Complete API</a><a class="toc-level-2" href="#examples">Examples</a></nav></aside>
|
|
</main>
|
|
<footer>WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.</footer>
|
|
</div>
|
|
}
|
|
}
|