briyah 2.0.16 → 2.0.17
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-sdk/server/src/ai/LLM/anthropic-output-schema.d.ts +24 -0
- package/dist-sdk/server/src/ai/LLM/anthropic-output-schema.js +111 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +29 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +77 -1
- package/dist-sdk/server/src/tools/tool-execution.service.js +5 -1
- package/package.json +1 -1
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns a Briyah response schema into one Anthropic's structured outputs accept.
|
|
3
|
+
*
|
|
4
|
+
* Every other provider already constrains its reply to the schema it is given
|
|
5
|
+
* (OpenAI `json_schema`, Gemini `responseSchema`, Together `json_schema`); the
|
|
6
|
+
* Anthropic path used to paste the schema into the prompt and only check that the
|
|
7
|
+
* reply parsed. Valid JSON in the wrong shape went straight through: an agent that
|
|
8
|
+
* answered with a tool's bare arguments — `{"dataset": …}` with no `action` — was
|
|
9
|
+
* accepted, routed to the moderator, and stalled its room. Sent as
|
|
10
|
+
* `output_config.format`, the schema is enforced while the reply is generated, so
|
|
11
|
+
* that shape cannot be produced.
|
|
12
|
+
*
|
|
13
|
+
* Anthropic's schema dialect is narrower than JSON Schema. Every object must say
|
|
14
|
+
* `additionalProperties: false`, and some keywords are refused. This returns a
|
|
15
|
+
* copy that meets those rules, or null when the schema needs something the dialect
|
|
16
|
+
* cannot express — the caller then sends no format and falls back to the prompt
|
|
17
|
+
* contract alone, which is what every call did before.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* The schema to send as `output_config.format.schema`, or null when it cannot be sent.
|
|
21
|
+
* @param jsonSchema A Briyah response schema, as loaded from a prompt folder's `.json`
|
|
22
|
+
* @returns A converted copy (the input is never modified), or null
|
|
23
|
+
*/
|
|
24
|
+
export declare function toAnthropicOutputSchema(jsonSchema: unknown): Record<string, unknown> | null;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Turns a Briyah response schema into one Anthropic's structured outputs accept.
|
|
4
|
+
*
|
|
5
|
+
* Every other provider already constrains its reply to the schema it is given
|
|
6
|
+
* (OpenAI `json_schema`, Gemini `responseSchema`, Together `json_schema`); the
|
|
7
|
+
* Anthropic path used to paste the schema into the prompt and only check that the
|
|
8
|
+
* reply parsed. Valid JSON in the wrong shape went straight through: an agent that
|
|
9
|
+
* answered with a tool's bare arguments — `{"dataset": …}` with no `action` — was
|
|
10
|
+
* accepted, routed to the moderator, and stalled its room. Sent as
|
|
11
|
+
* `output_config.format`, the schema is enforced while the reply is generated, so
|
|
12
|
+
* that shape cannot be produced.
|
|
13
|
+
*
|
|
14
|
+
* Anthropic's schema dialect is narrower than JSON Schema. Every object must say
|
|
15
|
+
* `additionalProperties: false`, and some keywords are refused. This returns a
|
|
16
|
+
* copy that meets those rules, or null when the schema needs something the dialect
|
|
17
|
+
* cannot express — the caller then sends no format and falls back to the prompt
|
|
18
|
+
* contract alone, which is what every call did before.
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.toAnthropicOutputSchema = toAnthropicOutputSchema;
|
|
22
|
+
/** Keywords Anthropic's structured outputs refuse. Dropping one loosens nothing the reply relies on. */
|
|
23
|
+
const UNSUPPORTED_KEYWORDS = [
|
|
24
|
+
'minimum',
|
|
25
|
+
'maximum',
|
|
26
|
+
'exclusiveMinimum',
|
|
27
|
+
'exclusiveMaximum',
|
|
28
|
+
'multipleOf',
|
|
29
|
+
'minLength',
|
|
30
|
+
'maxLength',
|
|
31
|
+
'maxItems',
|
|
32
|
+
'uniqueItems',
|
|
33
|
+
'minProperties',
|
|
34
|
+
'maxProperties',
|
|
35
|
+
'patternProperties',
|
|
36
|
+
];
|
|
37
|
+
/** String formats Anthropic validates; any other `format` is dropped. */
|
|
38
|
+
const SUPPORTED_FORMATS = new Set([
|
|
39
|
+
'date-time', 'time', 'date', 'duration', 'email', 'hostname', 'uri', 'ipv4', 'ipv6', 'uuid',
|
|
40
|
+
]);
|
|
41
|
+
/** Keywords whose value is one subschema. */
|
|
42
|
+
const SUBSCHEMA_KEYS = ['items', 'not'];
|
|
43
|
+
/** Keywords whose value is a list of subschemas. */
|
|
44
|
+
const SUBSCHEMA_LIST_KEYS = ['anyOf', 'allOf', 'oneOf', 'prefixItems'];
|
|
45
|
+
/** Keywords whose value maps names to subschemas. */
|
|
46
|
+
const SUBSCHEMA_MAP_KEYS = ['properties', '$defs', 'definitions'];
|
|
47
|
+
/** Thrown inside the walk when a schema cannot be expressed; caught by the entry point. */
|
|
48
|
+
class Inexpressible extends Error {
|
|
49
|
+
}
|
|
50
|
+
function isObjectSchema(schema) {
|
|
51
|
+
const type = schema.type;
|
|
52
|
+
return type === 'object' || (Array.isArray(type) && type.includes('object')) || 'properties' in schema;
|
|
53
|
+
}
|
|
54
|
+
function convert(schema) {
|
|
55
|
+
if (Array.isArray(schema))
|
|
56
|
+
return schema.map(convert);
|
|
57
|
+
if (!schema || typeof schema !== 'object')
|
|
58
|
+
return schema;
|
|
59
|
+
const out = {};
|
|
60
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
61
|
+
if (UNSUPPORTED_KEYWORDS.includes(key))
|
|
62
|
+
continue;
|
|
63
|
+
if (key === 'format' && !SUPPORTED_FORMATS.has(String(value)))
|
|
64
|
+
continue;
|
|
65
|
+
// Only 0 or 1 is accepted as a minimum item count.
|
|
66
|
+
if (key === 'minItems' && Number(value) > 1)
|
|
67
|
+
continue;
|
|
68
|
+
if (SUBSCHEMA_KEYS.includes(key)) {
|
|
69
|
+
out[key] = convert(value);
|
|
70
|
+
}
|
|
71
|
+
else if (SUBSCHEMA_LIST_KEYS.includes(key) && Array.isArray(value)) {
|
|
72
|
+
out[key] = value.map(convert);
|
|
73
|
+
}
|
|
74
|
+
else if (SUBSCHEMA_MAP_KEYS.includes(key) && value && typeof value === 'object') {
|
|
75
|
+
out[key] = Object.fromEntries(Object.entries(value).map(([name, sub]) => [name, convert(sub)]));
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
out[key] = value;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (isObjectSchema(out)) {
|
|
82
|
+
// An open object — a map of arbitrary keys — is not expressible at all.
|
|
83
|
+
if (out.additionalProperties !== undefined && out.additionalProperties !== false) {
|
|
84
|
+
throw new Inexpressible('additionalProperties other than false');
|
|
85
|
+
}
|
|
86
|
+
out.additionalProperties = false;
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The schema to send as `output_config.format.schema`, or null when it cannot be sent.
|
|
92
|
+
* @param jsonSchema A Briyah response schema, as loaded from a prompt folder's `.json`
|
|
93
|
+
* @returns A converted copy (the input is never modified), or null
|
|
94
|
+
*/
|
|
95
|
+
function toAnthropicOutputSchema(jsonSchema) {
|
|
96
|
+
if (!jsonSchema || typeof jsonSchema !== 'object' || Array.isArray(jsonSchema))
|
|
97
|
+
return null;
|
|
98
|
+
// `name` labels the schema for OpenAI's response_format; it is not a JSON Schema keyword.
|
|
99
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
100
|
+
const { name: _name, ...schema } = jsonSchema;
|
|
101
|
+
try {
|
|
102
|
+
const converted = convert(schema);
|
|
103
|
+
// Structured outputs describe an object reply; anything else stays on the prompt contract.
|
|
104
|
+
return isObjectSchema(converted) ? converted : null;
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (error instanceof Inexpressible)
|
|
108
|
+
return null;
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -76,6 +76,35 @@ export declare class AnthropicAiService extends BaseAiService {
|
|
|
76
76
|
*/
|
|
77
77
|
private static trimHeadroom;
|
|
78
78
|
textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, cacheConfig?: any, maxOutputChars?: number): Promise<any>;
|
|
79
|
+
/**
|
|
80
|
+
* Model and schema pairs the API refused a format for. Later calls with the same
|
|
81
|
+
* pair go out on the prompt contract alone rather than failing first every time.
|
|
82
|
+
* Process-lifetime: a model that gains support is picked up on restart.
|
|
83
|
+
*/
|
|
84
|
+
private static readonly unconstrained;
|
|
85
|
+
/**
|
|
86
|
+
* The schema to enforce on this call, or null to rely on the prompt contract.
|
|
87
|
+
* @param agent The agent being prompted
|
|
88
|
+
* @param jsonSchema The response schema, if the call has one
|
|
89
|
+
* @returns The converted schema and the key it is remembered under, or null
|
|
90
|
+
*/
|
|
91
|
+
private outputFormatFor;
|
|
92
|
+
/**
|
|
93
|
+
* Sends a request, and when the API refuses its output format, sends it again
|
|
94
|
+
* without one.
|
|
95
|
+
*
|
|
96
|
+
* Not every model supports structured outputs, and the model table cannot say
|
|
97
|
+
* which: litellm's `supports_response_schema` is set on models the API refuses a
|
|
98
|
+
* format for. So the API decides. The pair is only remembered as refused when the
|
|
99
|
+
* same request then succeeds without the format; a 400 for any other reason
|
|
100
|
+
* fails again, the format is put back, and the error goes to the caller's retry
|
|
101
|
+
* loop as it always did.
|
|
102
|
+
* @param params The request, mutated to drop the format once it is refused, so the
|
|
103
|
+
* caller's retries and a paused-turn resume do not send it again
|
|
104
|
+
* @param formatKey The key from outputFormatFor, when a format was attached
|
|
105
|
+
* @returns The API's response
|
|
106
|
+
*/
|
|
107
|
+
private createConstrained;
|
|
79
108
|
/**
|
|
80
109
|
* Appends "here is what you said, now correct it" to a local messages array
|
|
81
110
|
* for a retry.
|
|
@@ -19,6 +19,7 @@ const errors_1 = require("../../common/errors");
|
|
|
19
19
|
const logger_1 = require("../../common/logger");
|
|
20
20
|
const ai_debug_logger_1 = require("../ai-debug-logger");
|
|
21
21
|
const attachment_type_1 = require("./attachment-type");
|
|
22
|
+
const anthropic_output_schema_1 = require("./anthropic-output-schema");
|
|
22
23
|
let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.BaseAiService {
|
|
23
24
|
static { AnthropicAiService_1 = this; }
|
|
24
25
|
anthropic;
|
|
@@ -322,10 +323,20 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
|
|
|
322
323
|
createParams.thinking = { type: 'disabled' };
|
|
323
324
|
createParams.temperature = 0;
|
|
324
325
|
}
|
|
326
|
+
// Enforce the schema while the reply is generated, where the API can (see
|
|
327
|
+
// anthropic-output-schema.ts). The prompt keeps its copy of the schema: its
|
|
328
|
+
// descriptions still tell the model what each field is for.
|
|
329
|
+
const format = this.outputFormatFor(agent, jsonSchema);
|
|
330
|
+
if (format) {
|
|
331
|
+
createParams.output_config = {
|
|
332
|
+
...(createParams.output_config ?? {}),
|
|
333
|
+
format: { type: 'json_schema', schema: format.schema },
|
|
334
|
+
};
|
|
335
|
+
}
|
|
325
336
|
this.debugLogRequest(agent.agentName, createParams);
|
|
326
337
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
327
338
|
try {
|
|
328
|
-
let response = await this.
|
|
339
|
+
let response = await this.createConstrained(createParams, format?.key);
|
|
329
340
|
if (response.usage) {
|
|
330
341
|
this.computeMessageCost(agent, response.usage);
|
|
331
342
|
}
|
|
@@ -434,6 +445,71 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
|
|
|
434
445
|
// If we get here, all retries failed
|
|
435
446
|
throw new Error(`Failed to get valid response after ${maxRetries} attempts. Last error: ${lastError?.message || 'Unknown error'}`);
|
|
436
447
|
}
|
|
448
|
+
/**
|
|
449
|
+
* Model and schema pairs the API refused a format for. Later calls with the same
|
|
450
|
+
* pair go out on the prompt contract alone rather than failing first every time.
|
|
451
|
+
* Process-lifetime: a model that gains support is picked up on restart.
|
|
452
|
+
*/
|
|
453
|
+
static unconstrained = new Set();
|
|
454
|
+
/**
|
|
455
|
+
* The schema to enforce on this call, or null to rely on the prompt contract.
|
|
456
|
+
* @param agent The agent being prompted
|
|
457
|
+
* @param jsonSchema The response schema, if the call has one
|
|
458
|
+
* @returns The converted schema and the key it is remembered under, or null
|
|
459
|
+
*/
|
|
460
|
+
outputFormatFor(agent, jsonSchema) {
|
|
461
|
+
if (!jsonSchema)
|
|
462
|
+
return null;
|
|
463
|
+
// A web search answer carries citations, and structured outputs refuse citations.
|
|
464
|
+
if (agent.allowSearch)
|
|
465
|
+
return null;
|
|
466
|
+
const schema = (0, anthropic_output_schema_1.toAnthropicOutputSchema)(jsonSchema);
|
|
467
|
+
if (!schema)
|
|
468
|
+
return null;
|
|
469
|
+
const key = `${agent.modelName}|${JSON.stringify(schema)}`;
|
|
470
|
+
return AnthropicAiService_1.unconstrained.has(key) ? null : { schema, key };
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Sends a request, and when the API refuses its output format, sends it again
|
|
474
|
+
* without one.
|
|
475
|
+
*
|
|
476
|
+
* Not every model supports structured outputs, and the model table cannot say
|
|
477
|
+
* which: litellm's `supports_response_schema` is set on models the API refuses a
|
|
478
|
+
* format for. So the API decides. The pair is only remembered as refused when the
|
|
479
|
+
* same request then succeeds without the format; a 400 for any other reason
|
|
480
|
+
* fails again, the format is put back, and the error goes to the caller's retry
|
|
481
|
+
* loop as it always did.
|
|
482
|
+
* @param params The request, mutated to drop the format once it is refused, so the
|
|
483
|
+
* caller's retries and a paused-turn resume do not send it again
|
|
484
|
+
* @param formatKey The key from outputFormatFor, when a format was attached
|
|
485
|
+
* @returns The API's response
|
|
486
|
+
*/
|
|
487
|
+
async createConstrained(params, formatKey) {
|
|
488
|
+
try {
|
|
489
|
+
return await this.anthropic.messages.create(params);
|
|
490
|
+
}
|
|
491
|
+
catch (error) {
|
|
492
|
+
const config = params.output_config;
|
|
493
|
+
if (!formatKey || error?.status !== 400 || !config?.format)
|
|
494
|
+
throw error;
|
|
495
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
496
|
+
const { format: _format, ...rest } = config;
|
|
497
|
+
if (Object.keys(rest).length)
|
|
498
|
+
params.output_config = rest;
|
|
499
|
+
else
|
|
500
|
+
delete params.output_config;
|
|
501
|
+
try {
|
|
502
|
+
const response = await this.anthropic.messages.create(params);
|
|
503
|
+
AnthropicAiService_1.unconstrained.add(formatKey);
|
|
504
|
+
logger_1.logger.warn(`Structured output refused for ${params.model}; this schema goes out unconstrained from now on: ${error.message}`);
|
|
505
|
+
return response;
|
|
506
|
+
}
|
|
507
|
+
catch (second) {
|
|
508
|
+
params.output_config = config;
|
|
509
|
+
throw second;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
437
513
|
/**
|
|
438
514
|
* Appends "here is what you said, now correct it" to a local messages array
|
|
439
515
|
* for a retry.
|
|
@@ -74,7 +74,11 @@ class ToolExecutionService {
|
|
|
74
74
|
*/
|
|
75
75
|
async runForAgent(name, contentJson, grantedNames, context, room, illustration, callerAgentId) {
|
|
76
76
|
if (!grantedNames.includes(name)) {
|
|
77
|
-
|
|
77
|
+
// Name the tools it does have. A model that put a tool's argument in the
|
|
78
|
+
// tool's place — `execute` with name "wc_experience_mods", a dataset of
|
|
79
|
+
// query_data — corrects itself in one step when it can see the right name.
|
|
80
|
+
const granted = grantedNames.length ? grantedNames.join(', ') : 'none';
|
|
81
|
+
return { ok: false, error: `Tool "${name}" is not available to you. Your tools: ${granted}.` };
|
|
78
82
|
}
|
|
79
83
|
let args = {};
|
|
80
84
|
if (contentJson && contentJson.trim()) {
|
package/package.json
CHANGED