@outputai/llm 0.11.0 → 0.11.1-next.2223fa5.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.
Files changed (69) hide show
  1. package/package.json +2 -2
  2. package/src/agent.js +105 -83
  3. package/src/agent.spec.js +312 -225
  4. package/src/ai_provider.js +2 -2
  5. package/src/ai_sdk_options.js +93 -39
  6. package/src/ai_sdk_options.spec.js +314 -154
  7. package/src/consts.js +6 -0
  8. package/src/generate.js +81 -0
  9. package/src/generate.spec.js +466 -0
  10. package/src/index.d.ts +222 -242
  11. package/src/index.js +3 -4
  12. package/src/prompt/content.js +70 -0
  13. package/src/prompt/content.spec.js +208 -0
  14. package/src/prompt/{escape.js → interpolations.js} +11 -18
  15. package/src/prompt/interpolations.spec.js +109 -0
  16. package/src/prompt/loader.full.spec.js +293 -0
  17. package/src/prompt/loader.js +45 -39
  18. package/src/prompt/loader.spec.js +186 -289
  19. package/src/prompt/markup/attributes.js +52 -0
  20. package/src/prompt/markup/attributes.spec.js +132 -0
  21. package/src/prompt/markup/nodes.js +71 -0
  22. package/src/prompt/markup/nodes.spec.js +333 -0
  23. package/src/prompt/markup/tokenizer.js +3 -0
  24. package/src/prompt/markup/tokenizer.spec.js +149 -0
  25. package/src/prompt/markup/tokens.js +26 -0
  26. package/src/prompt/markup/tokens.spec.js +250 -0
  27. package/src/prompt/validations.js +98 -67
  28. package/src/prompt/validations.spec.js +204 -47
  29. package/src/{prompt/load_content.js → utils/file.js} +12 -15
  30. package/src/utils/file.spec.js +89 -0
  31. package/src/utils/models.js +15 -0
  32. package/src/utils/models.spec.js +119 -0
  33. package/src/utils/skills.js +74 -0
  34. package/src/utils/skills.spec.js +168 -0
  35. package/src/utils/sources.js +48 -0
  36. package/src/utils/sources.spec.js +122 -0
  37. package/src/utils/stream.js +22 -0
  38. package/src/utils/stream.spec.js +55 -0
  39. package/src/utils/tools.js +47 -0
  40. package/src/utils/tools.spec.js +167 -0
  41. package/src/utils/wrap.js +148 -0
  42. package/src/utils/wrap.spec.js +359 -0
  43. package/src/validations.js +149 -27
  44. package/src/validations.spec.js +451 -53
  45. package/src/ai_model.js +0 -60
  46. package/src/ai_model.spec.js +0 -259
  47. package/src/ai_sdk.js +0 -92
  48. package/src/ai_sdk.spec.js +0 -564
  49. package/src/prompt/block_options.js +0 -58
  50. package/src/prompt/block_options.spec.js +0 -71
  51. package/src/prompt/blocks.js +0 -47
  52. package/src/prompt/blocks.spec.js +0 -63
  53. package/src/prompt/escape.spec.js +0 -159
  54. package/src/prompt/load_content.spec.js +0 -83
  55. package/src/prompt/loader_validation.spec.js +0 -128
  56. package/src/prompt/parser.js +0 -16
  57. package/src/prompt/parser.spec.js +0 -186
  58. package/src/prompt/prepare_text.js +0 -27
  59. package/src/prompt/prepare_text.spec.js +0 -141
  60. package/src/prompt/skill.js +0 -128
  61. package/src/prompt/skill.spec.js +0 -172
  62. package/src/utils/message.js +0 -3
  63. package/src/utils/message.spec.js +0 -29
  64. package/src/utils/response_wrappers.js +0 -100
  65. package/src/utils/response_wrappers.spec.js +0 -240
  66. package/src/utils/source_extraction.js +0 -53
  67. package/src/utils/source_extraction.spec.js +0 -194
  68. package/src/utils/trace.js +0 -19
  69. package/src/utils/trace.spec.js +0 -112
