@use-crux/anthropic
Anthropic SDK adapter, factory pattern with native options.
Peer dependency: @anthropic-ai/sdk
import {
createAnthropic,
anthropicProviderRuntime,
anthropicTranscript,
toMessages,
fromMessages,
} from "@use-crux/anthropic";
import {
createGenerateObjectFn,
createGenerateTextFn,
} from "@use-crux/anthropic";For usage examples and provider comparison, see the Execution guide.
createAnthropic(client)
Create an adapter bound to an Anthropic client.
createAnthropic() is anthropicProviderRuntime.create. The package-owned anthropicTranscript owns tool_use / tool_result conversion plus assistant text/tool-call extraction. Anthropic-specific request params, cache-control system blocks, and response metadata normalization stay owned by @use-crux/anthropic; Crux still owns prompt resolution, tool loops, safety, validation retry, memory capture, and observability. Provider prompt caching uses Crux's cacheBoundary marker: the adapter places one Anthropic cache_control breakpoint at the end of the stable cached prefix.
Anthropic content support is part-aware beneath the public codec surface: user image data/URLs encode as image blocks, PDF data/URLs encode as document blocks, assistant image/document blocks decode back into canonical message content, and unsupported parts such as audio fail before the provider call.
Video is likewise unsupported. generateImage(), transcribe(), and
generateSpeech() are structurally absent from this package rather than
throwing at runtime.
| Field | Type | Description |
|---|---|---|
client | Anthropic | The Anthropic client instance |
Returns:
| Method | Description |
|---|---|
.generate(prompt, options) | Execute a prompt via messages.parse (structured) or .create (text) |
.stream(prompt, options) | Stream a prompt execution |
.prepare(prompt, options) | Prepare a sans-I/O call handle with provider params |
.retrievalModel(config) | Bind Anthropic generation to core retrieval recipe steps |
.reranker(config) | Create a judge-backed core Reranker |
import { createAnthropic } from "@use-crux/anthropic";
import Anthropic from "@anthropic-ai/sdk";
const adapter = createAnthropic(
new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),
);
const result = await adapter.generate(editDraft, {
model: "claude-sonnet-4-5-20250929",
input: { instruction: "Fix the intro" },
});
result.text;
result.usage;
result.finalStep;adapter.generate(prompt, options)
| Field | Type | Description |
|---|---|---|
prompt | Prompt | The prompt to execute |
options.model | string | Model name |
options.input | object | Input values |
options.tools | Record<string, unknown>? | Additional Crux tools to merge at call time |
options.toolMiddleware | ToolMiddleware | readonly ToolMiddleware[]? | Tool execution hooks, including Crux resumable approvals through result.messages. |
options.toolApproval | ToolApprovalMap? | Call-site approval policy; exact tool names beat '*'. |
options.toolsContext | Record<string, unknown>? | Required for composed tools that declare contextSchema; values are Zod-validated before the tool loop starts. |
options.runtimeContext | unknown? | Shared per-run context visible to tool execute, middleware, and function-form toolApproval policies. |
options.transport | (params, info) => Promise<Message> | BYO wire call. Crux still owns tools, approvals, validation retry, routing, and timeouts. |
options.extra.tools | ToolUnion[]? | Anthropic-native tools that bypass Crux tool conversion |
options.extra.tool_choice | ToolChoice? | Anthropic-native tool selection |
Returns: normalized Crux generate result with:
result.text: extracted assistant textresult.usage: accumulated usage when every provider-call step reported usageresult.cost: provider-reported cost when availableresult.finalStep: final provider-call text, usage, finish reason, response id, and actual model idresult.raw: raw Anthropic SDK responseresult._meta: retained trace metadata for observability plumbing
When the prompt has an output schema, Anthropic's parsed value remains available on result.raw.parsed_output.
Anthropic requires max_tokens. If not set in your prompt's settings, the
adapter defaults to 4096.
adapter.stream(prompt, options)
Stream a prompt execution.
| Field | Type | Description |
|---|---|---|
prompt | Prompt | The prompt to execute |
options.model | string | Model name |
options.input | object | Input values |
options.tools | Record<string, unknown>? | Additional Crux tools to merge at call time |
options.toolMiddleware | ToolMiddleware | readonly ToolMiddleware[]? | Tool execution hooks, including Crux resumable approvals through result.messages. |
options.toolApproval | ToolApprovalMap? | Call-site approval policy; exact tool names beat '*'. |
options.toolsContext | Record<string, unknown>? | Required for composed tools that declare contextSchema; values are Zod-validated before the tool loop starts. |
options.runtimeContext | unknown? | Shared per-run context visible to tool execute, middleware, and function-form toolApproval policies. |
options.extra.tools | ToolUnion[]? | Anthropic-native tools that bypass Crux tool conversion |
options.extra.tool_choice | ToolChoice? | Anthropic-native tool selection |
Returns: StreamResult<MessageStream>:
result.textStream: provider-neutral text deltasresult.raw: raw AnthropicMessageStreamresult.completion: promise resolving to the canonical completion envelope (text, optionalusage, optionalcost,steps,finalStep,messages, and pending approvals)
adapter.prepare(prompt, options)
Prepare a headless Anthropic call. Crux resolves the prompt, opens the same
executor path used by generate(), and returns provider params without making
the SDK call.
const call = await adapter.prepare(editDraft, {
model: "claude-sonnet-4-5-20250929",
input: { instruction: "Fix the intro" },
});
const response = await client.messages.create(call.params);
const result = await call.finish(response);Use step(response) when the model may request tools or validation retry may
need another turn. The returned next.params is the next Anthropic request.
generate(prompt, { ...options, transport }) is the BYO-wire mode where Crux
keeps owning the loop and invokes your callback for each Anthropic request.
stream() with transport is intentionally unsupported and rejects with
CruxTransportStreamUnsupportedError.
toParams(resolved, options) / fromResponse(response)
toParams() converts a ResolvedPrompt plus { model, settings?, extra? }
into Anthropic message-create params. ResolvedPrompt does not include a
model, so options.model is required. fromResponse() normalizes an
Anthropic response into Crux AdapterResponse facts.
These codecs are translation-only. They do not run tool middleware, approvals, validation retry, memory capture, safety, or observability.
adapter.retrievalModel(config)
Create a core RetrievalModel from the adapter instance.
const retrievalModel = adapter.retrievalModel({ model: "claude-haiku-4-5" });Use it as a recipe-level model or step-level model.
adapter.reranker(config)
Create a core Reranker for rerank({ engine }).
const engine = adapter.reranker({
model: "claude-haiku-4-5",
topN: 12,
});Anthropic does not expose a native rerank endpoint in this adapter. adapter.reranker() uses Crux's judgeReranker() over the configured Anthropic model, so each rerank call spends generation tokens.
toMessages(sdkMessages)
Convert Anthropic MessageParam[] to canonical Message[].
| Field | Type | Description |
|---|---|---|
sdkMessages | MessageParam[] | Anthropic SDK messages |
Returns: Message[]
fromMessages(messages)
Convert canonical Message[] to Anthropic MessageParam[].
| Field | Type | Description |
|---|---|---|
messages | Message[] | Canonical messages |
Returns: MessageParam[]
Anthropic has no tool role. Tool results are converted to user messages
with tool_result content blocks.
anthropicTranscript is the lower-level NativeTranscriptCodec used by createAnthropic(). toMessages() and fromMessages() are provider-history converters, not a generic cross-provider transcript API; they delegate to the same Anthropic-owned codec that request assembly, assistant tool_use extraction, and second-call tool-loop payloads use.
Assistant tool calls become ordered tool_use content blocks. Tool-result content keeps native Anthropic image and PDF blocks where supported, falling back to deterministic text references for unsupported media.
createGenerateObjectFn(client, model)
Create a GenerateObjectFn bound to a client and model.
| Field | Type | Description |
|---|---|---|
client | Anthropic | Anthropic client instance |
model | string | Model name |
Returns: GenerateObjectFn
This is a provider-native helper generated from the same native chat profile as createAnthropic(). It uses Anthropic's structured parse surface and returns the parsed { object }, preserving provider errors. It does not run Crux prompt resolution, validation retry, safety, cassettes, tools, memory capture, or instrumentation. Use createGenerateObjectFnFromGenerate(generate) from @use-crux/core/compaction when a GenerateObjectFn needs full adapter runtime behavior.
createGenerateTextFn(client, model)
Create a GenerateTextFn bound to a client and model.
| Field | Type | Description |
|---|---|---|
client | Anthropic | Anthropic client instance |
model | string | Model name |
Returns: GenerateTextFn
This helper is also generated from the native chat profile, so text helper calls and adapter calls share request construction and response extraction.
Embeddings
@use-crux/anthropic is a generation adapter. It does not export a provider-native embedding() helper because Anthropic's direct SDK surface here does not provide the dense embedding API that Crux needs for embedding().
When you want Anthropic for generation plus retrieval/indexing around it, use one of these patterns:
- pair
createAnthropic()withembedding()from@use-crux/ai - pair it with
embedding()from@use-crux/openaior@use-crux/googlefor the write/query vector side - keep Anthropic as the chat model while another provider handles embeddings
Types
import type { AnthropicExtra, AnthropicRequest } from "@use-crux/anthropic";Related
- Guide: Execution
- Reference: Prompts
- Reference: @use-crux/ai (Vercel AI SDK)