Skip to content

Commit d023c2f

Browse files
committed
docs: expand package READMEs
1 parent e6b3494 commit d023c2f

7 files changed

Lines changed: 552 additions & 41 deletions

File tree

README.md

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,6 @@ const message = await complete(model!, {
4545
console.log(message.content);
4646
```
4747

48-
## Requirements
49-
50-
Node `>=18.17.0`. The provider adapters use `globalThis.fetch` directly — no
51-
ponyfill, no polyfill. All supported runtimes (modern browsers, Bun, Deno, and
52-
Node 18.17+) ship a Web-standard fetch with a `ReadableStream` body, which the
53-
adapters need for SSE.
54-
5548
## Consuming from webpack / Next.js
5649

5750
The packages publish ESM with `.js`-suffixed relative imports (e.g.

packages/agent/README.md

Lines changed: 154 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,159 @@
11
# @agentic-kit/agent
22

3-
Minimal stateful agent runtime for `agentic-kit`.
3+
<p align="center" width="100%">
4+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5+
</p>
46

5-
This package provides:
7+
<p align="center" width="100%">
8+
<a href="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml">
9+
<img height="20" src="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml/badge.svg" />
10+
</a>
11+
<a href="https://github.com/constructive-io/agentic-kit/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12+
<a href="https://www.npmjs.com/package/@agentic-kit/agent"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/agentic-kit?filename=packages%2Fagent%2Fpackage.json"/></a>
13+
</p>
614

7-
- sequential tool execution
8-
- lifecycle events for UI and orchestration
9-
- abort and continue semantics
10-
- pluggable context transforms
15+
Minimal stateful agent runtime built on `agentic-kit`. The `Agent` class drives
16+
a sequential model/tool loop, emits structured lifecycle events, and exposes a
17+
run handle that can be consumed as async events, a `ReadableStream`, or an SSE
18+
`Response` for transport to a frontend.
1119

12-
It is intentionally minimal in v1 and sits on top of the lower-level
13-
`agentic-kit` provider portability layer.
20+
## Installation
21+
22+
```bash
23+
npm install @agentic-kit/agent agentic-kit
24+
```
25+
26+
## Quick Start
27+
28+
```ts
29+
import { Agent } from '@agentic-kit/agent';
30+
import { getModel } from 'agentic-kit';
31+
32+
const agent = new Agent({
33+
initialState: {
34+
model: getModel('openai', 'gpt-5.4-mini')!,
35+
systemPrompt: 'You are a helpful assistant.',
36+
tools: [],
37+
},
38+
});
39+
40+
await agent.prompt('What is 2 + 2?');
41+
console.log(agent.state.messages);
42+
```
43+
44+
## Streaming a Run
45+
46+
The `prompt()` and `continue()` methods return an `AgentRunHandle`. Awaiting it
47+
runs to completion; treating it as a stream yields lifecycle events.
48+
49+
```ts
50+
const handle = agent.prompt('Plan a trip to Lisbon.');
51+
52+
for await (const event of handle.events()) {
53+
if (event.type === 'message_update') {
54+
process.stdout.write(JSON.stringify(event.assistantMessageEvent));
55+
}
56+
}
57+
```
58+
59+
A handle can be consumed exactly once, in one of these ways:
60+
61+
- `await handle` — run to completion without observing events.
62+
- `handle.events()` — iterate `AgentEvent`s.
63+
- `handle.toReadableStream()` — wrap events in a `ReadableStream<AgentEvent>`.
64+
- `handle.toResponse(init?)` — wrap events as an SSE `Response`, ready to
65+
return from a Next.js / Hono / Express handler.
66+
67+
## SSE Transport
68+
69+
`toResponse()` serializes events as `data: <json>\n\n` frames. On the client,
70+
parse them back into `AgentEvent`s with `parseSSEStream`:
71+
72+
```ts
73+
import { parseSSEStream } from '@agentic-kit/agent';
74+
75+
const response = await fetch('/api/chat', { method: 'POST', body });
76+
for await (const event of parseSSEStream(response.body!)) {
77+
// event is a typed AgentEvent
78+
}
79+
```
80+
81+
## Tools, Decisions, and Pauses
82+
83+
Tools extend the base `ToolDefinition` from `agentic-kit` with an executor and
84+
an optional human-in-the-loop `decision` schema. When a tool with a `decision`
85+
schema is called and no decision is attached, the agent emits a
86+
`tool_decision_pending` event and pauses. Attach the decision to the matching
87+
`toolCall` block and call `continue()` to resume.
88+
89+
```ts
90+
const sendEmail: AgentTool = {
91+
name: 'send_email',
92+
label: 'Send email',
93+
description: 'Send an email to a recipient.',
94+
parameters: {
95+
type: 'object',
96+
properties: { to: { type: 'string' }, body: { type: 'string' } },
97+
required: ['to', 'body'],
98+
},
99+
decision: {
100+
type: 'object',
101+
properties: { approved: { type: 'boolean' } },
102+
required: ['approved'],
103+
},
104+
execute: async (toolCallId, args, decision) => {
105+
if (!(decision as { approved: boolean }).approved) {
106+
return { content: [{ type: 'text', text: 'Cancelled by user.' }] };
107+
}
108+
// ... send email
109+
return { content: [{ type: 'text', text: 'Sent.' }] };
110+
},
111+
};
112+
```
113+
114+
## Agent API
115+
116+
```ts
117+
new Agent(options: AgentOptions)
118+
```
119+
120+
`AgentOptions`:
121+
122+
- `initialState` — must include a `model`; `systemPrompt`, `tools`, and
123+
`messages` are optional.
124+
- `maxSteps` — cap on model invocations per run. Resets in `prompt()`,
125+
persists across `continue()`.
126+
- `streamFn` — override the underlying stream function (defaults to
127+
`stream` from `agentic-kit`).
128+
- `transformContext(messages, signal)` — async hook to rewrite the message
129+
list before each model call (compaction, summarization, retrieval).
130+
- `validateToolArguments(schema, args)` — override tool argument validation.
131+
Default uses a built-in JSON Schema subset.
132+
133+
State mutation:
134+
135+
- `setModel`, `setSystemPrompt`, `setTools`, `setStreamOptions`
136+
- `replaceMessages`, `appendMessage`, `clearMessages`, `reset`
137+
138+
Execution:
139+
140+
- `prompt(input, opts?)` — start a new run from a user message.
141+
- `continue(opts?)` — resume after a paused decision or after the messages
142+
array was edited externally.
143+
- `abort()` — cancel the active run.
144+
- `waitForIdle()` — resolves when the current run finishes.
145+
- `subscribe(listener)` — receive `AgentEvent`s without consuming the handle.
146+
147+
## Event Types
148+
149+
`AgentEvent` is a discriminated union covering the full lifecycle:
150+
151+
- `agent_start`, `agent_end` (with `stopReason: 'completed' | 'max_steps'`)
152+
- `turn_start`, `turn_end`
153+
- `message_start`, `message_update`, `message_end`
154+
- `tool_execution_start`, `tool_execution_update`, `tool_execution_end`
155+
- `tool_decision_pending` (carries `input` and `schema`)
156+
157+
Every `message_update` includes the underlying `assistantMessageEvent` from
158+
the provider stream (text/thinking/toolcall deltas), so consumers can render
159+
streaming text without re-deriving it from the partial message.

packages/agentic-kit/README.md

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,41 @@ for await (const event of result) {
6767
- `stream(model: ModelDescriptor, context: Context, options?: StreamOptions)`
6868
- `complete(model: ModelDescriptor, context: Context, options?: StreamOptions)`
6969
- `completeText(model: ModelDescriptor, context: Context, options?: StreamOptions)`
70-
- `registerModel(model: ModelDescriptor): void`
71-
- `registerProvider(provider: ProviderAdapter): void`
72-
- `getModel(provider: string, modelId: string): ModelDescriptor | undefined`
73-
- `getModels(provider?: string): ModelDescriptor[]`
70+
71+
### Registry
72+
73+
- `registerModel(model)`, `registerModels(models)`, `clearModels()`
74+
- `registerProvider(provider, sourceId?)`, `unregisterProviders(sourceId)`, `clearProviders()`
75+
- `getModel(provider, modelId)`, `getModels(provider?)`, `getModelProviders()`
76+
- `getProvider(api)`, `getRegisteredProviders()`
77+
78+
The package pre-registers `OpenAIAdapter`, `AnthropicAdapter`, and
79+
`OllamaAdapter` (with empty credentials) plus the built-in model catalogs
80+
from each adapter package. Re-register an adapter with your own API key to
81+
activate it.
82+
83+
### Message helpers
84+
85+
- `createUserMessage(content)`, `createAssistantMessage(model)`,
86+
`createToolResultMessage(toolCallId, toolName, content, isError?)`
87+
- `createTextContent(text?)`, `createImageContent(data, mimeType)`,
88+
`createToolCall(id, name)`
89+
- `getMessageText(assistant)` — concatenate text blocks.
90+
- `cloneMessage(message)` — deep clone.
91+
- `normalizeContext(context)` — apply per-message normalization.
92+
- `injectDeferralResults(messages, options?)` — synthesize stand-in
93+
`toolResult` messages for every `toolCall` that lacks both a decision and
94+
a paired result. Useful when the user types a new message instead of
95+
responding to a paused tool — the next request needs a well-formed
96+
transcript.
97+
- `transformMessages(messages, model)` — cross-provider normalization for
98+
replay across different providers.
99+
100+
### Adapter re-exports
101+
102+
- `OpenAIAdapter`, `AnthropicAdapter`, `OllamaAdapter`
103+
- Types: `OpenAIOptions`, `AnthropicOptions`
104+
- `OllamaClient` for direct Ollama HTTP access.
74105

75106
### Legacy Compatibility API
76107

packages/anthropic/README.md

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,94 @@
1212
<a href="https://www.npmjs.com/package/@agentic-kit/anthropic"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/agentic-kit?filename=packages%2Fanthropic%2Fpackage.json"/></a>
1313
</p>
1414

15-
Anthropic (Claude) adapter for agentic-kit with SSE streaming support.
15+
Anthropic (Claude) adapter for `agentic-kit`. Speaks the Messages API over
16+
SSE, surfaces text / thinking / tool-call deltas as structured events, and
17+
plugs into the shared model and provider registries.
1618

1719
## Installation
1820

1921
```bash
20-
npm install @agentic-kit/anthropic
22+
npm install @agentic-kit/anthropic agentic-kit
2123
```
2224

25+
## Usage
26+
27+
The adapter can either be used directly or registered with the shared
28+
`agentic-kit` provider registry.
29+
30+
### Direct adapter
31+
32+
```ts
33+
import { AnthropicAdapter } from '@agentic-kit/anthropic';
34+
35+
const adapter = new AnthropicAdapter({ apiKey: process.env.ANTHROPIC_API_KEY! });
36+
const model = adapter.createModel('claude-sonnet-4-5');
37+
38+
const result = adapter.stream(model, {
39+
messages: [{ role: 'user', content: 'Hello', timestamp: Date.now() }],
40+
});
41+
42+
for await (const event of result) {
43+
if (event.type === 'text_delta') {
44+
process.stdout.write(event.delta);
45+
}
46+
}
47+
```
48+
49+
### Through `agentic-kit`
50+
51+
The base `agentic-kit` package pre-registers an Anthropic adapter with an
52+
empty key. Override it with your own key once at startup:
53+
54+
```ts
55+
import { registerProvider, stream, getModel } from 'agentic-kit';
56+
import { AnthropicAdapter } from '@agentic-kit/anthropic';
57+
58+
registerProvider(new AnthropicAdapter({ apiKey: process.env.ANTHROPIC_API_KEY! }));
59+
60+
const model = getModel('anthropic', 'claude-sonnet-4-5')!;
61+
const result = stream(model, { messages: [...] });
62+
```
63+
64+
## API Reference
65+
66+
### `new AnthropicAdapter(options | apiKey)`
67+
68+
`AnthropicOptions`:
69+
70+
- `apiKey` — required.
71+
- `baseUrl` — defaults to `https://api.anthropic.com/v1`.
72+
- `defaultModel` — defaults to `claude-sonnet-4-5`.
73+
- `provider` — override the registry key (defaults to `'anthropic'`).
74+
- `headers` — extra headers merged into every request.
75+
- `maxTokens` — default `max_tokens` when neither model nor request sets one.
76+
77+
### `adapter.createModel(modelId, overrides?)`
78+
79+
Returns a `ModelDescriptor`. If `modelId` matches a built-in entry in
80+
`ANTHROPIC_MODELS`, the built-in is used as a base; otherwise a generic
81+
descriptor is synthesized.
82+
83+
### `adapter.stream(model, context, options?)`
84+
85+
Starts a streaming request and returns an `AssistantMessageEventStream` — an
86+
async iterable of `AssistantMessageEvent`s with a `.result()` promise for the
87+
final `AssistantMessage`.
88+
89+
`StreamOptions`:
90+
91+
- `apiKey`, `headers` — per-request overrides.
92+
- `maxTokens`, `temperature`.
93+
- `reasoning``'minimal' | 'low' | 'medium' | 'high' | 'xhigh'`. Enables
94+
Claude extended thinking; maps to a token budget (`256``16384`).
95+
- `onPayload` — observe the raw request body before send.
96+
- `signal` — abort the request mid-stream.
97+
98+
### `adapter.listModels()`
99+
100+
Returns the entries from `ANTHROPIC_MODELS` for this adapter's provider key.
101+
102+
### `ANTHROPIC_MODELS`
103+
104+
Built-in `ModelDescriptor[]` with cost, context window, and capability
105+
metadata for the latest Claude tier (Sonnet 4.5, Haiku 4.5).

packages/ollama/README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ await client.deleteModel('mistral');
6262

6363
- `new OllamaClient(baseUrl?: string)` – defaults to `http://localhost:11434`
6464
- `.listModels(): Promise<string[]>`
65+
- `.showModel(model: string): Promise<{ capabilities?: string[] } | null>`
6566
- `.generate(input: GenerateInput, onChunk?: (chunk: string) => void): Promise<string | void>`
66-
- `.generateEmbedding(text: string): Promise<number[]>`
67+
- `.generateEmbedding(text: string, model?: string): Promise<number[]>` — defaults to `nomic-embed-text`
6768
- `.pullModel(model: string): Promise<void>`
6869
- `.deleteModel(model: string): Promise<void>`
6970

@@ -107,11 +108,17 @@ Notes:
107108
```ts
108109
interface GenerateInput {
109110
model: string;
110-
prompt: string;
111+
prompt?: string;
112+
messages?: ChatMessage[];
113+
system?: string;
111114
stream?: boolean;
115+
temperature?: number;
116+
maxTokens?: number;
112117
}
113118
```
114119

120+
Either `prompt` (single-turn) or `messages` (multi-turn) must be set.
121+
115122
## Contributing
116123

117124
Please open issues or pull requests on [GitHub](https://github.com/constructive-io/agentic-kit).

0 commit comments

Comments
 (0)