page wrnexusai {
  seo {
    title = "@wrnexus/ai"
    description = "Server-side Anthropic client with generation and streaming."
  }

  view {
    <div class="docs-shell">
      <a class="skip-link" href="#main">Skip to content</a>
      <header class="topbar">
        <a class="brand" href="/"><span>W</span> WRNexusJS</a>
        <nav aria-label="Primary"><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
        <div class="topbar-actions"><a class="preview-pill" href="/access">Private preview · v0.2.31</a><button data-wire-theme-toggle class="theme-button" aria-label="Toggle color theme" title="Toggle color theme">◐</button></div>
      </header>
      <div class="mobile-doc-nav"><details><summary>Browse documentation</summary><nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a><a href="/tutorial">Tutorial</a><a href="/guides/project-structure">Guides</a><a href="/examples">Examples</a><a href="/search">Search</a></nav></details></div>
      <main class="page package-page">
      <aside class="sidebar"><a href="/packages">← All packages</a><span class="category">AI</span><h2>@wrnexus/ai</h2><p>Server-side Anthropic client with generation and streaming.</p><span class="status status-beta">Private preview · 0.2.31</span><nav><a href="#access">Access</a><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
      <article id="main" class="documentation"><section class="doc-intro"><span class="eyebrow">AI · Preview</span><h1>@wrnexus/ai</h1><p>Server-side Anthropic client with generation and streaming.</p><section id="access" class="access-callout"><h2>Private registry access required</h2><p>This package is not available from the public npm registry. After WorkRoot approves access and supplies private registry instructions, install the release-aligned package:</p><pre><code>bun add @wrnexus/ai@0.2.31</code><button type="button" class="copy-button" aria-label="Copy installation command">Copy</button></pre><p><a href="/access">Request preview access</a>. Never put registry tokens in source control.</p></section></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>
<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 &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;
const ai = createAI(); // or createAI(&#123; apiKey, model, maxTokens, baseURL, version &#125;)</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>&quot;claude-opus-4-8&quot;</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>&quot;2023-06-01&quot;</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&lt;string&gt;</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(&quot;Write a haiku about Bun.&quot;);

const reply = await ai.generate(
  [
    &#123; role: &quot;user&quot;, content: &quot;My name is Ada.&quot; &#125;,
    &#123; role: &quot;assistant&quot;, content: &quot;Hi Ada!&quot; &#125;,
    &#123; role: &quot;user&quot;, content: &quot;What's my name?&quot; &#125;,
  ],
  &#123; system: &quot;You are concise.&quot; &#125;,
);</code></pre>
<h4 id="ai-stream-prompt-opts-asyncgenerator-string"><code>ai.stream(prompt, opts?): AsyncGenerator&lt;string&gt;</code></h4>
<p>Yields text deltas as they arrive.</p>
<pre data-language="ts"><code>for await (const chunk of ai.stream(&quot;Tell me a story.&quot;)) &#123;
  process.stdout.write(chunk);
&#125;</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 &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;
const ai = createAI();

export const POST = async (ctx) =&gt; &#123;
  const &#123; prompt &#125; = await ctx.req.json();
  return ai.streamResponse(prompt);
&#125;;</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>`&quot;low&quot; \</td><td>&quot;medium&quot; \</td><td>&quot;high&quot; \</td><td>&quot;xhigh&quot; \</td><td>&quot;max&quot;`</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>&quot;authentication_error&quot;</code>, <code>&quot;rate_limit_error&quot;</code>, <code>&quot;refusal&quot;</code>).</p>
<pre data-language="ts"><code>import &#123; AIError &#125; from &quot;@wrnexus/ai&quot;;
try &#123;
  await ai.generate(&quot;...&quot;);
&#125; catch (e) &#123;
  if (e instanceof AIError &amp;&amp; e.type === &quot;rate_limit_error&quot;) &#123;
    /* back off */
  &#125;
&#125;</code></pre>
<h3 id="usage">Usage</h3>
<h4 id="return-generated-json-from-an-api-route">Return generated JSON from an API route</h4>
<pre data-language="ts"><code>// app/api/summarize.ts — summarize posted text
import &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;
const ai = createAI();

export const POST = async (ctx) =&gt; &#123;
  const &#123; text &#125; = await ctx.req.json().catch(() =&gt; (&#123;&#125;));
  if (!text) return Response.json(&#123; error: &quot;Provide 'text'.&quot; &#125;, &#123; status: 400 &#125;);
  const summary = await ai.generate(`Summarize in one sentence:\n\n$&#123;text&#125;`, &#123;
    system: &quot;You are a precise summarizer.&quot;,
  &#125;);
  return Response.json(&#123; summary &#125;);
&#125;;</code></pre>
<h4 id="stream-a-chat-response-to-the-browser">Stream a chat response to the browser</h4>
<pre data-language="ts"><code>// app/api/chat.ts
import &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;

const ai = createAI(&#123; model: &quot;claude-sonnet-5&quot; &#125;);

export const POST = async (ctx) =&gt; &#123;
  const &#123; messages &#125; = await ctx.req.json();
  return ai.streamResponse(messages, &#123;
    system: &quot;Answer using concise Markdown.&quot;,
    maxTokens: 1_500,
  &#125;);
&#125;;</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>&#123; model &#125;</code> for a different model (e.g.</li>
<p><code>&quot;claude-sonnet-5&quot;</code> for speed/cost, <code>&quot;claude-haiku-4-5&quot;</code> for the fastest).</p>
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration comes from the exact installed 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 &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;
 *   const ai = createAI();                       // reads ANTHROPIC_API_KEY
 *   const text = await ai.generate(&quot;Write a haiku about Bun.&quot;);
 *
 * Streaming (great for API routes):
 *   export const POST = async (ctx) =&gt; ai.streamResponse(await ctx.req.text());
 */
type Role = &quot;user&quot; | &quot;assistant&quot;;
interface Message &#123;
    role: Role;
    content: string;
&#125;
/** Reasoning effort — higher means deeper thinking + more tokens. */
type Effort = &quot;low&quot; | &quot;medium&quot; | &quot;high&quot; | &quot;xhigh&quot; | &quot;max&quot;;
interface AIConfig &#123;
    /** 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;
&#125;
interface GenerateOptions &#123;
    /** 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;
&#125;
/** Thrown when the API returns a non-2xx response or refuses the request. */
declare class AIError extends Error &#123;
    readonly status: number;
    readonly type: string;
    constructor(message: string, status?: number, type?: string);
&#125;
interface AI &#123;
    /** Generate a full text response (non-streaming). */
    generate(prompt: string | Message[], opts?: GenerateOptions): Promise&lt;string&gt;;
    /** Stream the response as text deltas, as they arrive. */
    stream(prompt: string | Message[], opts?: GenerateOptions): AsyncGenerator&lt;string, void, unknown&gt;;
    /** Stream straight to a `Response` (text/plain) — drop-in for an API route return. */
    streamResponse(prompt: string | Message[], opts?: GenerateOptions): Response;
&#125;
/** Create a Claude client. Reads `ANTHROPIC_API_KEY` from the environment by default. */
declare function createAI(config?: AIConfig): AI;

export &#123; type AI, type AIConfig, AIError, type Effort, type GenerateOptions, type Message, type Role, createAI &#125;;
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Examples are taken from this package's installed documentation and must be evaluated with its requirements and stability notes.</p><div class="example-grid"><article class="example-card"><h3>Return generated JSON from an API route</h3><pre data-language="ts"><code>// app/api/summarize.ts — summarize posted text
import &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;
const ai = createAI();

export const POST = async (ctx) =&gt; &#123;
  const &#123; text &#125; = await ctx.req.json().catch(() =&gt; (&#123;&#125;));
  if (!text) return Response.json(&#123; error: &quot;Provide 'text'.&quot; &#125;, &#123; status: 400 &#125;);
  const summary = await ai.generate(`Summarize in one sentence:\n\n$&#123;text&#125;`, &#123;
    system: &quot;You are a precise summarizer.&quot;,
  &#125;);
  return Response.json(&#123; summary &#125;);
&#125;;</code></pre></article><article class="example-card"><h3>Stream a chat response to the browser</h3><pre data-language="ts"><code>// app/api/chat.ts
import &#123; createAI &#125; from &quot;@wrnexus/ai&quot;;

const ai = createAI(&#123; model: &quot;claude-sonnet-5&quot; &#125;);

export const POST = async (ctx) =&gt; &#123;
  const &#123; messages &#125; = await ctx.req.json();
  return ai.streamResponse(messages, &#123;
    system: &quot;Answer using concise Markdown.&quot;,
    maxTokens: 1_500,
  &#125;);
&#125;;</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="#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&lt;string&gt;</a><a class="toc-level-4" href="#ai-stream-prompt-opts-asyncgenerator-string">ai.stream(prompt, opts?): AsyncGenerator&lt;string&gt;</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-4" href="#return-generated-json-from-an-api-route">Return generated JSON from an API route</a><a class="toc-level-4" href="#stream-a-chat-response-to-the-browser">Stream a chat response to the browser</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.31 · Private Developer Preview · Bun-native · Documentation generated from installed package APIs.</footer>
    </div>
  }
}
