@merkie/agentic 0.1.0
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/LICENSE +21 -0
- package/README.md +93 -0
- package/dist/index.cjs +229 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +57 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.js +193 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Merkie
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# @merkie/agentic
|
|
2
|
+
|
|
3
|
+
> Batteries-included helpers for building LLM-powered apps with the [Vercel AI SDK](https://sdk.vercel.ai) and [OpenRouter](https://openrouter.ai).
|
|
4
|
+
|
|
5
|
+
Most AI SDK setups are bring-your-own-everything. `@merkie/agentic` is the start of a
|
|
6
|
+
framework that ships the boring-but-essential plumbing — observability,
|
|
7
|
+
persistence, and resilience — so you can focus on your agent code instead of
|
|
8
|
+
copy-pasting the same cost-tracking and logging boilerplate into every project.
|
|
9
|
+
|
|
10
|
+
This first release ships two things:
|
|
11
|
+
|
|
12
|
+
- **`createOpenRouter`** — a drop-in replacement for the provider factory that
|
|
13
|
+
auto-enables usage/cost accounting and reads your API key from the
|
|
14
|
+
environment.
|
|
15
|
+
- **`logStream`** — pretty-prints an AI SDK stream in real time (reasoning,
|
|
16
|
+
messages, tool calls/results) with live token and cost accounting.
|
|
17
|
+
|
|
18
|
+
> **Status:** early. The logging here will eventually be backed by a real
|
|
19
|
+
> persistence/observability layer; `chalk` and friends are temporary.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @merkie/agentic ai @openrouter/ai-sdk-provider
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`ai` and `@openrouter/ai-sdk-provider` are peer dependencies — you bring the
|
|
28
|
+
versions your app already uses.
|
|
29
|
+
|
|
30
|
+
Works in TypeScript and JavaScript, ESM and CommonJS.
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { streamText } from "ai";
|
|
36
|
+
import { createOpenRouter, logStream } from "@merkie/agentic";
|
|
37
|
+
|
|
38
|
+
// Reads OPENROUTER_API_KEY from the environment and turns on usage tracking.
|
|
39
|
+
const openrouter = createOpenRouter();
|
|
40
|
+
|
|
41
|
+
const result = streamText({
|
|
42
|
+
model: openrouter("openai/gpt-4o-mini"),
|
|
43
|
+
prompt: "Explain quantum tunneling in one paragraph.",
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
await logStream(result.fullStream);
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
CommonJS:
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
const { createOpenRouter, logStream } = require("@merkie/agentic");
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## API
|
|
56
|
+
|
|
57
|
+
### `createOpenRouter(settings?)`
|
|
58
|
+
|
|
59
|
+
Same signature and return type as `createOpenRouter` from
|
|
60
|
+
`@openrouter/ai-sdk-provider`, with two defaults applied:
|
|
61
|
+
|
|
62
|
+
| Default | Behavior | Override |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `apiKey` | Falls back to `process.env.OPENROUTER_API_KEY` | Pass `apiKey` |
|
|
65
|
+
| `extraBody.usage.include` | `true` (returns cost + token usage) | Pass `extraBody.usage` |
|
|
66
|
+
|
|
67
|
+
Every option you pass wins over the defaults, so it's 1:1 compatible with the
|
|
68
|
+
upstream factory:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const openrouter = createOpenRouter({
|
|
72
|
+
apiKey: myKey,
|
|
73
|
+
extraBody: {
|
|
74
|
+
transforms: ["middle-out"],
|
|
75
|
+
usage: { include: false }, // opt back out if you want
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### `logStream(stream)`
|
|
81
|
+
|
|
82
|
+
Consumes an `AsyncIterable` of AI SDK `TextStreamPart`s (i.e. the `fullStream`
|
|
83
|
+
from `streamText`) and prints each event as it arrives. When the model is served
|
|
84
|
+
through `createOpenRouter`, it also reports per-run cost and context-window
|
|
85
|
+
usage on completion.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
await logStream(result.fullStream);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT © Merkie
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
createOpenRouter: () => createOpenRouter,
|
|
34
|
+
logStream: () => logStream
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/openrouter.ts
|
|
39
|
+
var import_ai_sdk_provider = require("@openrouter/ai-sdk-provider");
|
|
40
|
+
function createOpenRouter(settings = {}) {
|
|
41
|
+
const { apiKey, extraBody, ...rest } = settings;
|
|
42
|
+
const userUsage = extraBody && typeof extraBody === "object" && "usage" in extraBody ? extraBody.usage : void 0;
|
|
43
|
+
return (0, import_ai_sdk_provider.createOpenRouter)({
|
|
44
|
+
apiKey: apiKey ?? process.env.OPENROUTER_API_KEY,
|
|
45
|
+
...rest,
|
|
46
|
+
extraBody: {
|
|
47
|
+
...extraBody,
|
|
48
|
+
usage: {
|
|
49
|
+
include: true,
|
|
50
|
+
...userUsage && typeof userUsage === "object" ? userUsage : {}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/logStream.ts
|
|
57
|
+
var import_chalk = __toESM(require("chalk"), 1);
|
|
58
|
+
var openRouterContextLengthCache = /* @__PURE__ */ new Map();
|
|
59
|
+
function getOpenRouterCost(part) {
|
|
60
|
+
if (part.type !== "finish-step") return null;
|
|
61
|
+
const metadataUsage = part.providerMetadata?.openrouter?.usage;
|
|
62
|
+
const rawUsage = part.usage.raw;
|
|
63
|
+
const cost = metadataUsage?.cost ?? rawUsage?.cost;
|
|
64
|
+
const upstreamInferenceCost = metadataUsage?.costDetails?.upstreamInferenceCost ?? rawUsage?.cost_details?.upstream_inference_cost;
|
|
65
|
+
if (cost === 0 && upstreamInferenceCost != null) {
|
|
66
|
+
return upstreamInferenceCost;
|
|
67
|
+
}
|
|
68
|
+
return cost ?? upstreamInferenceCost ?? null;
|
|
69
|
+
}
|
|
70
|
+
function formatCost(cost) {
|
|
71
|
+
return `$${cost.toFixed(6)}`;
|
|
72
|
+
}
|
|
73
|
+
function formatTokens(tokens) {
|
|
74
|
+
return tokens.toLocaleString("en-US");
|
|
75
|
+
}
|
|
76
|
+
function parsePositiveInteger(value) {
|
|
77
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0) {
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
if (typeof value === "string") {
|
|
81
|
+
const parsed = Number(value);
|
|
82
|
+
if (Number.isInteger(parsed) && parsed > 0) {
|
|
83
|
+
return parsed;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
function getOpenRouterContextLengthFromResponse(payload) {
|
|
89
|
+
const data = payload.data;
|
|
90
|
+
return parsePositiveInteger(data?.context_length) ?? parsePositiveInteger(data?.top_provider?.context_length);
|
|
91
|
+
}
|
|
92
|
+
async function fetchOpenRouterContextLength(modelId) {
|
|
93
|
+
const pathModelId = modelId.split("/").map(encodeURIComponent).join("/");
|
|
94
|
+
const response = await fetch(
|
|
95
|
+
`https://openrouter.ai/api/v1/model/${pathModelId}`
|
|
96
|
+
);
|
|
97
|
+
if (!response.ok) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return getOpenRouterContextLengthFromResponse(await response.json());
|
|
101
|
+
}
|
|
102
|
+
function getOpenRouterContextLength(modelId) {
|
|
103
|
+
const cached = openRouterContextLengthCache.get(modelId);
|
|
104
|
+
if (cached) return cached;
|
|
105
|
+
const promise = fetchOpenRouterContextLength(modelId).catch(() => null);
|
|
106
|
+
openRouterContextLengthCache.set(modelId, promise);
|
|
107
|
+
return promise;
|
|
108
|
+
}
|
|
109
|
+
function getModelId(part) {
|
|
110
|
+
if (part.type === "start-step") {
|
|
111
|
+
const body = part.request.body;
|
|
112
|
+
if (body && typeof body === "object" && "model" in body) {
|
|
113
|
+
const model = body.model;
|
|
114
|
+
if (typeof model === "string" && model.length > 0) {
|
|
115
|
+
return model;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (part.type === "finish-step") {
|
|
120
|
+
return part.response.modelId;
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
function getUsageTokens(usage) {
|
|
125
|
+
if (!usage) return null;
|
|
126
|
+
if (usage.inputTokens != null || usage.outputTokens != null) {
|
|
127
|
+
return (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
|
|
128
|
+
}
|
|
129
|
+
return usage.totalTokens ?? null;
|
|
130
|
+
}
|
|
131
|
+
function formatContextUsage(usage, contextWindowTokens) {
|
|
132
|
+
const tokens = getUsageTokens(usage);
|
|
133
|
+
if (tokens == null) return "context used ?";
|
|
134
|
+
if (contextWindowTokens == null) {
|
|
135
|
+
return `context used ${formatTokens(tokens)} tokens`;
|
|
136
|
+
}
|
|
137
|
+
const percentage = tokens / contextWindowTokens * 100;
|
|
138
|
+
const formattedPercentage = percentage > 0 && percentage < 0.01 ? "<0.01" : percentage.toFixed(2);
|
|
139
|
+
return `${formattedPercentage}% context used (${formatTokens(tokens)} / ${formatTokens(contextWindowTokens)} tokens)`;
|
|
140
|
+
}
|
|
141
|
+
async function logStream(stream) {
|
|
142
|
+
let active = null;
|
|
143
|
+
let openRouterCost = 0;
|
|
144
|
+
let hasOpenRouterCost = false;
|
|
145
|
+
let latestStepUsage;
|
|
146
|
+
let contextWindowPromise;
|
|
147
|
+
const endActive = () => {
|
|
148
|
+
if (active) process.stdout.write("\n");
|
|
149
|
+
active = null;
|
|
150
|
+
};
|
|
151
|
+
const startContextWindowFetch = (modelId) => {
|
|
152
|
+
if (!modelId || contextWindowPromise) return;
|
|
153
|
+
contextWindowPromise = getOpenRouterContextLength(modelId);
|
|
154
|
+
};
|
|
155
|
+
for await (const part of stream) {
|
|
156
|
+
switch (part.type) {
|
|
157
|
+
case "start-step":
|
|
158
|
+
endActive();
|
|
159
|
+
startContextWindowFetch(getModelId(part));
|
|
160
|
+
console.log(import_chalk.default.dim("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 step \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
|
|
161
|
+
break;
|
|
162
|
+
case "finish-step": {
|
|
163
|
+
latestStepUsage = part.usage;
|
|
164
|
+
startContextWindowFetch(getModelId(part));
|
|
165
|
+
const cost = getOpenRouterCost(part);
|
|
166
|
+
if (cost != null) {
|
|
167
|
+
openRouterCost += cost;
|
|
168
|
+
hasOpenRouterCost = true;
|
|
169
|
+
}
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
case "reasoning-delta":
|
|
173
|
+
if (active !== "reasoning") {
|
|
174
|
+
endActive();
|
|
175
|
+
process.stdout.write(import_chalk.default.magenta.bold("\u{1F9E0} reasoning "));
|
|
176
|
+
active = "reasoning";
|
|
177
|
+
}
|
|
178
|
+
process.stdout.write(import_chalk.default.magenta(part.text));
|
|
179
|
+
break;
|
|
180
|
+
case "text-delta":
|
|
181
|
+
if (active !== "text") {
|
|
182
|
+
endActive();
|
|
183
|
+
process.stdout.write(import_chalk.default.white.bold("\u{1F4AC} message "));
|
|
184
|
+
active = "text";
|
|
185
|
+
}
|
|
186
|
+
process.stdout.write(import_chalk.default.white(part.text));
|
|
187
|
+
break;
|
|
188
|
+
case "tool-call":
|
|
189
|
+
endActive();
|
|
190
|
+
console.log(
|
|
191
|
+
import_chalk.default.cyan.bold(`\u{1F527} tool call ${part.toolName}`) + import_chalk.default.cyan(`(${JSON.stringify(part.input)})`)
|
|
192
|
+
);
|
|
193
|
+
break;
|
|
194
|
+
case "tool-result":
|
|
195
|
+
endActive();
|
|
196
|
+
console.log(
|
|
197
|
+
import_chalk.default.green.bold(`\u2705 tool result ${part.toolName} `) + import_chalk.default.green(JSON.stringify(part.output))
|
|
198
|
+
);
|
|
199
|
+
break;
|
|
200
|
+
case "tool-error":
|
|
201
|
+
endActive();
|
|
202
|
+
console.log(
|
|
203
|
+
import_chalk.default.red.bold(`\u274C tool error ${part.toolName} `) + import_chalk.default.red(String(part.error))
|
|
204
|
+
);
|
|
205
|
+
break;
|
|
206
|
+
case "error":
|
|
207
|
+
endActive();
|
|
208
|
+
console.log(import_chalk.default.red.bold("\u203C\uFE0F stream error "), part.error);
|
|
209
|
+
break;
|
|
210
|
+
case "finish": {
|
|
211
|
+
endActive();
|
|
212
|
+
const contextWindowTokens = contextWindowPromise ? await contextWindowPromise : null;
|
|
213
|
+
console.log(
|
|
214
|
+
import_chalk.default.dim(
|
|
215
|
+
`
|
|
216
|
+
\u2500\u2500 done (${part.finishReason}) \xB7 ${formatContextUsage(latestStepUsage, contextWindowTokens)}${hasOpenRouterCost ? ` \xB7 cost ${formatCost(openRouterCost)}` : ""} \u2500\u2500`
|
|
217
|
+
)
|
|
218
|
+
);
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
225
|
+
0 && (module.exports = {
|
|
226
|
+
createOpenRouter,
|
|
227
|
+
logStream
|
|
228
|
+
});
|
|
229
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/openrouter.ts","../src/logStream.ts"],"sourcesContent":["export {\n\tcreateOpenRouter,\n\ttype OpenRouterProvider,\n\ttype OpenRouterProviderSettings,\n} from \"./openrouter.js\";\nexport { logStream } from \"./logStream.js\";\n","import {\n\tcreateOpenRouter as baseCreateOpenRouter,\n\ttype OpenRouterProvider,\n\ttype OpenRouterProviderSettings,\n} from \"@openrouter/ai-sdk-provider\";\n\n/**\n * Drop-in replacement for `createOpenRouter` from `@openrouter/ai-sdk-provider`.\n *\n * It behaves identically to the original, with two conveniences baked in:\n *\n * 1. `apiKey` defaults to `process.env.OPENROUTER_API_KEY` when you don't pass\n * one, so the common case is just `createOpenRouter()`.\n * 2. `extraBody.usage.include` defaults to `true`, which tells OpenRouter to\n * return cost + token accounting on every response. This is what powers the\n * mid-run cost/usage tracking in {@link logStream}.\n *\n * Every option you pass through wins over the defaults — including `usage` — so\n * this is 1:1 compatible with the upstream `createOpenRouter`. You can override\n * the api key, add your own `extraBody`, flip `usage.include` off, etc.\n *\n * @example\n * ```ts\n * import { createOpenRouter } from \"@merkie/agentic\";\n *\n * // Reads OPENROUTER_API_KEY from the environment, usage tracking on.\n * const openrouter = createOpenRouter();\n *\n * const model = openrouter(\"openai/gpt-4o-mini\");\n * ```\n */\nexport function createOpenRouter(\n\tsettings: OpenRouterProviderSettings = {},\n): OpenRouterProvider {\n\tconst { apiKey, extraBody, ...rest } = settings;\n\n\tconst userUsage =\n\t\textraBody && typeof extraBody === \"object\" && \"usage\" in extraBody\n\t\t\t? (extraBody as Record<string, unknown>).usage\n\t\t\t: undefined;\n\n\treturn baseCreateOpenRouter({\n\t\tapiKey: apiKey ?? process.env.OPENROUTER_API_KEY,\n\t\t...rest,\n\t\textraBody: {\n\t\t\t...extraBody,\n\t\t\tusage: {\n\t\t\t\tinclude: true,\n\t\t\t\t...(userUsage && typeof userUsage === \"object\"\n\t\t\t\t\t? (userUsage as Record<string, unknown>)\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t},\n\t});\n}\n\nexport type { OpenRouterProvider, OpenRouterProviderSettings };\n","import type { LanguageModelUsage, TextStreamPart, ToolSet } from \"ai\";\nimport chalk from \"chalk\";\n\ntype OpenRouterUsageCost = {\n\tcost?: number;\n\tcostDetails?: {\n\t\tupstreamInferenceCost?: number | null;\n\t};\n};\n\ntype OpenRouterModelResponse = {\n\tdata?: {\n\t\tcontext_length?: unknown;\n\t\ttop_provider?: {\n\t\t\tcontext_length?: unknown;\n\t\t};\n\t};\n};\n\nconst openRouterContextLengthCache = new Map<string, Promise<number | null>>();\n\nfunction getOpenRouterCost(part: TextStreamPart<ToolSet>) {\n\tif (part.type !== \"finish-step\") return null;\n\n\tconst metadataUsage = part.providerMetadata?.openrouter?.usage as\n\t\t| OpenRouterUsageCost\n\t\t| undefined;\n\tconst rawUsage = part.usage.raw as\n\t\t| {\n\t\t\t\tcost?: number;\n\t\t\t\tcost_details?: { upstream_inference_cost?: number | null };\n\t\t }\n\t\t| undefined;\n\n\tconst cost = metadataUsage?.cost ?? rawUsage?.cost;\n\tconst upstreamInferenceCost =\n\t\tmetadataUsage?.costDetails?.upstreamInferenceCost ??\n\t\trawUsage?.cost_details?.upstream_inference_cost;\n\n\t// OpenRouter credit usage reports `cost`; BYOK usage can report `cost: 0`\n\t// with the real provider charge in `upstreamInferenceCost`.\n\tif (cost === 0 && upstreamInferenceCost != null) {\n\t\treturn upstreamInferenceCost;\n\t}\n\n\treturn cost ?? upstreamInferenceCost ?? null;\n}\n\nfunction formatCost(cost: number) {\n\treturn `$${cost.toFixed(6)}`;\n}\n\nfunction formatTokens(tokens: number) {\n\treturn tokens.toLocaleString(\"en-US\");\n}\n\nfunction parsePositiveInteger(value: unknown) {\n\tif (typeof value === \"number\" && Number.isInteger(value) && value > 0) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isInteger(parsed) && parsed > 0) {\n\t\t\treturn parsed;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction getOpenRouterContextLengthFromResponse(payload: unknown) {\n\tconst data = (payload as OpenRouterModelResponse).data;\n\treturn (\n\t\tparsePositiveInteger(data?.context_length) ??\n\t\tparsePositiveInteger(data?.top_provider?.context_length)\n\t);\n}\n\nasync function fetchOpenRouterContextLength(modelId: string) {\n\tconst pathModelId = modelId.split(\"/\").map(encodeURIComponent).join(\"/\");\n\tconst response = await fetch(\n\t\t`https://openrouter.ai/api/v1/model/${pathModelId}`,\n\t);\n\n\tif (!response.ok) {\n\t\treturn null;\n\t}\n\n\treturn getOpenRouterContextLengthFromResponse(await response.json());\n}\n\nfunction getOpenRouterContextLength(modelId: string) {\n\tconst cached = openRouterContextLengthCache.get(modelId);\n\tif (cached) return cached;\n\n\tconst promise = fetchOpenRouterContextLength(modelId).catch(() => null);\n\topenRouterContextLengthCache.set(modelId, promise);\n\treturn promise;\n}\n\nfunction getModelId(part: TextStreamPart<ToolSet>) {\n\tif (part.type === \"start-step\") {\n\t\tconst body = part.request.body;\n\t\tif (body && typeof body === \"object\" && \"model\" in body) {\n\t\t\tconst model = body.model;\n\t\t\tif (typeof model === \"string\" && model.length > 0) {\n\t\t\t\treturn model;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (part.type === \"finish-step\") {\n\t\treturn part.response.modelId;\n\t}\n\n\treturn null;\n}\n\nfunction getUsageTokens(usage: LanguageModelUsage | undefined) {\n\tif (!usage) return null;\n\n\t// Context usage is the stopping-point conversation size estimate:\n\t// the last step's input tokens are the full history before the final response,\n\t// and its output tokens are what will be appended to that history. An exact\n\t// \"next empty user message\" count would require another provider tokenization\n\t// pass because the stream does not emit usage for hypothetical future calls.\n\tif (usage.inputTokens != null || usage.outputTokens != null) {\n\t\treturn (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n\t}\n\n\treturn usage.totalTokens ?? null;\n}\n\nfunction formatContextUsage(\n\tusage: LanguageModelUsage | undefined,\n\tcontextWindowTokens: number | null,\n) {\n\tconst tokens = getUsageTokens(usage);\n\tif (tokens == null) return \"context used ?\";\n\n\tif (contextWindowTokens == null) {\n\t\treturn `context used ${formatTokens(tokens)} tokens`;\n\t}\n\n\tconst percentage = (tokens / contextWindowTokens) * 100;\n\tconst formattedPercentage =\n\t\tpercentage > 0 && percentage < 0.01 ? \"<0.01\" : percentage.toFixed(2);\n\n\treturn `${formattedPercentage}% context used (${formatTokens(tokens)} / ${formatTokens(contextWindowTokens)} tokens)`;\n}\n\n/**\n * Pretty-prints every event coming off an AI SDK full stream so you can watch\n * the model think, talk, and call tools in real time — and see live token /\n * cost accounting when the model is served through OpenRouter (see\n * {@link createOpenRouter}).\n *\n * Pass it the `fullStream` from `streamText`:\n *\n * @example\n * ```ts\n * import { streamText } from \"ai\";\n * import { createOpenRouter, logStream } from \"@merkie/agentic\";\n *\n * const openrouter = createOpenRouter();\n *\n * const result = streamText({\n * model: openrouter(\"openai/gpt-4o-mini\"),\n * prompt: \"Explain quantum tunneling in one paragraph.\",\n * });\n *\n * await logStream(result.fullStream);\n * ```\n */\nexport async function logStream(\n\tstream: AsyncIterable<TextStreamPart<ToolSet>>,\n): Promise<void> {\n\t// Track which \"channel\" (reasoning vs. text) we're currently writing to so we\n\t// only print a header when it changes, and stream deltas onto the same line.\n\tlet active: \"reasoning\" | \"text\" | null = null;\n\tlet openRouterCost = 0;\n\tlet hasOpenRouterCost = false;\n\tlet latestStepUsage: LanguageModelUsage | undefined;\n\tlet contextWindowPromise: Promise<number | null> | undefined;\n\n\tconst endActive = () => {\n\t\tif (active) process.stdout.write(\"\\n\");\n\t\tactive = null;\n\t};\n\n\tconst startContextWindowFetch = (modelId: string | null) => {\n\t\tif (!modelId || contextWindowPromise) return;\n\t\tcontextWindowPromise = getOpenRouterContextLength(modelId);\n\t};\n\n\tfor await (const part of stream) {\n\t\tswitch (part.type) {\n\t\t\tcase \"start-step\":\n\t\t\t\tendActive();\n\t\t\t\tstartContextWindowFetch(getModelId(part));\n\t\t\t\tconsole.log(chalk.dim(\"──────── step ────────\"));\n\t\t\t\tbreak;\n\n\t\t\tcase \"finish-step\": {\n\t\t\t\tlatestStepUsage = part.usage;\n\t\t\t\tstartContextWindowFetch(getModelId(part));\n\t\t\t\tconst cost = getOpenRouterCost(part);\n\t\t\t\tif (cost != null) {\n\t\t\t\t\topenRouterCost += cost;\n\t\t\t\t\thasOpenRouterCost = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"reasoning-delta\":\n\t\t\t\tif (active !== \"reasoning\") {\n\t\t\t\t\tendActive();\n\t\t\t\t\tprocess.stdout.write(chalk.magenta.bold(\"🧠 reasoning \"));\n\t\t\t\t\tactive = \"reasoning\";\n\t\t\t\t}\n\t\t\t\tprocess.stdout.write(chalk.magenta(part.text));\n\t\t\t\tbreak;\n\n\t\t\tcase \"text-delta\":\n\t\t\t\tif (active !== \"text\") {\n\t\t\t\t\tendActive();\n\t\t\t\t\tprocess.stdout.write(chalk.white.bold(\"💬 message \"));\n\t\t\t\t\tactive = \"text\";\n\t\t\t\t}\n\t\t\t\tprocess.stdout.write(chalk.white(part.text));\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-call\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.cyan.bold(`🔧 tool call ${part.toolName}`) +\n\t\t\t\t\t\tchalk.cyan(`(${JSON.stringify(part.input)})`),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-result\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green.bold(`✅ tool result ${part.toolName} `) +\n\t\t\t\t\t\tchalk.green(JSON.stringify(part.output)),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-error\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.red.bold(`❌ tool error ${part.toolName} `) +\n\t\t\t\t\t\tchalk.red(String(part.error)),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"error\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(chalk.red.bold(\"‼️ stream error \"), part.error);\n\t\t\t\tbreak;\n\n\t\t\tcase \"finish\": {\n\t\t\t\tendActive();\n\t\t\t\tconst contextWindowTokens = contextWindowPromise\n\t\t\t\t\t? await contextWindowPromise\n\t\t\t\t\t: null;\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t`\\n── done (${part.finishReason}) · ${formatContextUsage(latestStepUsage, contextWindowTokens)}${hasOpenRouterCost ? ` · cost ${formatCost(openRouterCost)}` : \"\"} ──`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport default logStream;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,6BAIO;AA2BA,SAAS,iBACf,WAAuC,CAAC,GACnB;AACrB,QAAM,EAAE,QAAQ,WAAW,GAA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QAAM,MAAM,KAAK,IAAI,CAAC;AAC3C;AAAA,MAED,KAAK;AACJ,kBAAU;AACV,gBAAQ;AAAA,UACP,aAAAA,QAAM,KAAK,KAAK,wBAAiB,KAAK,QAAQ,EAAE,IAC/C,aAAAA,QAAM,KAAK,IAAI,KAAK,UAAU,KAAK,KAAK,CAAC,GAAG;AAAA,QAC9C;AACA;AAAA,MAED,KAAK;AACJ,kBAAU;AACV,gBAAQ;AAAA,UACP,aAAAA,QAAM,MAAM,KAAK,sBAAiB,KAAK,QAAQ,GAAG,IACjD,aAAAA,QAAM,MAAM,KAAK,UAAU,KAAK,MAAM,CAAC;AAAA,QACzC;AACA;AAAA,MAED,KAAK;AACJ,kBAAU;AACV,gBAAQ;AAAA,UACP,aAAAA,QAAM,IAAI,KAAK,qBAAgB,KAAK,QAAQ,GAAG,IAC9C,aAAAA,QAAM,IAAI,OAAO,KAAK,KAAK,CAAC;AAAA,QAC9B;AACA;AAAA,MAED,KAAK;AACJ,kBAAU;AACV,gBAAQ,IAAI,aAAAA,QAAM,IAAI,KAAK,6BAAmB,GAAG,KAAK,KAAK;AAC3D;AAAA,MAED,KAAK,UAAU;AACd,kBAAU;AACV,cAAM,sBAAsB,uBACzB,MAAM,uBACN;AACH,gBAAQ;AAAA,UACP,aAAAA,QAAM;AAAA,YACL;AAAA,qBAAc,KAAK,YAAY,UAAO,mBAAmB,iBAAiB,mBAAmB,CAAC,GAAG,oBAAoB,cAAW,WAAW,cAAc,CAAC,KAAK,EAAE;AAAA,UAClK;AAAA,QACD;AACA;AAAA,MACD;AAAA,IACD;AAAA,EACD;AACD;","names":["baseCreateOpenRouter","chalk"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { OpenRouterProviderSettings, OpenRouterProvider } from '@openrouter/ai-sdk-provider';
|
|
2
|
+
export { OpenRouterProvider, OpenRouterProviderSettings } from '@openrouter/ai-sdk-provider';
|
|
3
|
+
import { TextStreamPart, ToolSet } from 'ai';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Drop-in replacement for `createOpenRouter` from `@openrouter/ai-sdk-provider`.
|
|
7
|
+
*
|
|
8
|
+
* It behaves identically to the original, with two conveniences baked in:
|
|
9
|
+
*
|
|
10
|
+
* 1. `apiKey` defaults to `process.env.OPENROUTER_API_KEY` when you don't pass
|
|
11
|
+
* one, so the common case is just `createOpenRouter()`.
|
|
12
|
+
* 2. `extraBody.usage.include` defaults to `true`, which tells OpenRouter to
|
|
13
|
+
* return cost + token accounting on every response. This is what powers the
|
|
14
|
+
* mid-run cost/usage tracking in {@link logStream}.
|
|
15
|
+
*
|
|
16
|
+
* Every option you pass through wins over the defaults — including `usage` — so
|
|
17
|
+
* this is 1:1 compatible with the upstream `createOpenRouter`. You can override
|
|
18
|
+
* the api key, add your own `extraBody`, flip `usage.include` off, etc.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { createOpenRouter } from "@merkie/agentic";
|
|
23
|
+
*
|
|
24
|
+
* // Reads OPENROUTER_API_KEY from the environment, usage tracking on.
|
|
25
|
+
* const openrouter = createOpenRouter();
|
|
26
|
+
*
|
|
27
|
+
* const model = openrouter("openai/gpt-4o-mini");
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function createOpenRouter(settings?: OpenRouterProviderSettings): OpenRouterProvider;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Pretty-prints every event coming off an AI SDK full stream so you can watch
|
|
34
|
+
* the model think, talk, and call tools in real time — and see live token /
|
|
35
|
+
* cost accounting when the model is served through OpenRouter (see
|
|
36
|
+
* {@link createOpenRouter}).
|
|
37
|
+
*
|
|
38
|
+
* Pass it the `fullStream` from `streamText`:
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { streamText } from "ai";
|
|
43
|
+
* import { createOpenRouter, logStream } from "@merkie/agentic";
|
|
44
|
+
*
|
|
45
|
+
* const openrouter = createOpenRouter();
|
|
46
|
+
*
|
|
47
|
+
* const result = streamText({
|
|
48
|
+
* model: openrouter("openai/gpt-4o-mini"),
|
|
49
|
+
* prompt: "Explain quantum tunneling in one paragraph.",
|
|
50
|
+
* });
|
|
51
|
+
*
|
|
52
|
+
* await logStream(result.fullStream);
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function logStream(stream: AsyncIterable<TextStreamPart<ToolSet>>): Promise<void>;
|
|
56
|
+
|
|
57
|
+
export { createOpenRouter, logStream };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { OpenRouterProviderSettings, OpenRouterProvider } from '@openrouter/ai-sdk-provider';
|
|
2
|
+
export { OpenRouterProvider, OpenRouterProviderSettings } from '@openrouter/ai-sdk-provider';
|
|
3
|
+
import { TextStreamPart, ToolSet } from 'ai';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Drop-in replacement for `createOpenRouter` from `@openrouter/ai-sdk-provider`.
|
|
7
|
+
*
|
|
8
|
+
* It behaves identically to the original, with two conveniences baked in:
|
|
9
|
+
*
|
|
10
|
+
* 1. `apiKey` defaults to `process.env.OPENROUTER_API_KEY` when you don't pass
|
|
11
|
+
* one, so the common case is just `createOpenRouter()`.
|
|
12
|
+
* 2. `extraBody.usage.include` defaults to `true`, which tells OpenRouter to
|
|
13
|
+
* return cost + token accounting on every response. This is what powers the
|
|
14
|
+
* mid-run cost/usage tracking in {@link logStream}.
|
|
15
|
+
*
|
|
16
|
+
* Every option you pass through wins over the defaults — including `usage` — so
|
|
17
|
+
* this is 1:1 compatible with the upstream `createOpenRouter`. You can override
|
|
18
|
+
* the api key, add your own `extraBody`, flip `usage.include` off, etc.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { createOpenRouter } from "@merkie/agentic";
|
|
23
|
+
*
|
|
24
|
+
* // Reads OPENROUTER_API_KEY from the environment, usage tracking on.
|
|
25
|
+
* const openrouter = createOpenRouter();
|
|
26
|
+
*
|
|
27
|
+
* const model = openrouter("openai/gpt-4o-mini");
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function createOpenRouter(settings?: OpenRouterProviderSettings): OpenRouterProvider;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Pretty-prints every event coming off an AI SDK full stream so you can watch
|
|
34
|
+
* the model think, talk, and call tools in real time — and see live token /
|
|
35
|
+
* cost accounting when the model is served through OpenRouter (see
|
|
36
|
+
* {@link createOpenRouter}).
|
|
37
|
+
*
|
|
38
|
+
* Pass it the `fullStream` from `streamText`:
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { streamText } from "ai";
|
|
43
|
+
* import { createOpenRouter, logStream } from "@merkie/agentic";
|
|
44
|
+
*
|
|
45
|
+
* const openrouter = createOpenRouter();
|
|
46
|
+
*
|
|
47
|
+
* const result = streamText({
|
|
48
|
+
* model: openrouter("openai/gpt-4o-mini"),
|
|
49
|
+
* prompt: "Explain quantum tunneling in one paragraph.",
|
|
50
|
+
* });
|
|
51
|
+
*
|
|
52
|
+
* await logStream(result.fullStream);
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function logStream(stream: AsyncIterable<TextStreamPart<ToolSet>>): Promise<void>;
|
|
56
|
+
|
|
57
|
+
export { createOpenRouter, logStream };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// src/openrouter.ts
|
|
2
|
+
import {
|
|
3
|
+
createOpenRouter as baseCreateOpenRouter
|
|
4
|
+
} from "@openrouter/ai-sdk-provider";
|
|
5
|
+
function createOpenRouter(settings = {}) {
|
|
6
|
+
const { apiKey, extraBody, ...rest } = settings;
|
|
7
|
+
const userUsage = extraBody && typeof extraBody === "object" && "usage" in extraBody ? extraBody.usage : void 0;
|
|
8
|
+
return baseCreateOpenRouter({
|
|
9
|
+
apiKey: apiKey ?? process.env.OPENROUTER_API_KEY,
|
|
10
|
+
...rest,
|
|
11
|
+
extraBody: {
|
|
12
|
+
...extraBody,
|
|
13
|
+
usage: {
|
|
14
|
+
include: true,
|
|
15
|
+
...userUsage && typeof userUsage === "object" ? userUsage : {}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/logStream.ts
|
|
22
|
+
import chalk from "chalk";
|
|
23
|
+
var openRouterContextLengthCache = /* @__PURE__ */ new Map();
|
|
24
|
+
function getOpenRouterCost(part) {
|
|
25
|
+
if (part.type !== "finish-step") return null;
|
|
26
|
+
const metadataUsage = part.providerMetadata?.openrouter?.usage;
|
|
27
|
+
const rawUsage = part.usage.raw;
|
|
28
|
+
const cost = metadataUsage?.cost ?? rawUsage?.cost;
|
|
29
|
+
const upstreamInferenceCost = metadataUsage?.costDetails?.upstreamInferenceCost ?? rawUsage?.cost_details?.upstream_inference_cost;
|
|
30
|
+
if (cost === 0 && upstreamInferenceCost != null) {
|
|
31
|
+
return upstreamInferenceCost;
|
|
32
|
+
}
|
|
33
|
+
return cost ?? upstreamInferenceCost ?? null;
|
|
34
|
+
}
|
|
35
|
+
function formatCost(cost) {
|
|
36
|
+
return `$${cost.toFixed(6)}`;
|
|
37
|
+
}
|
|
38
|
+
function formatTokens(tokens) {
|
|
39
|
+
return tokens.toLocaleString("en-US");
|
|
40
|
+
}
|
|
41
|
+
function parsePositiveInteger(value) {
|
|
42
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0) {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
if (typeof value === "string") {
|
|
46
|
+
const parsed = Number(value);
|
|
47
|
+
if (Number.isInteger(parsed) && parsed > 0) {
|
|
48
|
+
return parsed;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
function getOpenRouterContextLengthFromResponse(payload) {
|
|
54
|
+
const data = payload.data;
|
|
55
|
+
return parsePositiveInteger(data?.context_length) ?? parsePositiveInteger(data?.top_provider?.context_length);
|
|
56
|
+
}
|
|
57
|
+
async function fetchOpenRouterContextLength(modelId) {
|
|
58
|
+
const pathModelId = modelId.split("/").map(encodeURIComponent).join("/");
|
|
59
|
+
const response = await fetch(
|
|
60
|
+
`https://openrouter.ai/api/v1/model/${pathModelId}`
|
|
61
|
+
);
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
return getOpenRouterContextLengthFromResponse(await response.json());
|
|
66
|
+
}
|
|
67
|
+
function getOpenRouterContextLength(modelId) {
|
|
68
|
+
const cached = openRouterContextLengthCache.get(modelId);
|
|
69
|
+
if (cached) return cached;
|
|
70
|
+
const promise = fetchOpenRouterContextLength(modelId).catch(() => null);
|
|
71
|
+
openRouterContextLengthCache.set(modelId, promise);
|
|
72
|
+
return promise;
|
|
73
|
+
}
|
|
74
|
+
function getModelId(part) {
|
|
75
|
+
if (part.type === "start-step") {
|
|
76
|
+
const body = part.request.body;
|
|
77
|
+
if (body && typeof body === "object" && "model" in body) {
|
|
78
|
+
const model = body.model;
|
|
79
|
+
if (typeof model === "string" && model.length > 0) {
|
|
80
|
+
return model;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (part.type === "finish-step") {
|
|
85
|
+
return part.response.modelId;
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function getUsageTokens(usage) {
|
|
90
|
+
if (!usage) return null;
|
|
91
|
+
if (usage.inputTokens != null || usage.outputTokens != null) {
|
|
92
|
+
return (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
|
|
93
|
+
}
|
|
94
|
+
return usage.totalTokens ?? null;
|
|
95
|
+
}
|
|
96
|
+
function formatContextUsage(usage, contextWindowTokens) {
|
|
97
|
+
const tokens = getUsageTokens(usage);
|
|
98
|
+
if (tokens == null) return "context used ?";
|
|
99
|
+
if (contextWindowTokens == null) {
|
|
100
|
+
return `context used ${formatTokens(tokens)} tokens`;
|
|
101
|
+
}
|
|
102
|
+
const percentage = tokens / contextWindowTokens * 100;
|
|
103
|
+
const formattedPercentage = percentage > 0 && percentage < 0.01 ? "<0.01" : percentage.toFixed(2);
|
|
104
|
+
return `${formattedPercentage}% context used (${formatTokens(tokens)} / ${formatTokens(contextWindowTokens)} tokens)`;
|
|
105
|
+
}
|
|
106
|
+
async function logStream(stream) {
|
|
107
|
+
let active = null;
|
|
108
|
+
let openRouterCost = 0;
|
|
109
|
+
let hasOpenRouterCost = false;
|
|
110
|
+
let latestStepUsage;
|
|
111
|
+
let contextWindowPromise;
|
|
112
|
+
const endActive = () => {
|
|
113
|
+
if (active) process.stdout.write("\n");
|
|
114
|
+
active = null;
|
|
115
|
+
};
|
|
116
|
+
const startContextWindowFetch = (modelId) => {
|
|
117
|
+
if (!modelId || contextWindowPromise) return;
|
|
118
|
+
contextWindowPromise = getOpenRouterContextLength(modelId);
|
|
119
|
+
};
|
|
120
|
+
for await (const part of stream) {
|
|
121
|
+
switch (part.type) {
|
|
122
|
+
case "start-step":
|
|
123
|
+
endActive();
|
|
124
|
+
startContextWindowFetch(getModelId(part));
|
|
125
|
+
console.log(chalk.dim("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 step \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
|
|
126
|
+
break;
|
|
127
|
+
case "finish-step": {
|
|
128
|
+
latestStepUsage = part.usage;
|
|
129
|
+
startContextWindowFetch(getModelId(part));
|
|
130
|
+
const cost = getOpenRouterCost(part);
|
|
131
|
+
if (cost != null) {
|
|
132
|
+
openRouterCost += cost;
|
|
133
|
+
hasOpenRouterCost = true;
|
|
134
|
+
}
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
case "reasoning-delta":
|
|
138
|
+
if (active !== "reasoning") {
|
|
139
|
+
endActive();
|
|
140
|
+
process.stdout.write(chalk.magenta.bold("\u{1F9E0} reasoning "));
|
|
141
|
+
active = "reasoning";
|
|
142
|
+
}
|
|
143
|
+
process.stdout.write(chalk.magenta(part.text));
|
|
144
|
+
break;
|
|
145
|
+
case "text-delta":
|
|
146
|
+
if (active !== "text") {
|
|
147
|
+
endActive();
|
|
148
|
+
process.stdout.write(chalk.white.bold("\u{1F4AC} message "));
|
|
149
|
+
active = "text";
|
|
150
|
+
}
|
|
151
|
+
process.stdout.write(chalk.white(part.text));
|
|
152
|
+
break;
|
|
153
|
+
case "tool-call":
|
|
154
|
+
endActive();
|
|
155
|
+
console.log(
|
|
156
|
+
chalk.cyan.bold(`\u{1F527} tool call ${part.toolName}`) + chalk.cyan(`(${JSON.stringify(part.input)})`)
|
|
157
|
+
);
|
|
158
|
+
break;
|
|
159
|
+
case "tool-result":
|
|
160
|
+
endActive();
|
|
161
|
+
console.log(
|
|
162
|
+
chalk.green.bold(`\u2705 tool result ${part.toolName} `) + chalk.green(JSON.stringify(part.output))
|
|
163
|
+
);
|
|
164
|
+
break;
|
|
165
|
+
case "tool-error":
|
|
166
|
+
endActive();
|
|
167
|
+
console.log(
|
|
168
|
+
chalk.red.bold(`\u274C tool error ${part.toolName} `) + chalk.red(String(part.error))
|
|
169
|
+
);
|
|
170
|
+
break;
|
|
171
|
+
case "error":
|
|
172
|
+
endActive();
|
|
173
|
+
console.log(chalk.red.bold("\u203C\uFE0F stream error "), part.error);
|
|
174
|
+
break;
|
|
175
|
+
case "finish": {
|
|
176
|
+
endActive();
|
|
177
|
+
const contextWindowTokens = contextWindowPromise ? await contextWindowPromise : null;
|
|
178
|
+
console.log(
|
|
179
|
+
chalk.dim(
|
|
180
|
+
`
|
|
181
|
+
\u2500\u2500 done (${part.finishReason}) \xB7 ${formatContextUsage(latestStepUsage, contextWindowTokens)}${hasOpenRouterCost ? ` \xB7 cost ${formatCost(openRouterCost)}` : ""} \u2500\u2500`
|
|
182
|
+
)
|
|
183
|
+
);
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
export {
|
|
190
|
+
createOpenRouter,
|
|
191
|
+
logStream
|
|
192
|
+
};
|
|
193
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openrouter.ts","../src/logStream.ts"],"sourcesContent":["import {\n\tcreateOpenRouter as baseCreateOpenRouter,\n\ttype OpenRouterProvider,\n\ttype OpenRouterProviderSettings,\n} from \"@openrouter/ai-sdk-provider\";\n\n/**\n * Drop-in replacement for `createOpenRouter` from `@openrouter/ai-sdk-provider`.\n *\n * It behaves identically to the original, with two conveniences baked in:\n *\n * 1. `apiKey` defaults to `process.env.OPENROUTER_API_KEY` when you don't pass\n * one, so the common case is just `createOpenRouter()`.\n * 2. `extraBody.usage.include` defaults to `true`, which tells OpenRouter to\n * return cost + token accounting on every response. This is what powers the\n * mid-run cost/usage tracking in {@link logStream}.\n *\n * Every option you pass through wins over the defaults — including `usage` — so\n * this is 1:1 compatible with the upstream `createOpenRouter`. You can override\n * the api key, add your own `extraBody`, flip `usage.include` off, etc.\n *\n * @example\n * ```ts\n * import { createOpenRouter } from \"@merkie/agentic\";\n *\n * // Reads OPENROUTER_API_KEY from the environment, usage tracking on.\n * const openrouter = createOpenRouter();\n *\n * const model = openrouter(\"openai/gpt-4o-mini\");\n * ```\n */\nexport function createOpenRouter(\n\tsettings: OpenRouterProviderSettings = {},\n): OpenRouterProvider {\n\tconst { apiKey, extraBody, ...rest } = settings;\n\n\tconst userUsage =\n\t\textraBody && typeof extraBody === \"object\" && \"usage\" in extraBody\n\t\t\t? (extraBody as Record<string, unknown>).usage\n\t\t\t: undefined;\n\n\treturn baseCreateOpenRouter({\n\t\tapiKey: apiKey ?? process.env.OPENROUTER_API_KEY,\n\t\t...rest,\n\t\textraBody: {\n\t\t\t...extraBody,\n\t\t\tusage: {\n\t\t\t\tinclude: true,\n\t\t\t\t...(userUsage && typeof userUsage === \"object\"\n\t\t\t\t\t? (userUsage as Record<string, unknown>)\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t},\n\t});\n}\n\nexport type { OpenRouterProvider, OpenRouterProviderSettings };\n","import type { LanguageModelUsage, TextStreamPart, ToolSet } from \"ai\";\nimport chalk from \"chalk\";\n\ntype OpenRouterUsageCost = {\n\tcost?: number;\n\tcostDetails?: {\n\t\tupstreamInferenceCost?: number | null;\n\t};\n};\n\ntype OpenRouterModelResponse = {\n\tdata?: {\n\t\tcontext_length?: unknown;\n\t\ttop_provider?: {\n\t\t\tcontext_length?: unknown;\n\t\t};\n\t};\n};\n\nconst openRouterContextLengthCache = new Map<string, Promise<number | null>>();\n\nfunction getOpenRouterCost(part: TextStreamPart<ToolSet>) {\n\tif (part.type !== \"finish-step\") return null;\n\n\tconst metadataUsage = part.providerMetadata?.openrouter?.usage as\n\t\t| OpenRouterUsageCost\n\t\t| undefined;\n\tconst rawUsage = part.usage.raw as\n\t\t| {\n\t\t\t\tcost?: number;\n\t\t\t\tcost_details?: { upstream_inference_cost?: number | null };\n\t\t }\n\t\t| undefined;\n\n\tconst cost = metadataUsage?.cost ?? rawUsage?.cost;\n\tconst upstreamInferenceCost =\n\t\tmetadataUsage?.costDetails?.upstreamInferenceCost ??\n\t\trawUsage?.cost_details?.upstream_inference_cost;\n\n\t// OpenRouter credit usage reports `cost`; BYOK usage can report `cost: 0`\n\t// with the real provider charge in `upstreamInferenceCost`.\n\tif (cost === 0 && upstreamInferenceCost != null) {\n\t\treturn upstreamInferenceCost;\n\t}\n\n\treturn cost ?? upstreamInferenceCost ?? null;\n}\n\nfunction formatCost(cost: number) {\n\treturn `$${cost.toFixed(6)}`;\n}\n\nfunction formatTokens(tokens: number) {\n\treturn tokens.toLocaleString(\"en-US\");\n}\n\nfunction parsePositiveInteger(value: unknown) {\n\tif (typeof value === \"number\" && Number.isInteger(value) && value > 0) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isInteger(parsed) && parsed > 0) {\n\t\t\treturn parsed;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction getOpenRouterContextLengthFromResponse(payload: unknown) {\n\tconst data = (payload as OpenRouterModelResponse).data;\n\treturn (\n\t\tparsePositiveInteger(data?.context_length) ??\n\t\tparsePositiveInteger(data?.top_provider?.context_length)\n\t);\n}\n\nasync function fetchOpenRouterContextLength(modelId: string) {\n\tconst pathModelId = modelId.split(\"/\").map(encodeURIComponent).join(\"/\");\n\tconst response = await fetch(\n\t\t`https://openrouter.ai/api/v1/model/${pathModelId}`,\n\t);\n\n\tif (!response.ok) {\n\t\treturn null;\n\t}\n\n\treturn getOpenRouterContextLengthFromResponse(await response.json());\n}\n\nfunction getOpenRouterContextLength(modelId: string) {\n\tconst cached = openRouterContextLengthCache.get(modelId);\n\tif (cached) return cached;\n\n\tconst promise = fetchOpenRouterContextLength(modelId).catch(() => null);\n\topenRouterContextLengthCache.set(modelId, promise);\n\treturn promise;\n}\n\nfunction getModelId(part: TextStreamPart<ToolSet>) {\n\tif (part.type === \"start-step\") {\n\t\tconst body = part.request.body;\n\t\tif (body && typeof body === \"object\" && \"model\" in body) {\n\t\t\tconst model = body.model;\n\t\t\tif (typeof model === \"string\" && model.length > 0) {\n\t\t\t\treturn model;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (part.type === \"finish-step\") {\n\t\treturn part.response.modelId;\n\t}\n\n\treturn null;\n}\n\nfunction getUsageTokens(usage: LanguageModelUsage | undefined) {\n\tif (!usage) return null;\n\n\t// Context usage is the stopping-point conversation size estimate:\n\t// the last step's input tokens are the full history before the final response,\n\t// and its output tokens are what will be appended to that history. An exact\n\t// \"next empty user message\" count would require another provider tokenization\n\t// pass because the stream does not emit usage for hypothetical future calls.\n\tif (usage.inputTokens != null || usage.outputTokens != null) {\n\t\treturn (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n\t}\n\n\treturn usage.totalTokens ?? null;\n}\n\nfunction formatContextUsage(\n\tusage: LanguageModelUsage | undefined,\n\tcontextWindowTokens: number | null,\n) {\n\tconst tokens = getUsageTokens(usage);\n\tif (tokens == null) return \"context used ?\";\n\n\tif (contextWindowTokens == null) {\n\t\treturn `context used ${formatTokens(tokens)} tokens`;\n\t}\n\n\tconst percentage = (tokens / contextWindowTokens) * 100;\n\tconst formattedPercentage =\n\t\tpercentage > 0 && percentage < 0.01 ? \"<0.01\" : percentage.toFixed(2);\n\n\treturn `${formattedPercentage}% context used (${formatTokens(tokens)} / ${formatTokens(contextWindowTokens)} tokens)`;\n}\n\n/**\n * Pretty-prints every event coming off an AI SDK full stream so you can watch\n * the model think, talk, and call tools in real time — and see live token /\n * cost accounting when the model is served through OpenRouter (see\n * {@link createOpenRouter}).\n *\n * Pass it the `fullStream` from `streamText`:\n *\n * @example\n * ```ts\n * import { streamText } from \"ai\";\n * import { createOpenRouter, logStream } from \"@merkie/agentic\";\n *\n * const openrouter = createOpenRouter();\n *\n * const result = streamText({\n * model: openrouter(\"openai/gpt-4o-mini\"),\n * prompt: \"Explain quantum tunneling in one paragraph.\",\n * });\n *\n * await logStream(result.fullStream);\n * ```\n */\nexport async function logStream(\n\tstream: AsyncIterable<TextStreamPart<ToolSet>>,\n): Promise<void> {\n\t// Track which \"channel\" (reasoning vs. text) we're currently writing to so we\n\t// only print a header when it changes, and stream deltas onto the same line.\n\tlet active: \"reasoning\" | \"text\" | null = null;\n\tlet openRouterCost = 0;\n\tlet hasOpenRouterCost = false;\n\tlet latestStepUsage: LanguageModelUsage | undefined;\n\tlet contextWindowPromise: Promise<number | null> | undefined;\n\n\tconst endActive = () => {\n\t\tif (active) process.stdout.write(\"\\n\");\n\t\tactive = null;\n\t};\n\n\tconst startContextWindowFetch = (modelId: string | null) => {\n\t\tif (!modelId || contextWindowPromise) return;\n\t\tcontextWindowPromise = getOpenRouterContextLength(modelId);\n\t};\n\n\tfor await (const part of stream) {\n\t\tswitch (part.type) {\n\t\t\tcase \"start-step\":\n\t\t\t\tendActive();\n\t\t\t\tstartContextWindowFetch(getModelId(part));\n\t\t\t\tconsole.log(chalk.dim(\"──────── step ────────\"));\n\t\t\t\tbreak;\n\n\t\t\tcase \"finish-step\": {\n\t\t\t\tlatestStepUsage = part.usage;\n\t\t\t\tstartContextWindowFetch(getModelId(part));\n\t\t\t\tconst cost = getOpenRouterCost(part);\n\t\t\t\tif (cost != null) {\n\t\t\t\t\topenRouterCost += cost;\n\t\t\t\t\thasOpenRouterCost = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"reasoning-delta\":\n\t\t\t\tif (active !== \"reasoning\") {\n\t\t\t\t\tendActive();\n\t\t\t\t\tprocess.stdout.write(chalk.magenta.bold(\"🧠 reasoning \"));\n\t\t\t\t\tactive = \"reasoning\";\n\t\t\t\t}\n\t\t\t\tprocess.stdout.write(chalk.magenta(part.text));\n\t\t\t\tbreak;\n\n\t\t\tcase \"text-delta\":\n\t\t\t\tif (active !== \"text\") {\n\t\t\t\t\tendActive();\n\t\t\t\t\tprocess.stdout.write(chalk.white.bold(\"💬 message \"));\n\t\t\t\t\tactive = \"text\";\n\t\t\t\t}\n\t\t\t\tprocess.stdout.write(chalk.white(part.text));\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-call\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.cyan.bold(`🔧 tool call ${part.toolName}`) +\n\t\t\t\t\t\tchalk.cyan(`(${JSON.stringify(part.input)})`),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-result\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.green.bold(`✅ tool result ${part.toolName} `) +\n\t\t\t\t\t\tchalk.green(JSON.stringify(part.output)),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool-error\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.red.bold(`❌ tool error ${part.toolName} `) +\n\t\t\t\t\t\tchalk.red(String(part.error)),\n\t\t\t\t);\n\t\t\t\tbreak;\n\n\t\t\tcase \"error\":\n\t\t\t\tendActive();\n\t\t\t\tconsole.log(chalk.red.bold(\"‼️ stream error \"), part.error);\n\t\t\t\tbreak;\n\n\t\t\tcase \"finish\": {\n\t\t\t\tendActive();\n\t\t\t\tconst contextWindowTokens = contextWindowPromise\n\t\t\t\t\t? await contextWindowPromise\n\t\t\t\t\t: null;\n\t\t\t\tconsole.log(\n\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t`\\n── done (${part.finishReason}) · ${formatContextUsage(latestStepUsage, contextWindowTokens)}${hasOpenRouterCost ? ` · cost ${formatCost(openRouterCost)}` : \"\"} ──`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport default logStream;\n"],"mappings":";AAAA;AAAA,EACC,oBAAoB;AAAA,OAGd;AA2BA,SAAS,iBACf,WAAuC,CAAC,GACnB;AACrB,QAAM,EAAE,QAAQ,WAAW,GAAG,KAAK,IAAI;AAEvC,QAAM,YACL,aAAa,OAAO,cAAc,YAAY,WAAW,YACrD,UAAsC,QACvC;AAEJ,SAAO,qBAAqB;AAAA,IAC3B,QAAQ,UAAU,QAAQ,IAAI;AAAA,IAC9B,GAAG;AAAA,IACH,WAAW;AAAA,MACV,GAAG;AAAA,MACH,OAAO;AAAA,QACN,SAAS;AAAA,QACT,GAAI,aAAa,OAAO,cAAc,WAClC,YACD,CAAC;AAAA,MACL;AAAA,IACD;AAAA,EACD,CAAC;AACF;;;ACrDA,OAAO,WAAW;AAkBlB,IAAM,+BAA+B,oBAAI,IAAoC;AAE7E,SAAS,kBAAkB,MAA+B;AACzD,MAAI,KAAK,SAAS,cAAe,QAAO;AAExC,QAAM,gBAAgB,KAAK,kBAAkB,YAAY;AAGzD,QAAM,WAAW,KAAK,MAAM;AAO5B,QAAM,OAAO,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AQ,IAAI,MAAM,IAAI,KAAK,6BAAmB,GAAG,KAAK,KAAK;AAC3D;AAAA,MAED,KAAK,UAAU;AACd,kBAAU;AACV,cAAM,sBAAsB,uBACzB,MAAM,uBACN;AACH,gBAAQ;AAAA,UACP,MAAM;AAAA,YACL;AAAA,qBAAc,KAAK,YAAY,UAAO,mBAAmB,iBAAiB,mBAAmB,CAAC,GAAG,oBAAoB,cAAW,WAAW,cAAc,CAAC,KAAK,EAAE;AAAA,UAClK;AAAA,QACD;AACA;AAAA,MACD;AAAA,IACD;AAAA,EACD;AACD;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@merkie/agentic",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Batteries-included helpers for building LLM-powered apps with the Vercel AI SDK and OpenRouter — automatic cost/usage tracking and pretty stream logging out of the box.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Merkie <archercalder@gmail.com>",
|
|
8
|
+
"homepage": "https://github.com/Merkie/agentic#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/Merkie/agentic.git"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/Merkie/agentic/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"ai",
|
|
18
|
+
"llm",
|
|
19
|
+
"agent",
|
|
20
|
+
"agents",
|
|
21
|
+
"openrouter",
|
|
22
|
+
"vercel-ai-sdk",
|
|
23
|
+
"ai-sdk",
|
|
24
|
+
"observability",
|
|
25
|
+
"cost-tracking",
|
|
26
|
+
"usage-tracking",
|
|
27
|
+
"streaming"
|
|
28
|
+
],
|
|
29
|
+
"main": "./dist/index.cjs",
|
|
30
|
+
"module": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"require": "./dist/index.cjs"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=18"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsup",
|
|
52
|
+
"dev": "tsup --watch",
|
|
53
|
+
"test": "vitest run",
|
|
54
|
+
"test:watch": "vitest",
|
|
55
|
+
"typecheck": "tsc --noEmit",
|
|
56
|
+
"prepublishOnly": "npm run build"
|
|
57
|
+
},
|
|
58
|
+
"dependencies": {
|
|
59
|
+
"chalk": "^5.6.2"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"@openrouter/ai-sdk-provider": ">=2",
|
|
63
|
+
"ai": ">=5"
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"@openrouter/ai-sdk-provider": "2.3.3",
|
|
67
|
+
"@types/node": "22.15.0",
|
|
68
|
+
"ai": "6.0.160",
|
|
69
|
+
"tsup": "^8.5.0",
|
|
70
|
+
"typescript": "5.4.5",
|
|
71
|
+
"vitest": "^3.2.4"
|
|
72
|
+
}
|
|
73
|
+
}
|