@@ -0,0 +1,26 @@
1
+ import { ValidationError } from '@outputai/core';
2
+ import { extractAttributes } from './attributes.js';
3
+
4
+ export const extractTag = v => {
5
+ const capture = v.match( /^<\/?\s*([\w-]+)(?:\s+(.+?))?\s*>$/ );
6
+ if ( !capture ) {
7
+ throw new ValidationError( `Could not parse tag "${v}".` );
8
+ }
9
+ const [ name, rawAttributes ] = capture.slice( 1, 3 );
10
+ if ( !name ) {
11
+ throw new ValidationError( `Could not parse tag "${v}".` );
12
+ }
13
+ return {
14
+ tagName: name.toLowerCase(),
15
+ attributes: rawAttributes ? extractAttributes( rawAttributes ) : {}
16
+ };
17
+ };
18
+
19
+ const hasClosing = v => /\/\s*>$/.test( v );
20
+ const hasOpening = v => /^<[A-Za-z][\w-]*(?=\s|\/?>)[^<]*>$/.test( v );
21
+
22
+ export const isOpeningTag = v => hasOpening( v ) && !hasClosing( v );
23
+ export const isComment = v => v.startsWith( '<!--' ) && v.endsWith( '-->' ) && v.length >= 7 && !v.slice( 4, -3 ).includes( '-->' );
24
+ export const isSelfClosingTag = v => hasOpening( v ) && hasClosing( v );
25
+ export const isEmptyText = v => /^\s*$/.test( v );
26
+ export const isClosingTag = v => /^<\/\s*[A-Za-z]+[\w-]*\s*>$/.test( v );
@@ -0,0 +1,250 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { extractAttributes } from './attributes.js';
3
+ import {
4
+ extractTag,
5
+ isClosingTag,
6
+ isComment,
7
+ isEmptyText,
8
+ isOpeningTag,
9
+ isSelfClosingTag
10
+ } from './tokens.js';
11
+
12
+ vi.mock( './attributes.js', () => ( {
13
+ extractAttributes: vi.fn()
14
+ } ) );
15
+
16
+ describe( 'extractTag', () => {
17
+ beforeEach( () => {
18
+ vi.mocked( extractAttributes ).mockReset().mockReturnValue( {} );
19
+ } );
20
+
21
+ it( 'extracts and lowercases an opening tag name', () => {
22
+ expect( extractTag( '<User>' ) ).toEqual( {
23
+ tagName: 'user',
24
+ attributes: {}
25
+ } );
26
+ expect( extractAttributes ).not.toHaveBeenCalled();
27
+ } );
28
+
29
+ it( 'extracts a hyphenated tag name', () => {
30
+ expect( extractTag( '<CUSTOM-BLOCK>' ) ).toEqual( {
31
+ tagName: 'custom-block',
32
+ attributes: {}
33
+ } );
34
+ } );
35
+
36
+ it( 'extracts a closing tag name', () => {
37
+ expect( extractTag( '</User>' ) ).toEqual( {
38
+ tagName: 'user',
39
+ attributes: {}
40
+ } );
41
+ } );
42
+
43
+ it( 'supports whitespace inside closing tags', () => {
44
+ expect( extractTag( '</ User >' ) ).toEqual( {
45
+ tagName: 'user',
46
+ attributes: {}
47
+ } );
48
+ expect( extractAttributes ).not.toHaveBeenCalled();
49
+ } );
50
+
51
+ it( 'delegates raw opening-tag attributes', () => {
52
+ const attributes = { options: 'cached shared', pinned: true };
53
+ vi.mocked( extractAttributes ).mockReturnValue( attributes );
54
+
55
+ expect( extractTag( '<user options = "cached shared" pinned>' ) ).toEqual( {
56
+ tagName: 'user',
57
+ attributes
58
+ } );
59
+ expect( extractAttributes ).toHaveBeenCalledOnce();
60
+ expect( extractAttributes ).toHaveBeenCalledWith( 'options = "cached shared" pinned' );
61
+ } );
62
+
63
+ it( 'propagates attribute parsing errors', () => {
64
+ vi.mocked( extractAttributes ).mockImplementation( () => {
65
+ throw new Error( 'invalid attributes' );
66
+ } );
67
+
68
+ expect( () => extractTag( '<user color="red>' ) ).toThrow( 'invalid attributes' );
69
+ } );
70
+
71
+ it( 'throws a descriptive error for a malformed token', () => {
72
+ expect( () => extractTag( 'plain text' ) )
73
+ .toThrow( /^Could not parse tag "plain text"\.$/ );
74
+ } );
75
+ } );
76
+
77
+ describe( 'isOpeningTag', () => {
78
+ it.each( [
79
+ '<user>',
80
+ '<user >',
81
+ '<User options="cached">',
82
+ '<custom-block mode=fast>',
83
+ '<user\toptions=fast>',
84
+ '<user\noptions="cached shared">',
85
+ '<user condition="score > 10">',
86
+ '<user color=\'red>'
87
+ ] )( 'recognizes %s', token => {
88
+ expect( isOpeningTag( token ) ).toBe( true );
89
+ } );
90
+
91
+ it.each( [
92
+ '</user>',
93
+ '< user>',
94
+ '<>',
95
+ '<,>',
96
+ '<b,b>',
97
+ '<b, b>',
98
+ '<user,>',
99
+ '<user=admin>',
100
+ '<user.name>',
101
+ '<1user>',
102
+ '<_user>',
103
+ '<üser>',
104
+ '<user />',
105
+ '<user/>',
106
+ '<user options="cached" />',
107
+ '<user / >',
108
+ '<!-- note -->',
109
+ '<!DOCTYPE html>',
110
+ '<?xml version="1.0"?>',
111
+ '<user',
112
+ 'user>',
113
+ '<user></user>',
114
+ '<user<other>>',
115
+ '<user condition="a < b">',
116
+ 'plain text'
117
+ ] )( 'rejects %s', token => {
118
+ expect( isOpeningTag( token ) ).toBe( false );
119
+ } );
120
+ } );
121
+
122
+ describe( 'isClosingTag', () => {
123
+ it.each( [
124
+ '</user>',
125
+ '</User>',
126
+ '</custom-block>',
127
+ '</ user >',
128
+ '</user >',
129
+ '</\tuser\t>',
130
+ '</\nuser\n>'
131
+ ] )( 'recognizes %s', token => {
132
+ expect( isClosingTag( token ) ).toBe( true );
133
+ } );
134
+
135
+ it.each( [
136
+ '<user>',
137
+ '<user />',
138
+ '<!-- note -->',
139
+ '</>',
140
+ '< /user>',
141
+ '</user',
142
+ '</user/>',
143
+ '</user / >',
144
+ '</user options=ignored>',
145
+ '</b,b>',
146
+ '</1user>',
147
+ '</_user>',
148
+ '</üser>',
149
+ '</user> suffix',
150
+ 'prefix </user>',
151
+ '</user></system>',
152
+ '</user<system>>',
153
+ 'plain text'
154
+ ] )( 'rejects %s', token => {
155
+ expect( isClosingTag( token ) ).toBe( false );
156
+ } );
157
+ } );
158
+
159
+ describe( 'isSelfClosingTag', () => {
160
+ it.each( [
161
+ '<user/>',
162
+ '<user />',
163
+ '<CUSTOM-BLOCK />',
164
+ '<image source="avatar.png" />',
165
+ '<user options = "cached shared" />',
166
+ '<user condition="score > 10"/>',
167
+ '<user\tmode=fast\t/>',
168
+ '<user\nmode=fast\n/>',
169
+ '<user / >',
170
+ '<user color=\'red />'
171
+ ] )( 'recognizes %s', token => {
172
+ expect( isSelfClosingTag( token ) ).toBe( true );
173
+ } );
174
+
175
+ it.each( [
176
+ '<user>',
177
+ '</user>',
178
+ '<!-- note -->',
179
+ '< user/>',
180
+ '<>',
181
+ '<,/>',
182
+ '<b,b/>',
183
+ '<user,/>',
184
+ '<1user/>',
185
+ '<_user/>',
186
+ '<üser/>',
187
+ '</user/>',
188
+ '<user/',
189
+ '<user/> suffix',
190
+ 'prefix <user/>',
191
+ '<user/><system/>',
192
+ '<user<other>/>',
193
+ '<!DOCTYPE html />',
194
+ '<?xml version="1.0"?>',
195
+ '<user path="/tmp">',
196
+ '<user path="/" >',
197
+ 'plain text'
198
+ ] )( 'rejects %s', token => {
199
+ expect( isSelfClosingTag( token ) ).toBe( false );
200
+ } );
201
+ } );
202
+
203
+ describe( 'isComment', () => {
204
+ it.each( [
205
+ '<!---->',
206
+ '<!-- -->',
207
+ '<!-- note -->',
208
+ '<!-- first\nsecond -->',
209
+ '<!-- <user>text</user> -->',
210
+ '<!-- a > b and c < d -->'
211
+ ] )( 'recognizes %s', token => {
212
+ expect( isComment( token ) ).toBe( true );
213
+ } );
214
+
215
+ it.each( [
216
+ '<!-->',
217
+ '<! -- note -->',
218
+ '<!-- unfinished',
219
+ '<!-- note -- >',
220
+ '<!-- note --!>',
221
+ 'prefix <!-- note -->',
222
+ '<!-- note --> suffix',
223
+ '<user><!-- note --></user>',
224
+ '<!-- first --><!-- second -->',
225
+ '<!-- first -->\n<!-- second -->',
226
+ '<!-- -->text<!-- -->'
227
+ ] )( 'rejects %s', token => {
228
+ expect( isComment( token ) ).toBe( false );
229
+ } );
230
+ } );
231
+
232
+ describe( 'isEmptyText', () => {
233
+ it.each( [
234
+ '',
235
+ ' ',
236
+ '\t',
237
+ '\n\n',
238
+ ' \n\t '
239
+ ] )( 'recognizes whitespace-only text', token => {
240
+ expect( isEmptyText( token ) ).toBe( true );
241
+ } );
242
+
243
+ it.each( [
244
+ 'text',
245
+ ' text ',
246
+ '<user>'
247
+ ] )( 'rejects non-whitespace text', token => {
248
+ expect( isEmptyText( token ) ).toBe( false );
249
+ } );
250
+ } );
@@ -1,95 +1,126 @@
1
1
  import { Logger, ValidationError, z } from '@outputai/core';
