@outputai/core 0.15.1-dev.46e7530.0 → 0.15.1-dev.de5fa8c.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/dist/credentials/index.d.ts +1 -1
- package/dist/credentials/types.d.ts +4 -4
- package/dist/evals/aggregate.d.ts +2 -0
- package/dist/evals/aggregate.js +11 -0
- package/dist/evals/eval_workflow.d.ts +20 -0
- package/dist/evals/eval_workflow.js +98 -0
- package/dist/evals/index.d.ts +7 -0
- package/dist/evals/index.js +4 -0
- package/dist/evals/interpret.d.ts +3 -0
- package/dist/evals/interpret.js +40 -0
- package/dist/evals/schemas.d.ts +96 -0
- package/dist/evals/schemas.js +60 -0
- package/dist/evals/verdict.d.ts +27 -0
- package/dist/evals/verdict.js +109 -0
- package/dist/evals/verify.d.ts +42 -0
- package/dist/evals/verify.js +19 -0
- package/package.json +64 -14
- package/src/consts.d.ts +2 -0
- package/src/helpers/fetch.js +21 -9
- package/src/helpers/path.js +34 -0
- package/src/helpers/redact.js +2 -1
- package/src/http/config.js +10 -0
- package/src/http/cost.d.ts +20 -0
- package/src/http/cost.js +41 -0
- package/src/http/fetch/events.js +10 -0
- package/src/http/fetch/index.d.ts +24 -0
- package/src/http/fetch/index.js +78 -0
- package/src/http/fetch/logger.d.ts +10 -0
- package/src/http/fetch/logger.js +56 -0
- package/src/http/index.d.ts +28 -0
- package/src/http/index.js +9 -0
- package/src/http/ky/index.d.ts +25 -0
- package/src/http/ky/index.js +10 -0
- package/src/http/request_tag.js +30 -0
- package/src/interface/index.d.ts +1 -0
- package/src/llm/agent.js +147 -0
- package/src/llm/ai_provider.js +131 -0
- package/src/llm/ai_sdk_options.js +126 -0
- package/src/llm/consts.js +6 -0
- package/src/llm/deprecated_provider_aliases.js +8 -0
- package/src/llm/generate.js +98 -0
- package/src/llm/index.d.ts +697 -0
- package/src/llm/index.js +6 -0
- package/src/llm/judge.js +48 -0
- package/src/llm/prompt/content.js +70 -0
- package/src/llm/prompt/interpolations.js +58 -0
- package/src/llm/prompt/loader.js +67 -0
- package/src/llm/prompt/markup/attributes.js +52 -0
- package/src/llm/prompt/markup/nodes.js +71 -0
- package/src/llm/prompt/markup/tokenizer.js +3 -0
- package/src/llm/prompt/markup/tokens.js +26 -0
- package/src/llm/prompt/validations.js +129 -0
- package/src/llm/utils/cost.js +267 -0
- package/src/llm/utils/error_handler.js +53 -0
- package/src/llm/utils/file.js +42 -0
- package/src/llm/utils/google_vertex_auth.js +31 -0
- package/src/llm/utils/image.js +37 -0
- package/src/llm/utils/legacy_cost_attribute.js +75 -0
- package/src/llm/utils/metering.js +139 -0
- package/src/llm/utils/models.js +15 -0
- package/src/llm/utils/models_pricing.js +96 -0
- package/src/llm/utils/models_pricing_snapshot.json +4711 -0
- package/src/llm/utils/skills.js +74 -0
- package/src/llm/utils/sources.js +73 -0
- package/src/llm/utils/stream.js +75 -0
- package/src/llm/utils/tools.js +62 -0
- package/src/llm/utils/usage.js +155 -0
- package/src/llm/utils/usage_tools.js +23 -0
- package/src/llm/utils/web_search.js +155 -0
- package/src/llm/utils/wrap.js +279 -0
- package/src/llm/validations.js +234 -0
- package/src/tracing/trace_attribute.d.ts +0 -17
- package/src/tracing/trace_attribute.js +1 -29
- package/src/worker/bundler_options.js +1 -9
- package/src/worker/configs.js +23 -4
- package/src/worker/index.js +16 -47
- package/src/worker/interceptors/activity.js +0 -1
- package/src/worker/interceptors/workflow.js +0 -1
- package/src/worker/loader/workflows.js +16 -2
- package/src/worker/telemetry.js +122 -2
- package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
- package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
- package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
- package/src/worker/worker_options.js +43 -0
- package/src/sdk/README.md +0 -47
- package/src/sdk/helpers/component_metadata.d.ts +0 -17
- package/src/sdk/helpers/component_metadata.js +0 -6
- package/src/sdk/helpers/index.d.ts +0 -12
- package/src/sdk/helpers/index.js +0 -3
- package/src/sdk/helpers/objects.d.ts +0 -56
- package/src/sdk/helpers/objects.js +0 -8
- package/src/sdk/helpers/path.d.ts +0 -11
- package/src/sdk/helpers/path.js +0 -32
- package/src/sdk/runtime/context.d.ts +0 -30
- package/src/sdk/runtime/context.js +0 -15
- package/src/sdk/runtime/events.d.ts +0 -13
- package/src/sdk/runtime/events.js +0 -5
- package/src/sdk/runtime/index.d.ts +0 -12
- package/src/sdk/runtime/index.js +0 -3
- package/src/sdk/runtime/tracing.d.ts +0 -48
- package/src/sdk/runtime/tracing.js +0 -11
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs';
|
|
2
|
+
import { resolve, basename } from 'node:path';
|
|
3
|
+
import matter from 'gray-matter';
|
|
4
|
+
import { ValidationError } from '#errors';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef Skill
|
|
8
|
+
* @property {string} name
|
|
9
|
+
* @property {string} description
|
|
10
|
+
* @property {string} instructions
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Recursively load skill paths. Explicit files may use any extension; directories load `.md` files only.
|
|
15
|
+
* Frontmatter may provide `name` and `description`; body becomes the instructions.
|
|
16
|
+
*
|
|
17
|
+
* @param {string[]} paths
|
|
18
|
+
* @param {boolean} markdownFilesOnly
|
|
19
|
+
* @returns {Skills[]}
|
|
20
|
+
*/
|
|
21
|
+
const recursiveLoadSkillPaths = ( paths, markdownFilesOnly ) => {
|
|
22
|
+
const loaded = [];
|
|
23
|
+
for ( const path of paths ) {
|
|
24
|
+
if ( !existsSync( path ) ) {
|
|
25
|
+
throw new ValidationError( `Skill path "${path}" not found` );
|
|
26
|
+
}
|
|
27
|
+
const stats = lstatSync( path );
|
|
28
|
+
if ( stats.isSymbolicLink() ) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if ( stats.isDirectory() ) {
|
|
32
|
+
loaded.push( ...recursiveLoadSkillPaths(
|
|
33
|
+
readdirSync( path ).sort().map( f => resolve( path, f ) ),
|
|
34
|
+
true
|
|
35
|
+
) );
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if ( markdownFilesOnly && !path.endsWith( '.md' ) ) {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const raw = readFileSync( path, 'utf-8' );
|
|
43
|
+
const { data, content } = matter( raw );
|
|
44
|
+
loaded.push( {
|
|
45
|
+
name: data.name ?? basename( path, '.md' ),
|
|
46
|
+
description: data.description ?? basename( path, '.md' ),
|
|
47
|
+
instructions: content.trim()
|
|
48
|
+
} );
|
|
49
|
+
}
|
|
50
|
+
return loaded;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Recursively load skill files without following symbolic links.
|
|
55
|
+
*
|
|
56
|
+
* @param {string[]} paths
|
|
57
|
+
* @returns {Skills[]}
|
|
58
|
+
*/
|
|
59
|
+
export const recursiveLoadSkillFile = paths => recursiveLoadSkillPaths( paths, false );
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Resolve all skills available to a prompt.
|
|
63
|
+
*
|
|
64
|
+
* @param {object} prompt - Loaded prompt object
|
|
65
|
+
* @returns {{ name: string, description: string, instructions: string }[]}
|
|
66
|
+
*/
|
|
67
|
+
export const loadSkills = prompt => {
|
|
68
|
+
const baseDir = prompt.fileDir;
|
|
69
|
+
|
|
70
|
+
// skills referenced in the prompt config
|
|
71
|
+
const promptSkillPaths = prompt.config.skills.map( f => resolve( baseDir, f ) );
|
|
72
|
+
|
|
73
|
+
return recursiveLoadSkillFile( promptSkillPaths );
|
|
74
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { Logger } from '#runtime_logger';
|
|
3
|
+
|
|
4
|
+
/** Builds the final source shape */
|
|
5
|
+
const buildSource = ( { url, title } ) => {
|
|
6
|
+
const trimmedUrl = url.trim();
|
|
7
|
+
return {
|
|
8
|
+
type: 'source',
|
|
9
|
+
sourceType: 'url',
|
|
10
|
+
id: createHash( 'sha256' ).update( trimmedUrl ).digest( 'hex' ).slice( 0, 16 ),
|
|
11
|
+
url: trimmedUrl,
|
|
12
|
+
title: title ?? ''
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Return value it is array, otherwise return [] */
|
|
17
|
+
const asArray = v => Array.isArray( v ) ? v : [];
|
|
18
|
+
|
|
19
|
+
const isNonBlankUrl = url => typeof url === 'string' && url.trim().length > 0;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Extracts source from search tool results embedded in AI SDK step data.
|
|
23
|
+
*
|
|
24
|
+
* Detects any tool result containing a `results[]` array whose items have a `url` string field.
|
|
25
|
+
* This covers perplexitySearch, tavilySearch, exaSearch, and any future tool with the same shape.
|
|
26
|
+
* Deduplicate key is "url"
|
|
27
|
+
*
|
|
28
|
+
* @param {Array} steps - AI SDK response steps (response.steps)
|
|
29
|
+
* @returns {Array<{ key: string, source: object }>}
|
|
30
|
+
*/
|
|
31
|
+
const extractSourcesFromSteps = steps =>
|
|
32
|
+
asArray( steps )
|
|
33
|
+
.flatMap( step => asArray( step?.toolResults ) )
|
|
34
|
+
.flatMap( toolResult => asArray( toolResult?.output?.results ) )
|
|
35
|
+
.filter( item => isNonBlankUrl( item?.url ) )
|
|
36
|
+
.map( item => {
|
|
37
|
+
const source = buildSource( item );
|
|
38
|
+
return { key: source.url, source };
|
|
39
|
+
} );
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Extract only the valid sources from the response (has url or id).
|
|
43
|
+
* Deduplicate key is `url` when set, otherwise `id` (document sources have `id` and no `url`).
|
|
44
|
+
*
|
|
45
|
+
* @param {Array} sources
|
|
46
|
+
* @returns {Array<{ key: string, source: object }>}
|
|
47
|
+
*/
|
|
48
|
+
const extractValidSourcesFromResponse = sources =>
|
|
49
|
+
asArray( sources )
|
|
50
|
+
.filter( item => item !== null && typeof item === 'object' && ( isNonBlankUrl( item.url ) || typeof item.id === 'string' ) )
|
|
51
|
+
.map( item => ( { key: isNonBlankUrl( item.url ) ? item.url.trim() : item.id, source: item } ) );
|
|
52
|
+
|
|
53
|
+
/** Deduplicate wrapped sources by their key */
|
|
54
|
+
const deduplicateSources = sources => new Map( sources.map( item => [ item.key, item.source ] ) ).values().toArray();
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Extract sources from tools usage and final response, deduplicate, and return.
|
|
58
|
+
* Response sources are preferred over tools when the key matches.
|
|
59
|
+
*
|
|
60
|
+
* @param {object} response AI SDK response
|
|
61
|
+
* @returns {object[]} Merged sources
|
|
62
|
+
*/
|
|
63
|
+
export const extractSources = response => {
|
|
64
|
+
try {
|
|
65
|
+
const { steps, sources: sourcesFromResponse } = response ?? {};
|
|
66
|
+
const sourcesFromTools = extractSourcesFromSteps( asArray( steps ) );
|
|
67
|
+
const validSourcesFromResponse = extractValidSourcesFromResponse( sourcesFromResponse );
|
|
68
|
+
return deduplicateSources( sourcesFromTools.concat( validSourcesFromResponse ) );
|
|
69
|
+
} catch ( error ) {
|
|
70
|
+
Logger.error( 'Sources extraction failed', { namespace: 'LLM', error: error?.message || String( error ) } );
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
|
|
3
|
+
/** How long a failed stream may go quiet before the drain gives up on its remaining parts */
|
|
4
|
+
const FAILURE_DRAIN_TIMEOUT_MS = 250;
|
|
5
|
+
|
|
6
|
+
const TIMED_OUT = Symbol( 'drain-timed-out' );
|
|
7
|
+
|
|
8
|
+
/** Extracts the error an abort or error part should surface, or null for every other part */
|
|
9
|
+
const extractError = ( part, abortSignal ) => {
|
|
10
|
+
if ( part?.type === 'abort' ) {
|
|
11
|
+
const reason = abortSignal?.reason;
|
|
12
|
+
return reason instanceof Error ?
|
|
13
|
+
reason :
|
|
14
|
+
new Error( part.reason ?? 'Streaming aborted.', { cause: reason } );
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if ( part?.type === 'error' ) {
|
|
18
|
+
return part.error instanceof Error ?
|
|
19
|
+
part.error :
|
|
20
|
+
new Error( part.error ? String( part.error ) : 'Streaming failed.', { cause: part.error } );
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if ( abortSignal?.aborted ) {
|
|
24
|
+
return abortSignal.reason instanceof Error ?
|
|
25
|
+
abortSignal.reason :
|
|
26
|
+
new Error( 'Streaming aborted.', { cause: abortSignal.reason } );
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Reads the next part, resolving with `TIMED_OUT` when the stream goes quiet for longer than `timeoutMs` */
|
|
33
|
+
const nextWithin = async ( iterator, timeoutMs ) =>
|
|
34
|
+
Promise.race( [ iterator.next(), delay( timeoutMs, TIMED_OUT, { ref: false } ) ] );
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Consumes a streaming result until it completes, then throws the first abort or error part it saw.
|
|
38
|
+
* Callers must not throw from the AI SDK `onError` callback; that errors the stream before these parts are delivered.
|
|
39
|
+
*
|
|
40
|
+
* The draining continues past a failure on purpose: the AI SDK fires its lifecycle callbacks as parts flow through the
|
|
41
|
+
* stream, so `onStepEnd` and `onEnd` - and with them the usage of everything already spent - only arrive if something
|
|
42
|
+
* keeps reading. A stalled provider can leave the stream open forever, so once a failure is captured every read waits
|
|
43
|
+
* at most `FAILURE_DRAIN_TIMEOUT_MS` for the next part, and the drain gives up and throws anyway when none arrives.
|
|
44
|
+
* A healthy stream ends immediately after a failure, so the timeout is not part of the normal path; a successful
|
|
45
|
+
* stream is never timed out.
|
|
46
|
+
*
|
|
47
|
+
* @param {object} stream - AI SDK stream result with `stream`
|
|
48
|
+
* @param {AbortSignal} [abortSignal] - Used to recover the original abort reason
|
|
49
|
+
*/
|
|
50
|
+
export const drainStream = async ( stream, abortSignal ) => {
|
|
51
|
+
const iterator = stream.stream[Symbol.asyncIterator]();
|
|
52
|
+
const state = { error: null };
|
|
53
|
+
|
|
54
|
+
while ( true ) {
|
|
55
|
+
const hasDeadline = state.error || abortSignal?.aborted;
|
|
56
|
+
const result = await ( hasDeadline ? nextWithin( iterator, FAILURE_DRAIN_TIMEOUT_MS ) : iterator.next() );
|
|
57
|
+
|
|
58
|
+
if ( result.done ) {
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if ( result?.value || abortSignal?.aborted ) {
|
|
63
|
+
state.error ??= extractError( result.value, abortSignal );
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if ( result === TIMED_OUT ) {
|
|
67
|
+
iterator.return?.()?.catch( () => {} );
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if ( state.error ) {
|
|
73
|
+
throw state.error;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { tool as createTool } from 'ai';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { ValidationError } from '#errors';
|
|
4
|
+
import { getProvider } from '../ai_provider.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Build the `load_skill` AI SDK tool that the LLM calls to retrieve full skill instructions.
|
|
8
|
+
*
|
|
9
|
+
* @param {Skill[]} skills
|
|
10
|
+
* @returns {import('ai').Tool}
|
|
11
|
+
*/
|
|
12
|
+
export const buildLoadSkillTool = skills => createTool( {
|
|
13
|
+
description: 'Get detailed instructions for a named skill',
|
|
14
|
+
inputSchema: z.object( { name: z.string().describe( 'Name of the skill to load' ) } ),
|
|
15
|
+
execute: ( { name } ) => {
|
|
16
|
+
const sk = skills.find( s => s.name === name );
|
|
17
|
+
if ( !sk ) {
|
|
18
|
+
return `Skill "${name}" not found. Available: ${skills.map( s => s.name ).join( ', ' )}`;
|
|
19
|
+
}
|
|
20
|
+
return sk.instructions;
|
|
21
|
+
}
|
|
22
|
+
} );
|
|
23
|
+
|
|
24
|
+
const buildProviderError = ( prompt, suffix ) => `Provider "${prompt.config.provider}" used by prompt "${prompt.name}" does not support ${suffix}.`;
|
|
25
|
+
|
|
26
|
+
/** Load tools from a prompt provider. */
|
|
27
|
+
export const loadPromptTools = prompt => {
|
|
28
|
+
const promptToolNames = Object.keys( prompt.config.tools ?? {} );
|
|
29
|
+
if ( promptToolNames.length === 0 ) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const { tools } = getProvider( prompt.config.provider );
|
|
34
|
+
if ( !tools ) {
|
|
35
|
+
throw new ValidationError( buildProviderError( prompt, 'provider-specific tools' ) );
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const missingTools = promptToolNames.filter( t => !Object.hasOwn( tools, t ) || typeof tools[t] !== 'function' );
|
|
39
|
+
if ( missingTools.length > 0 ) {
|
|
40
|
+
throw new ValidationError( buildProviderError( prompt, `these tools: ${missingTools.join( ', ' )}` ) );
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const loadedTools = {};
|
|
44
|
+
for ( const name of promptToolNames ) {
|
|
45
|
+
loadedTools[name] = tools[name]( prompt.config.tools[name] );
|
|
46
|
+
}
|
|
47
|
+
return loadedTools;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Maps configured tool names to their canonical provider tool ids.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} [tools] - Final AI SDK tool map
|
|
54
|
+
* @returns {Record<string, string> | null} Provider tool ids keyed by configured name
|
|
55
|
+
*/
|
|
56
|
+
export const extractProviderToolIds = tools => {
|
|
57
|
+
const entries = Object.entries( tools ?? {} )
|
|
58
|
+
.filter( ( [ , tool ] ) => tool?.type === 'provider' && typeof tool.id === 'string' )
|
|
59
|
+
.map( ( [ name, tool ] ) => [ name, tool.id ] );
|
|
60
|
+
|
|
61
|
+
return entries.length > 0 ? Object.fromEntries( entries ) : null;
|
|
62
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import Decimal from 'decimal.js';
|
|
2
|
+
import { BaseAttribute } from '#trace_attribute';
|
|
3
|
+
import { extractUsageFromSteps } from './usage_tools.js';
|
|
4
|
+
import { parseWebSearchUsage } from './web_search.js';
|
|
5
|
+
|
|
6
|
+
const isValidTokenCount = v => Number.isSafeInteger( v ) && v >= 0;
|
|
7
|
+
|
|
8
|
+
const safeSum = ( ...values ) => values.filter( isValidTokenCount ).reduce( ( t, v ) => t + v, 0 );
|
|
9
|
+
|
|
10
|
+
export class LLMGenerationUsageItem {
|
|
11
|
+
static Group = { INPUT: 'input', OUTPUT: 'output', TOOLS: 'tools' };
|
|
12
|
+
|
|
13
|
+
group;
|
|
14
|
+
label;
|
|
15
|
+
amount;
|
|
16
|
+
|
|
17
|
+
constructor( group, label, amount ) {
|
|
18
|
+
this.group = group;
|
|
19
|
+
this.label = label;
|
|
20
|
+
this.amount = amount;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class LLMGenerationUsage extends BaseAttribute {
|
|
25
|
+
static TYPE = 'llm:generation:usage';
|
|
26
|
+
|
|
27
|
+
static Status = Object.freeze( {
|
|
28
|
+
COMPLETE: 'complete',
|
|
29
|
+
INCOMPLETE: 'incomplete'
|
|
30
|
+
} );
|
|
31
|
+
|
|
32
|
+
providerId;
|
|
33
|
+
modelId;
|
|
34
|
+
status = LLMGenerationUsage.Status.INCOMPLETE;
|
|
35
|
+
input = null;
|
|
36
|
+
output = null;
|
|
37
|
+
total = null;
|
|
38
|
+
items = [];
|
|
39
|
+
|
|
40
|
+
constructor( modelId, providerId, items ) {
|
|
41
|
+
super( LLMGenerationUsage.TYPE );
|
|
42
|
+
this.providerId = providerId;
|
|
43
|
+
this.modelId = modelId;
|
|
44
|
+
this.items = items;
|
|
45
|
+
const inputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.INPUT );
|
|
46
|
+
if ( inputItems.length > 0 ) {
|
|
47
|
+
this.input = inputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
48
|
+
}
|
|
49
|
+
const outputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.OUTPUT );
|
|
50
|
+
if ( outputItems.length > 0 ) {
|
|
51
|
+
this.output = outputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if ( isValidTokenCount( this.input ) || isValidTokenCount( this.output ) ) {
|
|
55
|
+
this.total = ( this.input ?? 0 ) + ( this.output ?? 0 );
|
|
56
|
+
}
|
|
57
|
+
this.status = LLMGenerationUsage.Status[isValidTokenCount( this.input ) && isValidTokenCount( this.output ) ? 'COMPLETE' : 'INCOMPLETE'];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Returns usage from response or reconstruct it from steps.
|
|
63
|
+
*
|
|
64
|
+
* The token check is load-bearing: aborted and truncated calls still report an aggregate, but with
|
|
65
|
+
* every token count undefined, and the steps are then the only record of what was already spent.
|
|
66
|
+
*/
|
|
67
|
+
const resolveUsage = ( { usage, steps } ) => {
|
|
68
|
+
if ( usage && ( isValidTokenCount( usage.inputTokens ) || isValidTokenCount( usage.outputTokens ) ) ) {
|
|
69
|
+
return usage;
|
|
70
|
+
}
|
|
71
|
+
return Array.isArray( steps ) && steps.length > 0 ? extractUsageFromSteps( steps ) : null;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Converts raw AI SDK usage to LLMGenerationUsage data.
|
|
76
|
+
*
|
|
77
|
+
* Reads `response.usage`, falling back to the sum of `response.steps` usage when the aggregate is
|
|
78
|
+
* missing tokens (truncated or failed streams). Grounding is aggregated from `response.steps`, so a
|
|
79
|
+
* partial `{ steps }` response is accepted when only the steps are known.
|
|
80
|
+
*
|
|
81
|
+
* @param {object} args
|
|
82
|
+
* @param {object} args.prompt - Output prompt with model configuration
|
|
83
|
+
* @param {object} [args.usage] - AI SDK response usage
|
|
84
|
+
* @param {object} [args.steps] - AI SDK response steps
|
|
85
|
+
* @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
|
|
86
|
+
*
|
|
87
|
+
* @returns {LLMGenerationUsage | null} LLM generation usage with input, output, total and detailed breakdown
|
|
88
|
+
*/
|
|
89
|
+
export const parseLLMUsage = ( { prompt, usage: usageArg = null, steps = [], toolIdsByName = null } ) => {
|
|
90
|
+
const usage = resolveUsage( { usage: usageArg, steps } );
|
|
91
|
+
if ( !usage ) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
const { provider: providerId, model: modelId } = prompt.config;
|
|
95
|
+
const { inputTokens, inputTokenDetails, outputTokens, outputTokenDetails } = usage;
|
|
96
|
+
const { noCacheTokens, cacheReadTokens, cacheWriteTokens } = inputTokenDetails ?? {};
|
|
97
|
+
const { textTokens, reasoningTokens } = outputTokenDetails ?? {};
|
|
98
|
+
|
|
99
|
+
const items = [];
|
|
100
|
+
|
|
101
|
+
if ( isValidTokenCount( inputTokens ) ) {
|
|
102
|
+
// the sum of the components must be equal to the tokens
|
|
103
|
+
const useDetails = inputTokens > 0 && safeSum( noCacheTokens, cacheReadTokens, cacheWriteTokens ) === inputTokens;
|
|
104
|
+
const group = LLMGenerationUsageItem.Group.INPUT;
|
|
105
|
+
|
|
106
|
+
if ( useDetails ) {
|
|
107
|
+
if ( isValidTokenCount( noCacheTokens ) ) {
|
|
108
|
+
items.push( new LLMGenerationUsageItem( group, 'no_cache', noCacheTokens ) );
|
|
109
|
+
}
|
|
110
|
+
if ( isValidTokenCount( cacheReadTokens ) ) {
|
|
111
|
+
items.push( new LLMGenerationUsageItem( group, 'cache_read', cacheReadTokens ) );
|
|
112
|
+
}
|
|
113
|
+
if ( isValidTokenCount( cacheWriteTokens ) ) {
|
|
114
|
+
items.push( new LLMGenerationUsageItem( group, 'cache_write', cacheWriteTokens ) );
|
|
115
|
+
}
|
|
116
|
+
} else {
|
|
117
|
+
items.push( new LLMGenerationUsageItem( group, null, inputTokens ) );
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if ( isValidTokenCount( outputTokens ) ) {
|
|
122
|
+
// the sum of the components must be equal to the tokens
|
|
123
|
+
const useDetails = outputTokens > 0 && safeSum( textTokens, reasoningTokens ) === outputTokens;
|
|
124
|
+
const group = LLMGenerationUsageItem.Group.OUTPUT;
|
|
125
|
+
|
|
126
|
+
if ( useDetails ) {
|
|
127
|
+
if ( isValidTokenCount( textTokens ) ) {
|
|
128
|
+
items.push( new LLMGenerationUsageItem( group, 'text', textTokens ) );
|
|
129
|
+
}
|
|
130
|
+
if ( isValidTokenCount( reasoningTokens ) ) {
|
|
131
|
+
items.push( new LLMGenerationUsageItem( group, 'reasoning', reasoningTokens ) );
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
items.push( new LLMGenerationUsageItem( group, null, outputTokens ) );
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Provider web search is billed per step, so aggregate across every step rather than only the final one.
|
|
139
|
+
if ( Array.isArray( steps ) ) {
|
|
140
|
+
const webSearch = steps.flatMap( step => parseWebSearchUsage( providerId, modelId, step, toolIdsByName ) );
|
|
141
|
+
if ( webSearch.length > 0 ) {
|
|
142
|
+
const totals = Map.groupBy( webSearch, item => item.label );
|
|
143
|
+
for ( const [ label, values ] of totals ) {
|
|
144
|
+
const amount = values.reduce( ( sum, item ) => sum + item.amount, 0 );
|
|
145
|
+
items.push( new LLMGenerationUsageItem( LLMGenerationUsageItem.Group.TOOLS, label, amount ) );
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if ( items.length === 0 ) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return new LLMGenerationUsage( modelId, providerId, items );
|
|
155
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const sum = ( a, b ) => {
|
|
2
|
+
if ( Number.isFinite( a ) ) {
|
|
3
|
+
return a + ( Number.isFinite( b ) ? b : 0 );
|
|
4
|
+
} else {
|
|
5
|
+
return Number.isFinite( b ) ? b : undefined;
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const isPlainObject = value => value !== null && typeof value === 'object';
|
|
10
|
+
|
|
11
|
+
/** Deep numeric merge of two AI SDK usage objects; `raw` is provider-shaped and never summed */
|
|
12
|
+
const mergeUsage = ( total, usage ) => Object.entries( usage )
|
|
13
|
+
.filter( ( [ key ] ) => key !== 'raw' )
|
|
14
|
+
.reduce( ( merged, [ key, value ] ) => ( {
|
|
15
|
+
...merged,
|
|
16
|
+
[key]: isPlainObject( value ) ? mergeUsage( merged[key] ?? {}, value ) : sum( merged[key], value )
|
|
17
|
+
} ), total );
|
|
18
|
+
|
|
19
|
+
/** Sums per-step AI SDK usage */
|
|
20
|
+
export const extractUsageFromSteps = steps => steps
|
|
21
|
+
.map( step => step?.usage )
|
|
22
|
+
.filter( Boolean )
|
|
23
|
+
.reduce( ( total, usage ) => mergeUsage( total, usage ), {} );
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Provider web search rates, expressed per million billing units to match `ppm` semantics.
|
|
3
|
+
*/
|
|
4
|
+
const Price = {
|
|
5
|
+
// Verified: 2026-10-28 / Source: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool
|
|
6
|
+
ANTHROPIC_WEB_SEARCH: 10_000,
|
|
7
|
+
// Verified: 2026-10-28 / Source: https://openai.com/api/pricing/
|
|
8
|
+
OPENAI_WEB_SEARCH: 10_000,
|
|
9
|
+
// Verified: 2026-10-28 / Source: https://openai.com/api/pricing/
|
|
10
|
+
OPENAI_WEB_SEARCH_PREVIEW: 25_000,
|
|
11
|
+
// Verified: 2026-10-28 / Source: https://openai.com/api/pricing/
|
|
12
|
+
OPENAI_WEB_SEARCH_PREVIEW_REASONING: 10_000,
|
|
13
|
+
// Verified: 2026-10-28 / Source: https://cloud.google.com/vertex-ai/generative-ai/pricing
|
|
14
|
+
GOOGLE_GROUNDING_QUERY: 14_000,
|
|
15
|
+
// Verified: 2026-10-28 / Source: https://cloud.google.com/vertex-ai/generative-ai/pricing
|
|
16
|
+
GOOGLE_GROUNDING_PROMPT: 35_000
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const Label = {
|
|
20
|
+
WEB_SEARCH: 'web_search',
|
|
21
|
+
WEB_SEARCH_PREVIEW: 'web_search_preview',
|
|
22
|
+
WEB_SEARCH_UNKNOWN: 'web_search_unknown',
|
|
23
|
+
GROUNDING_GENERIC: 'grounding',
|
|
24
|
+
GROUNDING_QUERY: 'grounding_query',
|
|
25
|
+
GROUNDING_PROMPT: 'grounding_prompt'
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const Tool = {
|
|
29
|
+
OPENAI_WEB_SEARCH: 'openai.web_search',
|
|
30
|
+
OPENAI_WEB_SEARCH_PREVIEW: 'openai.web_search_preview'
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// Google reports generated queries in grounding metadata. Gemini 3/4 bill per query; Gemini 2 bills per grounded prompt.
|
|
34
|
+
const parseGoogleGroundingUsage = ( modelId, providerMetadata ) => {
|
|
35
|
+
const meta = providerMetadata?.vertex ?? providerMetadata?.google;
|
|
36
|
+
const queries = meta?.groundingMetadata?.webSearchQueries;
|
|
37
|
+
if ( !Array.isArray( queries ) || queries.length === 0 ) {
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if ( /^gemini-[34]/.test( modelId ) ) {
|
|
42
|
+
return [ { label: Label.GROUNDING_QUERY, amount: queries.length } ];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if ( /^gemini-2/.test( modelId ) ) {
|
|
46
|
+
return [ { label: Label.GROUNDING_PROMPT, amount: 1 } ];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return [ { label: Label.GROUNDING_GENERIC, amount: queries.length } ];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Anthropic reports the billable request count directly in server-tool usage metadata.
|
|
53
|
+
const parseAnthropicWebSearchUsage = step => {
|
|
54
|
+
const amount = step?.providerMetadata?.anthropic?.usage?.server_tool_use?.web_search_requests;
|
|
55
|
+
return Number.isSafeInteger( amount ) && amount > 0 ? [ { label: Label.WEB_SEARCH, amount } ] : [];
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/*
|
|
59
|
+
* OpenAI bills only `search` result actions, not page opens or in-page finds. Tool names are user
|
|
60
|
+
* aliases, so canonical IDs come from `toolIdsByName`. When both variants are configured, AI SDK
|
|
61
|
+
* maps every result to the first variant and the billed variant cannot be determined.
|
|
62
|
+
*/
|
|
63
|
+
const parseOpenAiWebSearchUsage = ( step, toolIdsByName ) => {
|
|
64
|
+
if ( !Array.isArray( step?.content ) ) {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const isSearch = p => p?.type === 'tool-result' && p.output?.action?.type === 'search';
|
|
69
|
+
|
|
70
|
+
const searchTools = [ Tool.OPENAI_WEB_SEARCH, Tool.OPENAI_WEB_SEARCH_PREVIEW ];
|
|
71
|
+
|
|
72
|
+
const mixedToolsAvailable = new Set( Object.values( toolIdsByName ).filter( id => searchTools.includes( id ) ) ).size > 1;
|
|
73
|
+
|
|
74
|
+
const webSearches = step.content.filter( p => isSearch( p ) && toolIdsByName[p.toolName] === Tool.OPENAI_WEB_SEARCH ).length;
|
|
75
|
+
|
|
76
|
+
const webSearchPreviews = step.content.filter( p => isSearch( p ) && toolIdsByName[p.toolName] === Tool.OPENAI_WEB_SEARCH_PREVIEW ).length;
|
|
77
|
+
|
|
78
|
+
// Mixed configurations prove a search ran, but not which available variant OpenAI billed.
|
|
79
|
+
if ( mixedToolsAvailable && webSearches + webSearchPreviews > 0 ) {
|
|
80
|
+
return [ { label: Label.WEB_SEARCH_UNKNOWN, amount: webSearches + webSearchPreviews } ];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if ( webSearches > 0 ) {
|
|
84
|
+
return [ { label: Label.WEB_SEARCH, amount: webSearches } ];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if ( webSearchPreviews > 0 ) {
|
|
88
|
+
return [ { label: Label.WEB_SEARCH_PREVIEW, amount: webSearchPreviews } ];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return [];
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Extracts provider web search requests from one AI SDK step.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} providerId - Provider that produced the response
|
|
98
|
+
* @param {string} modelId - Model that produced the response
|
|
99
|
+
* @param {object} step - AI SDK step
|
|
100
|
+
* @param {Record<string, string>} [toolIdsByName] - Provider tool ids keyed by configured name
|
|
101
|
+
* @returns {Array<{ label: string, amount: number }>} Search usage grouped by tool type
|
|
102
|
+
*/
|
|
103
|
+
export const parseWebSearchUsage = ( providerId, modelId, step, toolIdsByName ) => {
|
|
104
|
+
if ( providerId === 'google-vertex' ) {
|
|
105
|
+
return parseGoogleGroundingUsage( modelId, step?.providerMetadata );
|
|
106
|
+
}
|
|
107
|
+
if ( providerId === 'anthropic' ) {
|
|
108
|
+
return parseAnthropicWebSearchUsage( step );
|
|
109
|
+
}
|
|
110
|
+
if ( providerId === 'openai' && toolIdsByName ) {
|
|
111
|
+
return parseOpenAiWebSearchUsage( step, toolIdsByName );
|
|
112
|
+
}
|
|
113
|
+
return [];
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Resolves a provider web search rate.
|
|
118
|
+
*
|
|
119
|
+
* OpenAI preview search pricing depends on whether the selected model is a reasoning model.
|
|
120
|
+
*
|
|
121
|
+
* @param {string} providerId
|
|
122
|
+
* @param {string} label
|
|
123
|
+
* @param {boolean} isReasoning - Whether the used model had reasoning support
|
|
124
|
+
* @returns {number | null} Price per million requests, queries, or prompts
|
|
125
|
+
*/
|
|
126
|
+
export const resolveWebSearchPpm = ( providerId, label, isReasoning ) => {
|
|
127
|
+
if ( providerId === 'google-vertex' ) {
|
|
128
|
+
if ( label === Label.GROUNDING_QUERY ) {
|
|
129
|
+
return Price.GOOGLE_GROUNDING_QUERY;
|
|
130
|
+
}
|
|
131
|
+
if ( label === Label.GROUNDING_PROMPT ) {
|
|
132
|
+
return Price.GOOGLE_GROUNDING_PROMPT;
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if ( providerId === 'openai' ) {
|
|
138
|
+
if ( label === Label.WEB_SEARCH ) {
|
|
139
|
+
return Price.OPENAI_WEB_SEARCH;
|
|
140
|
+
}
|
|
141
|
+
if ( label === Label.WEB_SEARCH_PREVIEW && isReasoning === false ) {
|
|
142
|
+
return Price.OPENAI_WEB_SEARCH_PREVIEW;
|
|
143
|
+
}
|
|
144
|
+
if ( label === Label.WEB_SEARCH_PREVIEW && isReasoning === true ) {
|
|
145
|
+
return Price.OPENAI_WEB_SEARCH_PREVIEW_REASONING;
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if ( providerId === 'anthropic' && label === Label.WEB_SEARCH ) {
|
|
151
|
+
return Price.ANTHROPIC_WEB_SEARCH;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return null;
|
|
155
|
+
};
|