@agent-ledger/sdk-ts 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +168 -33
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
# @agent-ledger/sdk-ts
|
|
2
2
|
|
|
3
|
-
Official TypeScript client for Agent Ledger.
|
|
3
|
+
Official TypeScript client for Agent Ledger. Use it to instrument any Node.js/Edge agent with structured telemetry, stream session events, and receive immediate feedback when budget guardrails block spending.
|
|
4
|
+
|
|
5
|
+
## Table of contents
|
|
6
|
+
|
|
7
|
+
1. [Features](#features)
|
|
8
|
+
2. [Installation](#installation)
|
|
9
|
+
3. [Runtime requirements](#runtime-requirements)
|
|
10
|
+
4. [Getting started](#getting-started)
|
|
11
|
+
5. [Session lifecycle](#session-lifecycle)
|
|
12
|
+
6. [Event reference](#event-reference)
|
|
13
|
+
7. [API reference](#api-reference)
|
|
14
|
+
8. [Error handling](#error-handling)
|
|
15
|
+
9. [Configuration & environments](#configuration--environments)
|
|
16
|
+
10. [Recipes](#recipes)
|
|
17
|
+
11. [Testing & local dev](#testing--local-dev)
|
|
18
|
+
12. [License](#license)
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Minimal, dependency-free client that speaks directly to the Agent Ledger REST API (`/v1/sessions` and `/v1/events`).
|
|
23
|
+
- First-class TypeScript typings for every event structure (`LlmCallEvent`, `ToolCallEvent`, `ToolResultEvent`).
|
|
24
|
+
- Built-in budget guardrail awareness through `BudgetGuardrailError` so you can halt expensive runs immediately.
|
|
25
|
+
- Works anywhere `fetch` is available (Node.js 18+, Bun, Deno, Edge runtimes, or browsers talking to your own proxy).
|
|
26
|
+
- Simple abstractions so you can reuse the same instrumentation across CLI scripts, background workers, or serverless functions.
|
|
4
27
|
|
|
5
28
|
## Installation
|
|
6
29
|
|
|
@@ -8,77 +31,189 @@ Official TypeScript client for Agent Ledger. The SDK instruments your agents so
|
|
|
8
31
|
pnpm add @agent-ledger/sdk-ts
|
|
9
32
|
# or
|
|
10
33
|
npm install @agent-ledger/sdk-ts
|
|
34
|
+
# or
|
|
35
|
+
yarn add @agent-ledger/sdk-ts
|
|
11
36
|
```
|
|
12
37
|
|
|
13
|
-
##
|
|
38
|
+
## Runtime requirements
|
|
39
|
+
|
|
40
|
+
- Node.js 18 or newer (for the built-in `fetch` implementation). If you run older Node versions, polyfill `fetch` before importing the SDK.
|
|
41
|
+
- An Agent Ledger API key generated from the dashboard (Settings → API Keys).
|
|
42
|
+
- Outbound HTTPS access to `https://agent-ledger-api.azurewebsites.net` (or your self-hosted instance).
|
|
43
|
+
|
|
44
|
+
## Getting started
|
|
14
45
|
|
|
15
46
|
```ts
|
|
16
|
-
import { AgentLedgerClient } from "@agent-ledger/sdk-ts";
|
|
47
|
+
import { AgentLedgerClient, BudgetGuardrailError } from "@agent-ledger/sdk-ts";
|
|
17
48
|
|
|
18
49
|
const ledger = new AgentLedgerClient({
|
|
19
50
|
apiKey: process.env.AGENT_LEDGER_API_KEY!,
|
|
20
|
-
// baseUrl is optional. Defaults to the production Agent Ledger API.
|
|
21
51
|
});
|
|
22
52
|
|
|
23
|
-
async function
|
|
53
|
+
export async function runSupportAgent(prompt: string) {
|
|
24
54
|
const sessionId = await ledger.startSession("support-bot");
|
|
55
|
+
|
|
25
56
|
try {
|
|
57
|
+
// 1. Run your own LLM/tool logic
|
|
58
|
+
const response = await callModel(prompt);
|
|
59
|
+
|
|
60
|
+
// 2. Log the LLM call (Agent Ledger auto-computes spend from provider/model/tokens)
|
|
26
61
|
await ledger.logLLMCall(sessionId, {
|
|
27
62
|
stepIndex: 0,
|
|
28
|
-
model: "gpt-4o",
|
|
29
63
|
provider: "openai",
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
64
|
+
model: "gpt-4o-mini",
|
|
65
|
+
prompt,
|
|
66
|
+
response: response.text,
|
|
67
|
+
tokensIn: response.usage.inputTokens,
|
|
68
|
+
tokensOut: response.usage.outputTokens,
|
|
69
|
+
latencyMs: response.latencyMs,
|
|
35
70
|
});
|
|
36
71
|
|
|
37
|
-
// ...additional tool calls/events...
|
|
38
|
-
|
|
39
72
|
await ledger.endSession(sessionId, "success");
|
|
73
|
+
return response.text;
|
|
40
74
|
} catch (err) {
|
|
75
|
+
if (err instanceof BudgetGuardrailError) {
|
|
76
|
+
console.warn("Budget exceeded", err.details);
|
|
77
|
+
}
|
|
41
78
|
await ledger.endSession(sessionId, "error", { errorMessage: (err as Error).message });
|
|
42
79
|
throw err;
|
|
43
80
|
}
|
|
44
81
|
}
|
|
45
82
|
```
|
|
46
83
|
|
|
47
|
-
##
|
|
84
|
+
## Session lifecycle
|
|
85
|
+
|
|
86
|
+
1. **Start sessions** early with `startSession(agentName)` to capture every downstream event.
|
|
87
|
+
2. **Log events** whenever you call an LLM or tool:
|
|
88
|
+
- `logLLMCall` for prompts/responses.
|
|
89
|
+
- `logToolCall` for tool invocations (store the inputs).
|
|
90
|
+
- `logToolResult` for tool responses (store outputs/latency).
|
|
91
|
+
- `logEvents` if you need to batch arbitrary event objects.
|
|
92
|
+
3. **End sessions** with `endSession(sessionId, "success" | "error", { errorMessage? })` so the dashboard knows whether the run finished cleanly.
|
|
93
|
+
|
|
94
|
+
Tip: keep a simple helper that wraps this flow so every agent in your repo emits consistent telemetry.
|
|
95
|
+
|
|
96
|
+
## Event reference
|
|
97
|
+
|
|
98
|
+
| Event | Required fields | Optional fields | Notes |
|
|
99
|
+
| --- | --- | --- | --- |
|
|
100
|
+
| `LlmCallEvent` | `stepIndex`, `model`, `provider`, `prompt`, `response`, `tokensIn`, `tokensOut`, `latencyMs` | — | `logLLMCall` automatically sets `type` to `llm_call` and lets the backend price the call based on provider/model. |
|
|
101
|
+
| `ToolCallEvent` | `stepIndex`, `toolName`, `toolInput` | — | Capture the structured input you sent to an internal or external tool. |
|
|
102
|
+
| `ToolResultEvent` | `stepIndex`, `toolName`, `toolOutput`, `latencyMs` | — | Use together with `ToolCallEvent` to understand tool latency and result size. |
|
|
103
|
+
| Custom | Whatever your workflow needs plus `type` | — | Supply via `logEvents` if you want to store derived signals (examples: `session_start`, `session_end`, `guardrail_trigger`). |
|
|
104
|
+
|
|
105
|
+
Conventions:
|
|
106
|
+
|
|
107
|
+
- `stepIndex` is a zero-based counter that makes it easy to diff runs. Increment it in the order events happen, even if multiple tools share the same LLM output.
|
|
108
|
+
- Keep prompts/responses under 64 KB per event so they render nicely in the dashboard diff view.
|
|
109
|
+
- All numeric values are stored as numbers (no strings) so the API can aggregate cost statistics.
|
|
110
|
+
|
|
111
|
+
## API reference
|
|
112
|
+
|
|
113
|
+
### `new AgentLedgerClient(options)`
|
|
114
|
+
|
|
115
|
+
| Option | Type | Description |
|
|
116
|
+
| --- | --- | --- |
|
|
117
|
+
| `apiKey` | `string` (required) | Workspace API key from the dashboard. |
|
|
118
|
+
|
|
119
|
+
### `startSession(agentName: string): Promise<string>`
|
|
120
|
+
|
|
121
|
+
Creates a session row and returns its UUID. `agentName` should match how you identify the workflow in the dashboard (e.g., `support-bot`, `retrieval-worker`).
|
|
122
|
+
|
|
123
|
+
### `endSession(sessionId, status, opts?)`
|
|
124
|
+
|
|
125
|
+
Marks the session closed. Pass `{ errorMessage }` for failures so the UI shows context next to the run.
|
|
126
|
+
|
|
127
|
+
### `logEvents(sessionId, events)`
|
|
128
|
+
|
|
129
|
+
Lowest-level ingestion helper. Accepts an array of plain objects, so you can batch multiple events into a single network call. Events must include a `type` string (e.g., `llm_call`).
|
|
48
130
|
|
|
49
|
-
|
|
50
|
-
- `startSession(agentName)` → session ID
|
|
51
|
-
- `endSession(sessionId, status, { errorMessage? })`
|
|
52
|
-
- `logEvents(sessionId, events)` (low-level entry point)
|
|
53
|
-
- `logLLMCall`, `logToolCall`, `logToolResult` (typed helpers)
|
|
131
|
+
### `logLLMCall(sessionId, event)` / `logToolCall` / `logToolResult`
|
|
54
132
|
|
|
55
|
-
|
|
133
|
+
Typed helpers that:
|
|
56
134
|
|
|
57
|
-
|
|
135
|
+
- Fill the `type` automatically.
|
|
136
|
+
- Validate required fields at compile time.
|
|
137
|
+
- Call `logEvents` under the hood.
|
|
58
138
|
|
|
59
|
-
|
|
139
|
+
### Types exported
|
|
140
|
+
|
|
141
|
+
`AgentLedgerClient`, `AgentLedgerClientOptions`, `BudgetGuardrailError`, `BudgetGuardrailDetails`, `LlmCallEvent`, `ToolCallEvent`, `ToolResultEvent`, `AnyEvent`, `EventType`.
|
|
142
|
+
|
|
143
|
+
## Error handling
|
|
144
|
+
|
|
145
|
+
- **`BudgetGuardrailError`** (HTTP 429): thrown when the backend refuses the event because the agent exceeded its daily limit. Inspect `error.details`:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
{
|
|
149
|
+
agentName: string;
|
|
150
|
+
dailyLimitUsd: number;
|
|
151
|
+
spentTodayUsd: number;
|
|
152
|
+
attemptedCostUsd: number;
|
|
153
|
+
projectedCostUsd: number;
|
|
154
|
+
remainingBudgetUsd: number;
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
- **Generic `Error`**: wraps any other non-2xx response (`startSession`, `endSession`, `logEvents`). The `.message` contains the server-provided text when available.
|
|
159
|
+
|
|
160
|
+
Recommended practice: catch errors where you call `logEvents` so your business logic can continue (or at least emit a structured failure) even when the telemetry call is rejected.
|
|
161
|
+
|
|
162
|
+
## Configuration & environments
|
|
163
|
+
|
|
164
|
+
- Provide `AGENT_LEDGER_API_KEY` (or load it from your preferred secrets manager) and the SDK connects to the hosted API automatically.
|
|
165
|
+
- Default endpoint → `https://agent-ledger-api.azurewebsites.net`.
|
|
166
|
+
- For local API experiments, keep the SDK untouched and proxy traffic through your own tooling (MSW, mock servers, etc.).
|
|
167
|
+
|
|
168
|
+
Because the client is stateless, you can instantiate one per agent type or share a singleton across the entire app.
|
|
169
|
+
|
|
170
|
+
## Recipes
|
|
171
|
+
|
|
172
|
+
### Streaming agents / multi-step workflows
|
|
173
|
+
|
|
174
|
+
Reuse a monotonically increasing `stepIndex` while you stream partial responses. You can emit interim tool calls before the final LLM response lands to visualize branching logic.
|
|
175
|
+
|
|
176
|
+
### Custom tool instrumentation
|
|
60
177
|
|
|
61
178
|
```ts
|
|
62
|
-
|
|
179
|
+
async function callWeather(sessionId: string, city: string, stepIndex: number) {
|
|
180
|
+
await ledger.logToolCall(sessionId, {
|
|
181
|
+
stepIndex,
|
|
182
|
+
toolName: "weather",
|
|
183
|
+
toolInput: { city },
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
const result = await fetchWeather(city);
|
|
187
|
+
|
|
188
|
+
await ledger.logToolResult(sessionId, {
|
|
189
|
+
stepIndex,
|
|
190
|
+
toolName: "weather",
|
|
191
|
+
toolOutput: result,
|
|
192
|
+
latencyMs: result.latencyMs,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
```
|
|
63
196
|
|
|
197
|
+
### Handling guardrail blocks
|
|
198
|
+
|
|
199
|
+
```ts
|
|
64
200
|
try {
|
|
65
|
-
await ledger.
|
|
201
|
+
await ledger.logLLMCall(sessionId, event);
|
|
66
202
|
} catch (err) {
|
|
67
203
|
if (err instanceof BudgetGuardrailError) {
|
|
68
|
-
|
|
204
|
+
await ledger.endSession(sessionId, "error", {
|
|
205
|
+
errorMessage: `Budget exceeded: remaining ${err.details.remainingBudgetUsd}`,
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
69
208
|
}
|
|
209
|
+
throw err;
|
|
70
210
|
}
|
|
71
211
|
```
|
|
72
212
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
- `baseUrl` option overrides the API host per client.
|
|
76
|
-
- When omitted, the SDK looks for `process.env.AGENT_LEDGER_BASE_URL` and falls back to `https://agent-ledger-api.azurewebsites.net`.
|
|
77
|
-
- For local testing, set `AGENT_LEDGER_BASE_URL=http://localhost:3000` (or your tunnel URL) before instantiating the client.
|
|
78
|
-
|
|
79
|
-
## TypeScript support
|
|
213
|
+
## Testing & local dev
|
|
80
214
|
|
|
81
|
-
|
|
215
|
+
- The SDK performs real HTTP requests. For unit tests, stub `global.fetch` or intercept calls with tools like [MSW](https://mswjs.io/).
|
|
216
|
+
- When running the Agent Ledger API locally, ensure your test key exists in the development database and export it via `AGENT_LEDGER_API_KEY`.
|
|
82
217
|
|
|
83
218
|
## License
|
|
84
219
|
|