2
- import { attributesSchema } from './block_options.js';
2
+ import { deprecatedProviderAliases } from '../deprecated_provider_aliases.js';
3
3
 
4
- const toolConfigSchema = z.record( z.string(), z.unknown() );
5
- const toolsConfigSchema = z.record( z.string(), toolConfigSchema );
4
+ const log = Logger.createLogger( 'LLM' );
6
5
 
7
- // A provider-namespaced options object, e.g. { anthropic: { cacheControl: { type: 'ephemeral' } } }
8
- const providerOptionsSchema = z.record( z.string(), z.record( z.string(), z.unknown() ) );
6
+ const handleDeprecatedKeys = prompt => {
7
+ const { config: { maxTokens, maxOutputTokens, provider } } = prompt;
8
+
9
+ // @TODO: maxTokens was replaced by maxOutputTokens in v0.12, it can be removed down the road
10
+ if ( Number.isFinite( maxTokens ) ) {
11
+ if ( Number.isFinite( maxOutputTokens ) ) {
12
+ log.warn( 'Prompt has both "maxOutputTokens" and deprecated "maxTokens" keys set, "maxTokens" value will be ignored.' );
13
+ } else {
14
+ log.warn( 'Prompt has deprecated key "maxTokens". Its value was set to "maxOutputTokens".' );
15
+ prompt.config.maxOutputTokens = maxTokens;
16
+ }
17
+ }
18
+
19
+ // @TODO: this handle aliases removal in v0.11, it can be removed down the road
20
+ if ( Object.hasOwn( deprecatedProviderAliases, provider ) ) {
21
+ const canonical = deprecatedProviderAliases[provider];
22
+ log.warn( `Prompt uses deprecated provider alias "${provider}". Use "${canonical}" instead.` );
23
+ prompt.config.provider = canonical;
24
+ }
25
+
26
+ return prompt;
27
+ };
28
+
29
+ const objectMapSchema = z.record(
30
+ z.string(),
31
+ z.record(
32
+ z.string(),
33
+ z.unknown()
34
+ )
35
+ );
36
+
37
+ const promptConfigSchema = z.object( {
38
+ aspectRatio: z.string().regex( /^\d+:\d+$/ ).optional(),
39
+ frequencyPenalty: z.number().optional(),
40
+ maxImagesPerCall: z.number().int().positive().optional(),
41
+ maxOutputTokens: z.number().int().positive().optional(),
42
+ maxSteps: z.number().int().positive().default( 10 ),
43
+ maxTokens: z.number().int().positive().optional(),
44
+ // A provider-namespaced options object, e.g. { anthropic: { cacheControl: { type: 'ephemeral' } } }
45
+ messageOptions: z.record( z.string(), objectMapSchema ).optional(),
46
+ model: z.string().min( 1 ),
47
+ n: z.number().int().positive().optional(),
48
+ presencePenalty: z.number().optional(),
49
+ provider: z.string().min( 1 ),
50
+ providerOptions: z.object( {
51
+ thinking: z.object( {
52
+ type: z.enum( [ 'enabled', 'disabled' ] ),
53
+ budgetTokens: z.number().optional()
54
+ } ).loose().optional()
55
+ } ).loose().optional(),
56
+ seed: z.number().int().optional(),
57
+ size: z.string().regex( /^\d+x\d+$/ ).optional(),
58
+ skills: z.preprocess( v => Array.isArray( v ) ? v : [].concat( v ?? [] ), z.array( z.string().min( 1 ) ) ),
59
+ stopSequences: z.array( z.string() ).optional(),
60
+ temperature: z.number().nonnegative().optional(),
61
+ topK: z.number().nonnegative().optional(),
62
+ topP: z.number().nonnegative().optional(),
63
+ tools: objectMapSchema.optional()
64
+ } ).strict();
9
65
 
