@dawn-ai/langchain

Use this when

Use this integration package when framework code must materialize Dawn agent descriptors, adapt LangChain runnables, convert Dawn tools, configure provider loading, or compose the package's retry, summarization, offloading, and subagent helpers. Most application code declares agents through agent() and lets the Dawn runtime call this layer.

Install and import

bash
pnpm add @dawn-ai/langchain @langchain/core @langchain/langgraph-checkpoint
ts
import {
  chainAdapter,
  openaiEmbedder,
  resolveProvider,
  withRetry,
} from "@dawn-ai/langchain"

Install the optional LangChain provider package selected by your agents. @langchain/openai is included; Anthropic, Google, Mistral, Groq, Ollama, xAI, and OpenRouter integrations are optional peer dependencies.

Compatibility and audience

SurfaceRuntimePurityAudienceStability
@dawn-ai/langchainedge-safenot-claimedintegrationsupported
@dawn-ai/langchain/package.jsonpackage metadatan/atoolingsupported

The runtime root is edge-safe for Dawn's emitted Hono/workerd target. Compatibility evidence includes the emitted Hono app round trip on Node and a gated real-workerd lane without nodejs_compat; guards bundle the exact surface with the model layer externalized. This is not a dependency-free claim or a promise of generic browser portability: provider integrations, application tools, stores, and dynamically selected imports retain their own requirements. ./package.json is data for tooling, not TypeScript inventory or runtime code.

Public exports

@dawn-ai/langchain

ExportResponsibility
AgentStreamChunkDescribe streamed tokens, tool activity, interrupts, completion, and extensions.
AgentTurnResultDescribe a settled agent turn's output and whether it parked on an interrupt.
DawnToolDefinitionDescribe a Dawn tool accepted by agent materialization.
__resetMaterializedAgentsForTestsReset the process-global materialized-agent cache for tests.
executeAgentConsume an agent stream and return its completed output.
executeAgentTurnExecute one materialized-agent turn and return its structured result.
materializeAgentGraphCompile a Dawn agent descriptor into a LangGraph graph.
streamAgentStream normalized agent chunks.
chainAdapterAdapt a LangChain runnable to Dawn's chain backend contract.
BuiltInModelProviderIdRe-export the SDK-owned built-in provider union.
ModelProviderIdRe-export the SDK-owned provider identifier.
createChatModelLoad and construct a selected provider chat model.
providerPackagesMap built-in provider IDs to integration packages.
seedModelImporterInstall the process-global fallback provider importer.
inferProviderRe-export SDK provider inference.
resolveProviderResolve an explicit provider or infer one from a model ID.
RetryOptionsConfigure retry attempts, backoff, cap, and cancellation.
isRetryableErrorClassify known transient error messages.
withRetryRetry transient async failures with jittered exponential backoff.
openaiEmbedderConstruct the OpenAI-backed memory embedder.
OffloadStoreOptionsConfigure an offload store and its cleanup limits.
buildOffloadFileNameProduce a sanitized deterministic output filename.
OffloadStorePersist tool output and perform throttled best-effort cleanup.
OffloadToolOutputCtxConfigure one conditional tool-output offload.
offloadToolOutputReplace oversized output with a saved-file preview stub.
buildStubFormat a human-readable offloaded-output stub.
OffloadFnDescribe the tool converter's output-offload callback.
convertToolToLangChainConvert a Dawn tool into a LangChain structured tool.
executeWithToolLoopInvoke a chain and execute bounded tool-call rounds.
UnwrappedToolResultDescribe agent-visible content and optional state updates.
unwrapToolResultDecode Dawn's strict { result, state? } tool-return wrapper.
CommandRe-export LangGraph's resume/state-update command.
materializeStateSchemaBuild a LangGraph annotation root from resolved state fields.
ResolvedSubagentGraphDescribe a resolved child route graph.
SubagentResolverResolve an allowed task request to a child graph or rejection.
convertSubagentTaskToLangChainConvert Dawn's task placeholder to a resumable LangChain tool.
RunningSummaryTrack summary text and covered message count.
TokenCounterCount text tokens synchronously or asynchronously.
SummarizeFnDescribe the injected summarization operation.
ResolvedSummarizationConfigHold resolved thresholds and summarization dependencies.
PreModelHookStateDescribe messages and the optional running summary.
PreModelHookResultReturn a model-only message view and updated summary.
buildSummarizationHookBuild the non-destructive pre-model summary hook.
splitForSummarySplit aged messages from recent turns.
defaultSummarizeSummarize messages with the selected chat model.
countMessagesTokensCount tokens across LangChain messages.
defaultTokenCounterCount tokens with the package tokenizer.