10
66
  export const promptSchema = z.object( {
11
67
  name: z.string(),
12
- config: z.object( {
13
- provider: z.string().min( 1 ),
14
- model: z.string(),
15
- temperature: z.number().optional(),
16
- maxTokens: z.number().optional(),
17
- n: z.number().int().positive().optional(),
18
- maxImagesPerCall: z.number().int().positive().optional(),
19
- size: z.string().regex( /^\d+x\d+$/ ).optional(),
20
- aspectRatio: z.string().regex( /^\d+:\d+$/ ).optional(),
21
- seed: z.number().int().optional(),
22
- skills: z.union( [ z.string().min( 1 ), z.array( z.string().min( 1 ) ) ] ).optional(),
23
- tools: toolsConfigSchema.optional(),
24
- providerOptions: z.object( {
25
- thinking: z.object( {
26
- type: z.enum( [ 'enabled', 'disabled' ] ),
27
- budgetTokens: z.number().optional()
28
- } ).loose().optional()
29
- } ).loose().optional(),
30
- messageOptions: z.record( z.string(), providerOptionsSchema ).optional()
31
- } ).loose(),
68
+ config: promptConfigSchema,
32
69
  messages: z.array(
33
70
  z.object( {
34
71
  role: z.string(),
35
72
  content: z.string(),
36
- attributes: attributesSchema.optional()
73
+ providerOptions: objectMapSchema.optional()
37
74
  } ).strict()
38
75
  ),
39
- instructions: z.string().trim().min( 1 ).nullable().optional()
76
+ instructions: z.string().trim().min( 1 ).nullable().default( null ),
77
+ fileDir: z.string(),
78
+ variables: z.record( z.string(), z.unknown() ).default( {} )
40
79
  } ).strict().superRefine( ( prompt, ctx ) => {
41
80
  const hasMessages = prompt.messages.length > 0;
42
81
  const hasInstructions = !!prompt.instructions;
82
+ const addIssue = message => ctx.addIssue( { code: 'custom', path: [ 'messages', 'instructions' ], message } );
83
+
43
84
  if ( !hasMessages && !hasInstructions ) {
44
- ctx.addIssue( {
45
- code: 'custom',
46
- path: [ 'messages', 'instructions' ],
47
- message: 'Prompt must include either message blocks or plain instructions.'
48
- } );
49
- }
50
- if ( hasMessages && hasInstructions ) {
51
- ctx.addIssue( {
52
- code: 'custom',
53
- path: [ 'messages', 'instructions' ],
54
- message: 'Prompt cannot include both message blocks and plain instructions.'
55
- } );
85
+ addIssue( 'Prompt must include either message blocks or plain instructions.' );
86
+ } else if ( hasMessages && hasInstructions ) {
87
+ addIssue( 'Prompt cannot include both message blocks and plain instructions.' );
56
88
  }
57
- } );
58
-
59
- const SNAKE_CASE_WARNINGS = {
60
- max_tokens: 'maxTokens',
61
- max_images_per_call: 'maxImagesPerCall',
62
- aspect_ratio: 'aspectRatio',
63
- budget_tokens: 'budgetTokens',
64
- top_p: 'topP',
65
- top_k: 'topK',
66
- stop_sequences: 'stopSequences',
67
- options: 'providerOptions'
68
- };
89
+ } ).transform( handleDeprecatedKeys );
90
+
91
+ const promptConfigKeys = new Set( Object.keys( promptConfigSchema.shape ) );
92
+
93
+ /** Converts a string to camel case */
94
+ const toCamelCase = value => value.replace( /_([a-z])/g, ( _, letter ) => letter.toUpperCase() );
69
95
 
70
- function warnSnakeCaseFields( config ) {
71
- for ( const [ snake, camel ] of Object.entries( SNAKE_CASE_WARNINGS ) ) {
72
- if ( Object.hasOwn( config, snake ) ) {
73
- Logger.warn( `[output-llm] "${snake}" found in prompt config. Did you mean "${camel}"?`, { namespace: 'LLM' } );
96
+ /** Appends camelCase suggestions to unrecognized top-level config keys written in snake_case. */
97
+ const appendCamelCaseSuggestions = error => {
98
+ for ( const issue of error.issues ) {
99
+ if ( issue.code !== 'unrecognized_keys' || issue.path.length !== 1 || issue.path[0] !== 'config' ) {
100
+ continue;
101
+ }
102
+
103
+ const suggestions = issue.keys
104
+ .filter( key => key.includes( '_' ) )
105
+ .map( key => ( { key, camel: toCamelCase( key ) } ) )
106
+ .filter( ( { key, camel } ) => camel !== key && promptConfigKeys.has( camel ) )
107
+ .map( ( { key, camel } ) => `"${key}" is not valid; use "${camel}"` );
108
+
109
+ if ( suggestions.length > 0 ) {
110
+ issue.message = `${issue.message}. ${suggestions.join( '. ' )}`;
74
111
  }
75
112
  }
76
- const thinking = config.providerOptions?.thinking;
77
- if ( thinking && Object.hasOwn( thinking, 'budget_tokens' ) ) {
78
- Logger.warn( '[output-llm] "budget_tokens" found in providerOptions.thinking. Did you mean "budgetTokens"?', { namespace: 'LLM' } );
79
- }
80
- }
113
+ };
81
114
 
82
- export function validatePrompt( prompt ) {
115
+ export const parsePromptSchema = prompt => {
83
116
  const result = promptSchema.safeParse( prompt );
84
117
  if ( !result.success ) {
85
- const promptIdentifier = prompt?.name ? `"${prompt.name}"` : '(unnamed)';
86
- const errorMessage = z.prettifyError( result.error );
118
+ appendCamelCaseSuggestions( result.error );
87
119
 
88
120
  throw new ValidationError(
89
- `Invalid prompt file ${promptIdentifier}: ${errorMessage}`,
121
+ `Invalid prompt file ${prompt.name}: ${z.prettifyError( result.error )}`,
90
122
  { cause: result.error }
91
123
  );
92
124
  }
93
-
94
- warnSnakeCaseFields( result.data.config );
95
- }
125
+ return result.data;
126
+ };