__resetMaterializedAgentsForTests is public so the testing harness can reach it, but its name and contract are testing-only; it mutates process-wide cache state and is not an application lifecycle API. Helpers exported by implementation modules but omitted from the root barrel—such as composePromptMessages, AgentOptions, ResolvedStateField, ExecuteWithToolLoopOptions, BuildStubArgs, jsonSchemaToZod, warning/message helpers, and default importers—are not owned exports here.

@dawn-ai/langchain/package.json

This subpath exposes package metadata as JSON for tooling. It has no TypeScript export inventory, runtime compatibility classification, or purity claim; do not execute it as application code.

Key contracts

ts
export interface AgentStreamChunk {
  readonly type: "token" | "tool_call" | "tool_result" | "interrupt" | "done" | (string & {})
  readonly data: unknown
}

Fields: @dawn-ai/langchain#.:AgentStreamChunk

FieldTypeRequiredDescription
readonly type"token" | "tool_call" | "tool_result" | "interrupt" | "done" | (string & {})yesIdentify the chunk kind.
readonly dataunknownyesCarry the chunk payload.
ts
export interface RetryOptions {
  readonly maxAttempts?: number
  readonly baseDelayMs?: number
  readonly maxDelayMs?: number
  readonly signal?: AbortSignal
}

Fields: @dawn-ai/langchain#.:RetryOptions

FieldTypeRequiredDescription
readonly maxAttemptsnumbernoSet total attempts; defaults to 3.
readonly baseDelayMsnumbernoSet the first backoff; defaults to 1000.
readonly maxDelayMsnumbernoCap backoff; defaults to 10000.
readonly signalAbortSignalnoCancel the retry loop.
ts
export declare function resolveProvider(options: {
  readonly model: string
  readonly provider?: ModelProviderId
}): BuiltInModelProviderId
ts
export declare function withRetry<T>(
  fn: () => Promise<T>,
  options?: RetryOptions,
): Promise<T>
ts
export interface OffloadToolOutputCtx {
  readonly toolName: string
  readonly thresholdChars: number
  readonly previewLines: number
  readonly store: Pick<OffloadStore, "write">
  readonly signal?: AbortSignal
  readonly toolCallId?: string
}

Fields: @dawn-ai/langchain#.:OffloadToolOutputCtx

FieldTypeRequiredDescription
readonly toolNamestringyesName the output's tool.
readonly thresholdCharsnumberyesSet the character threshold.
readonly previewLinesnumberyesSet the retained preview length.
readonly storePick<OffloadStore, "write">yesPersist full output.
readonly signalAbortSignalnoCancel the write.
readonly toolCallIdstringnoKey the filename; content hashing is the fallback.
ts
export interface UnwrappedToolResult {
  readonly content: string
  readonly stateUpdates: Record<string, unknown> | undefined
}

Fields: @dawn-ai/langchain#.:UnwrappedToolResult

FieldTypeRequiredDescription
readonly contentstringyesCarry agent-visible content.
readonly stateUpdatesRecord<string, unknown> | undefinedyesCarry optional channel updates.

Several callable exports intentionally expose non-barrel helper shapes in their declarations. Read these shapes inline; they are not independently importable exports:

ts
type Importer = (specifier: string) => Promise<Record<string, unknown>>
type ResolvedStateField = {
  readonly name: string
  readonly reducer: "append" | "replace" | ((current: unknown, incoming: unknown) => unknown)
  readonly default: unknown
}
type ToolExecutor = {
  readonly name: string
  readonly run: (
    input: unknown,
    context: {
      readonly middleware?: Readonly<Record<string, unknown>>
      readonly signal: AbortSignal
    },
  ) => Promise<unknown> | unknown
}
type ExecuteWithToolLoopOptions = {
  readonly chain: { readonly invoke: (input: unknown) => Promise<unknown> }
  readonly input: unknown
  readonly middlewareContext?: Readonly<Record<string, unknown>>
  readonly tools: readonly ToolExecutor[]
  readonly signal: AbortSignal
  readonly maxIterations?: number
}
type BuildStubArgs = {
  readonly content: string
  readonly relPath: string
  readonly previewLines: number
  readonly thresholdChars: number
}

The larger inline AgentOptions shape used by executeAgent and streamAgent requires checkpointer, entry, input, routeParamNames, signal, and tools; it also accepts middleware, retry, state, prompt, offload, summarization, subagent, thread, sandbox, and cache-bypass controls. The subagent converter accepts a private { name, description?, schema? } placeholder, and the tool converter accepts the same basic tool definition plus a run callback. defaultSummarize accepts messages, model, optional previous summary, and signal.

Materialized graphs are cached by descriptor plus checkpointer. Sandbox-bound tools, subagents, stream transformers, and explicit bypass requests skip reuse. A checkpointer is mandatory at runtime; threadId is also required for an interrupted run to resume. Generated edge assembly must seed its static provider importer before model construction.

Behavior contract langchain.provider.explicit

An explicit model provider bypasses provider inference.

Provider lifecycle and failure boundaries

Unknown explicit providers throw with the supported list. If no provider is explicit and inference fails, resolution throws before model construction. seedModelImporter() is last-call-wins process state; seed it during runtime assembly, not per request.

Behavior contract langchain.retry.exhaustion

Retry throws after the configured maximum attempts are exhausted.

Retry failure boundaries

Only recognized transient messages retry. Non-transient failures throw immediately, cancellation throws Operation aborted, and retry delays include up to 500 ms of jitter capped by maxDelayMs.

Behavior contract langchain.tool-loop.limit

The tool loop limits iterations to prevent an infinite loop.

Tool-loop failure boundaries

Unknown tools and thrown tool failures become ToolMessage error content. Reaching the default 10 rounds, or an explicit lower limit, throws rather than returning a partial result.

Behavior contract langchain.chain.stream-fallback

A chain stream falls back to invoke when the entry has no stream method.

Chain, offload, and summarization boundaries

The fallback yields the invocation result once. Both execute and stream reject entries without invoke; native stream() results may be returned directly or through a promise.

Offload thresholds count characters, and the full tool output is written into the workspace; both stored content and preview stubs may contain sensitive data. Filenames sanitize tool names and call IDs; without a call ID they use a content hash. Cleanup is throttled and best-effort, while offloadToolOutput() returns original content if persistence fails. Tool wrapper recognition is strict: extra keys, arrays, missing result, or result: undefined use plain-return handling. Summarization changes only the model's input view; on summarizer failure it falls back to full history for that turn. It is context compression, not a trust or security boundary.

ts
import { chainAdapter, resolveProvider, withRetry } from "@dawn-ai/langchain"
 
const provider = resolveProvider({ model: "gpt-5-mini" })
const runnable = {
  invoke: async (input: { prompt: string }) => ({ provider, answer: input.prompt }),
}
 
const result = await withRetry(
  () =>
    chainAdapter.execute(runnable, { prompt: "hello" }, {
      signal: new AbortController().signal,
    }),
  { maxAttempts: 3 },
)

Continue with Agents, Context Management, Retry, and SDK API.