@posthog/agent 1.16.6 → 1.18.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/README.md +6 -2
- package/dist/claude-cli/cli.js +3617 -0
- package/dist/claude-cli/package.json +3 -0
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/src/agent.d.ts +0 -3
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +6 -27
- package/dist/src/agent.js.map +1 -1
- package/dist/src/agents/research.d.ts +1 -1
- package/dist/src/agents/research.d.ts.map +1 -1
- package/dist/src/agents/research.js +84 -53
- package/dist/src/agents/research.js.map +1 -1
- package/dist/src/file-manager.d.ts +3 -21
- package/dist/src/file-manager.d.ts.map +1 -1
- package/dist/src/file-manager.js +15 -47
- package/dist/src/file-manager.js.map +1 -1
- package/dist/src/git-manager.d.ts.map +1 -1
- package/dist/src/git-manager.js +8 -1
- package/dist/src/git-manager.js.map +1 -1
- package/dist/src/posthog-api.d.ts +6 -1
- package/dist/src/posthog-api.d.ts.map +1 -1
- package/dist/src/posthog-api.js +28 -0
- package/dist/src/posthog-api.js.map +1 -1
- package/dist/src/task-progress-reporter.d.ts.map +1 -1
- package/dist/src/task-progress-reporter.js +0 -1
- package/dist/src/task-progress-reporter.js.map +1 -1
- package/dist/src/types.d.ts +21 -2
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/dist/src/workflow/steps/plan.d.ts.map +1 -1
- package/dist/src/workflow/steps/plan.js +26 -18
- package/dist/src/workflow/steps/plan.js.map +1 -1
- package/dist/src/workflow/steps/research.d.ts.map +1 -1
- package/dist/src/workflow/steps/research.js +100 -66
- package/dist/src/workflow/steps/research.js.map +1 -1
- package/dist/src/workflow/types.d.ts +0 -2
- package/dist/src/workflow/types.d.ts.map +1 -1
- package/dist/templates/plan-template.md +1 -5
- package/package.json +2 -6
- package/src/agent.ts +7 -31
- package/src/agents/research.ts +84 -53
- package/src/file-manager.ts +18 -73
- package/src/git-manager.ts +7 -1
- package/src/posthog-api.ts +33 -1
- package/src/task-progress-reporter.ts +0 -1
- package/src/templates/plan-template.md +1 -5
- package/src/types.ts +25 -2
- package/src/workflow/steps/plan.ts +28 -21
- package/src/workflow/steps/research.ts +109 -74
- package/src/workflow/types.ts +0 -2
- package/dist/_virtual/_commonjsHelpers.js +0 -6
- package/dist/_virtual/_commonjsHelpers.js.map +0 -1
- package/dist/_virtual/index.js +0 -4
- package/dist/_virtual/index.js.map +0 -1
- package/dist/node_modules/@ai-sdk/anthropic/dist/index.js +0 -1154
- package/dist/node_modules/@ai-sdk/anthropic/dist/index.js.map +0 -1
- package/dist/node_modules/@ai-sdk/provider/dist/index.js +0 -296
- package/dist/node_modules/@ai-sdk/provider/dist/index.js.map +0 -1
- package/dist/node_modules/@ai-sdk/provider-utils/dist/index.js +0 -576
- package/dist/node_modules/@ai-sdk/provider-utils/dist/index.js.map +0 -1
- package/dist/node_modules/@ai-sdk/ui-utils/dist/index.js +0 -741
- package/dist/node_modules/@ai-sdk/ui-utils/dist/index.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/api/context.js +0 -112
- package/dist/node_modules/@opentelemetry/api/build/esm/api/context.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/api/diag.js +0 -123
- package/dist/node_modules/@opentelemetry/api/build/esm/api/diag.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/api/metrics.js +0 -62
- package/dist/node_modules/@opentelemetry/api/build/esm/api/metrics.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/api/propagation.js +0 -91
- package/dist/node_modules/@opentelemetry/api/build/esm/api/propagation.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/api/trace.js +0 -79
- package/dist/node_modules/@opentelemetry/api/build/esm/api/trace.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js +0 -59
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js +0 -99
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/utils.js +0 -31
- package/dist/node_modules/@opentelemetry/api/build/esm/baggage/utils.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js +0 -69
- package/dist/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/context/context.js +0 -54
- package/dist/node_modules/@opentelemetry/api/build/esm/context/context.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/context-api.js +0 -22
- package/dist/node_modules/@opentelemetry/api/build/esm/context-api.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js +0 -104
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js +0 -44
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/types.js +0 -43
- package/dist/node_modules/@opentelemetry/api/build/esm/diag/types.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/diag-api.js +0 -27
- package/dist/node_modules/@opentelemetry/api/build/esm/diag-api.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js +0 -62
- package/dist/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/internal/semver.js +0 -121
- package/dist/node_modules/@opentelemetry/api/build/esm/internal/semver.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js +0 -167
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js +0 -33
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics-api.js +0 -22
- package/dist/node_modules/@opentelemetry/api/build/esm/metrics-api.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js +0 -21
- package/dist/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js +0 -35
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js +0 -40
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation-api.js +0 -22
- package/dist/node_modules/@opentelemetry/api/build/esm/propagation-api.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js +0 -70
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js +0 -78
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js +0 -34
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js +0 -55
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js +0 -56
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js +0 -76
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js +0 -27
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js +0 -45
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/status.js +0 -22
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/status.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js +0 -25
- package/dist/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/trace-api.js +0 -24
- package/dist/node_modules/@opentelemetry/api/build/esm/trace-api.js.map +0 -1
- package/dist/node_modules/@opentelemetry/api/build/esm/version.js +0 -20
- package/dist/node_modules/@opentelemetry/api/build/esm/version.js.map +0 -1
- package/dist/node_modules/ai/dist/index.js +0 -2870
- package/dist/node_modules/ai/dist/index.js.map +0 -1
- package/dist/node_modules/nanoid/non-secure/index.js +0 -13
- package/dist/node_modules/nanoid/non-secure/index.js.map +0 -1
- package/dist/node_modules/secure-json-parse/index.js +0 -133
- package/dist/node_modules/secure-json-parse/index.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/Options.js +0 -37
- package/dist/node_modules/zod-to-json-schema/dist/esm/Options.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/Refs.js +0 -26
- package/dist/node_modules/zod-to-json-schema/dist/esm/Refs.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/errorMessages.js +0 -17
- package/dist/node_modules/zod-to-json-schema/dist/esm/errorMessages.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +0 -11
- package/dist/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/index.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/index.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parseDef.js +0 -66
- package/dist/node_modules/zod-to-json-schema/dist/esm/parseDef.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/any.js +0 -21
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/any.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/array.js +0 -30
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/array.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js +0 -53
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/date.js +0 -50
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/date.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/default.js +0 -11
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/default.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js +0 -11
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js +0 -9
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +0 -56
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js +0 -24
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/map.js +0 -30
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/map.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js +0 -19
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/never.js +0 -15
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/never.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/null.js +0 -13
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/null.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js +0 -37
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/number.js +0 -56
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/number.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/object.js +0 -76
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/object.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js +0 -25
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js +0 -24
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/record.js +0 -65
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/record.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/set.js +0 -24
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/set.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/string.js +0 -350
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/string.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js +0 -36
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js +0 -10
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/union.js +0 -84
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/union.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js +0 -8
- package/dist/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/selectParser.js +0 -110
- package/dist/node_modules/zod-to-json-schema/dist/esm/selectParser.js.map +0 -1
- package/dist/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js +0 -90
- package/dist/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js.map +0 -1
- package/dist/src/structured-extraction.d.ts +0 -28
- package/dist/src/structured-extraction.d.ts.map +0 -1
- package/dist/src/structured-extraction.js +0 -77
- package/dist/src/structured-extraction.js.map +0 -1
- package/dist/src/utils/ai-sdk.d.ts +0 -14
- package/dist/src/utils/ai-sdk.d.ts.map +0 -1
- package/dist/src/utils/ai-sdk.js +0 -38
- package/dist/src/utils/ai-sdk.js.map +0 -1
- package/src/structured-extraction.ts +0 -117
- package/src/utils/ai-sdk.ts +0 -47
|
@@ -1,2870 +0,0 @@
|
|
|
1
|
-
import { createIdGenerator, isAbortError, getErrorMessage, delay, safeValidateTypes, safeParseJSON, convertUint8ArrayToBase64, convertBase64ToUint8Array, convertAsyncIteratorToReadableStream } from '../../@ai-sdk/provider-utils/dist/index.js';
|
|
2
|
-
import { asSchema, parsePartialJson, formatDataStreamPart } from '../../@ai-sdk/ui-utils/dist/index.js';
|
|
3
|
-
export { jsonSchema, zodSchema } from '../../@ai-sdk/ui-utils/dist/index.js';
|
|
4
|
-
import { AISDKError, APICallError, UnsupportedFunctionalityError, isJSONObject, TypeValidationError, isJSONArray, JSONParseError, InvalidPromptError } from '../../@ai-sdk/provider/dist/index.js';
|
|
5
|
-
export { EmptyResponseBodyError, LoadAPIKeyError, NoSuchModelError } from '../../@ai-sdk/provider/dist/index.js';
|
|
6
|
-
import { SpanStatusCode } from '../../@opentelemetry/api/build/esm/trace/status.js';
|
|
7
|
-
import { trace } from '../../@opentelemetry/api/build/esm/trace-api.js';
|
|
8
|
-
import { z } from 'zod';
|
|
9
|
-
|
|
10
|
-
var __defProp = Object.defineProperty;
|
|
11
|
-
var __export = (target, all) => {
|
|
12
|
-
for (var name17 in all)
|
|
13
|
-
__defProp(target, name17, { get: all[name17], enumerable: true });
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
// core/util/prepare-response-headers.ts
|
|
17
|
-
function prepareResponseHeaders(headers, {
|
|
18
|
-
contentType,
|
|
19
|
-
dataStreamVersion
|
|
20
|
-
}) {
|
|
21
|
-
const responseHeaders = new Headers(headers != null ? headers : {});
|
|
22
|
-
if (!responseHeaders.has("Content-Type")) {
|
|
23
|
-
responseHeaders.set("Content-Type", contentType);
|
|
24
|
-
}
|
|
25
|
-
if (dataStreamVersion !== void 0) {
|
|
26
|
-
responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
|
|
27
|
-
}
|
|
28
|
-
return responseHeaders;
|
|
29
|
-
}
|
|
30
|
-
var UnsupportedModelVersionError = class extends AISDKError {
|
|
31
|
-
constructor() {
|
|
32
|
-
super({
|
|
33
|
-
name: "AI_UnsupportedModelVersionError",
|
|
34
|
-
message: `Unsupported model version. AI SDK 4 only supports models that implement specification version "v1". Please upgrade to AI SDK 5 to use this model.`
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
var name = "AI_InvalidArgumentError";
|
|
39
|
-
var marker = `vercel.ai.error.${name}`;
|
|
40
|
-
var symbol = Symbol.for(marker);
|
|
41
|
-
var _a;
|
|
42
|
-
var InvalidArgumentError = class extends AISDKError {
|
|
43
|
-
constructor({
|
|
44
|
-
parameter,
|
|
45
|
-
value,
|
|
46
|
-
message
|
|
47
|
-
}) {
|
|
48
|
-
super({
|
|
49
|
-
name,
|
|
50
|
-
message: `Invalid argument for parameter ${parameter}: ${message}`
|
|
51
|
-
});
|
|
52
|
-
this[_a] = true;
|
|
53
|
-
this.parameter = parameter;
|
|
54
|
-
this.value = value;
|
|
55
|
-
}
|
|
56
|
-
static isInstance(error) {
|
|
57
|
-
return AISDKError.hasMarker(error, marker);
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
_a = symbol;
|
|
61
|
-
var name2 = "AI_RetryError";
|
|
62
|
-
var marker2 = `vercel.ai.error.${name2}`;
|
|
63
|
-
var symbol2 = Symbol.for(marker2);
|
|
64
|
-
var _a2;
|
|
65
|
-
var RetryError = class extends AISDKError {
|
|
66
|
-
constructor({
|
|
67
|
-
message,
|
|
68
|
-
reason,
|
|
69
|
-
errors
|
|
70
|
-
}) {
|
|
71
|
-
super({ name: name2, message });
|
|
72
|
-
this[_a2] = true;
|
|
73
|
-
this.reason = reason;
|
|
74
|
-
this.errors = errors;
|
|
75
|
-
this.lastError = errors[errors.length - 1];
|
|
76
|
-
}
|
|
77
|
-
static isInstance(error) {
|
|
78
|
-
return AISDKError.hasMarker(error, marker2);
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
_a2 = symbol2;
|
|
82
|
-
|
|
83
|
-
// util/retry-with-exponential-backoff.ts
|
|
84
|
-
var retryWithExponentialBackoff = ({
|
|
85
|
-
maxRetries = 2,
|
|
86
|
-
initialDelayInMs = 2e3,
|
|
87
|
-
backoffFactor = 2
|
|
88
|
-
} = {}) => async (f) => _retryWithExponentialBackoff(f, {
|
|
89
|
-
maxRetries,
|
|
90
|
-
delayInMs: initialDelayInMs,
|
|
91
|
-
backoffFactor
|
|
92
|
-
});
|
|
93
|
-
async function _retryWithExponentialBackoff(f, {
|
|
94
|
-
maxRetries,
|
|
95
|
-
delayInMs,
|
|
96
|
-
backoffFactor
|
|
97
|
-
}, errors = []) {
|
|
98
|
-
try {
|
|
99
|
-
return await f();
|
|
100
|
-
} catch (error) {
|
|
101
|
-
if (isAbortError(error)) {
|
|
102
|
-
throw error;
|
|
103
|
-
}
|
|
104
|
-
if (maxRetries === 0) {
|
|
105
|
-
throw error;
|
|
106
|
-
}
|
|
107
|
-
const errorMessage = getErrorMessage(error);
|
|
108
|
-
const newErrors = [...errors, error];
|
|
109
|
-
const tryNumber = newErrors.length;
|
|
110
|
-
if (tryNumber > maxRetries) {
|
|
111
|
-
throw new RetryError({
|
|
112
|
-
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
|
|
113
|
-
reason: "maxRetriesExceeded",
|
|
114
|
-
errors: newErrors
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
|
|
118
|
-
await delay(delayInMs);
|
|
119
|
-
return _retryWithExponentialBackoff(
|
|
120
|
-
f,
|
|
121
|
-
{ maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
|
|
122
|
-
newErrors
|
|
123
|
-
);
|
|
124
|
-
}
|
|
125
|
-
if (tryNumber === 1) {
|
|
126
|
-
throw error;
|
|
127
|
-
}
|
|
128
|
-
throw new RetryError({
|
|
129
|
-
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
|
|
130
|
-
reason: "errorNotRetryable",
|
|
131
|
-
errors: newErrors
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// core/prompt/prepare-retries.ts
|
|
137
|
-
function prepareRetries({
|
|
138
|
-
maxRetries
|
|
139
|
-
}) {
|
|
140
|
-
if (maxRetries != null) {
|
|
141
|
-
if (!Number.isInteger(maxRetries)) {
|
|
142
|
-
throw new InvalidArgumentError({
|
|
143
|
-
parameter: "maxRetries",
|
|
144
|
-
value: maxRetries,
|
|
145
|
-
message: "maxRetries must be an integer"
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
if (maxRetries < 0) {
|
|
149
|
-
throw new InvalidArgumentError({
|
|
150
|
-
parameter: "maxRetries",
|
|
151
|
-
value: maxRetries,
|
|
152
|
-
message: "maxRetries must be >= 0"
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
const maxRetriesResult = maxRetries != null ? maxRetries : 2;
|
|
157
|
-
return {
|
|
158
|
-
maxRetries: maxRetriesResult,
|
|
159
|
-
retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// core/telemetry/assemble-operation-name.ts
|
|
164
|
-
function assembleOperationName({
|
|
165
|
-
operationId,
|
|
166
|
-
telemetry
|
|
167
|
-
}) {
|
|
168
|
-
return {
|
|
169
|
-
// standardized operation and resource name:
|
|
170
|
-
"operation.name": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`,
|
|
171
|
-
"resource.name": telemetry == null ? void 0 : telemetry.functionId,
|
|
172
|
-
// detailed, AI SDK specific data:
|
|
173
|
-
"ai.operationId": operationId,
|
|
174
|
-
"ai.telemetry.functionId": telemetry == null ? void 0 : telemetry.functionId
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// core/telemetry/get-base-telemetry-attributes.ts
|
|
179
|
-
function getBaseTelemetryAttributes({
|
|
180
|
-
model,
|
|
181
|
-
settings,
|
|
182
|
-
telemetry,
|
|
183
|
-
headers
|
|
184
|
-
}) {
|
|
185
|
-
var _a17;
|
|
186
|
-
return {
|
|
187
|
-
"ai.model.provider": model.provider,
|
|
188
|
-
"ai.model.id": model.modelId,
|
|
189
|
-
// settings:
|
|
190
|
-
...Object.entries(settings).reduce((attributes, [key, value]) => {
|
|
191
|
-
attributes[`ai.settings.${key}`] = value;
|
|
192
|
-
return attributes;
|
|
193
|
-
}, {}),
|
|
194
|
-
// add metadata as attributes:
|
|
195
|
-
...Object.entries((_a17 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a17 : {}).reduce(
|
|
196
|
-
(attributes, [key, value]) => {
|
|
197
|
-
attributes[`ai.telemetry.metadata.${key}`] = value;
|
|
198
|
-
return attributes;
|
|
199
|
-
},
|
|
200
|
-
{}
|
|
201
|
-
),
|
|
202
|
-
// request headers
|
|
203
|
-
...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {
|
|
204
|
-
if (value !== void 0) {
|
|
205
|
-
attributes[`ai.request.headers.${key}`] = value;
|
|
206
|
-
}
|
|
207
|
-
return attributes;
|
|
208
|
-
}, {})
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// core/telemetry/noop-tracer.ts
|
|
213
|
-
var noopTracer = {
|
|
214
|
-
startSpan() {
|
|
215
|
-
return noopSpan;
|
|
216
|
-
},
|
|
217
|
-
startActiveSpan(name17, arg1, arg2, arg3) {
|
|
218
|
-
if (typeof arg1 === "function") {
|
|
219
|
-
return arg1(noopSpan);
|
|
220
|
-
}
|
|
221
|
-
if (typeof arg2 === "function") {
|
|
222
|
-
return arg2(noopSpan);
|
|
223
|
-
}
|
|
224
|
-
if (typeof arg3 === "function") {
|
|
225
|
-
return arg3(noopSpan);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
var noopSpan = {
|
|
230
|
-
spanContext() {
|
|
231
|
-
return noopSpanContext;
|
|
232
|
-
},
|
|
233
|
-
setAttribute() {
|
|
234
|
-
return this;
|
|
235
|
-
},
|
|
236
|
-
setAttributes() {
|
|
237
|
-
return this;
|
|
238
|
-
},
|
|
239
|
-
addEvent() {
|
|
240
|
-
return this;
|
|
241
|
-
},
|
|
242
|
-
addLink() {
|
|
243
|
-
return this;
|
|
244
|
-
},
|
|
245
|
-
addLinks() {
|
|
246
|
-
return this;
|
|
247
|
-
},
|
|
248
|
-
setStatus() {
|
|
249
|
-
return this;
|
|
250
|
-
},
|
|
251
|
-
updateName() {
|
|
252
|
-
return this;
|
|
253
|
-
},
|
|
254
|
-
end() {
|
|
255
|
-
return this;
|
|
256
|
-
},
|
|
257
|
-
isRecording() {
|
|
258
|
-
return false;
|
|
259
|
-
},
|
|
260
|
-
recordException() {
|
|
261
|
-
return this;
|
|
262
|
-
}
|
|
263
|
-
};
|
|
264
|
-
var noopSpanContext = {
|
|
265
|
-
traceId: "",
|
|
266
|
-
spanId: "",
|
|
267
|
-
traceFlags: 0
|
|
268
|
-
};
|
|
269
|
-
|
|
270
|
-
// core/telemetry/get-tracer.ts
|
|
271
|
-
function getTracer({
|
|
272
|
-
isEnabled = false,
|
|
273
|
-
tracer
|
|
274
|
-
} = {}) {
|
|
275
|
-
if (!isEnabled) {
|
|
276
|
-
return noopTracer;
|
|
277
|
-
}
|
|
278
|
-
if (tracer) {
|
|
279
|
-
return tracer;
|
|
280
|
-
}
|
|
281
|
-
return trace.getTracer("ai");
|
|
282
|
-
}
|
|
283
|
-
function recordSpan({
|
|
284
|
-
name: name17,
|
|
285
|
-
tracer,
|
|
286
|
-
attributes,
|
|
287
|
-
fn,
|
|
288
|
-
endWhenDone = true
|
|
289
|
-
}) {
|
|
290
|
-
return tracer.startActiveSpan(name17, { attributes }, async (span) => {
|
|
291
|
-
try {
|
|
292
|
-
const result = await fn(span);
|
|
293
|
-
if (endWhenDone) {
|
|
294
|
-
span.end();
|
|
295
|
-
}
|
|
296
|
-
return result;
|
|
297
|
-
} catch (error) {
|
|
298
|
-
try {
|
|
299
|
-
recordErrorOnSpan(span, error);
|
|
300
|
-
} finally {
|
|
301
|
-
span.end();
|
|
302
|
-
}
|
|
303
|
-
throw error;
|
|
304
|
-
}
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
function recordErrorOnSpan(span, error) {
|
|
308
|
-
if (error instanceof Error) {
|
|
309
|
-
span.recordException({
|
|
310
|
-
name: error.name,
|
|
311
|
-
message: error.message,
|
|
312
|
-
stack: error.stack
|
|
313
|
-
});
|
|
314
|
-
span.setStatus({
|
|
315
|
-
code: SpanStatusCode.ERROR,
|
|
316
|
-
message: error.message
|
|
317
|
-
});
|
|
318
|
-
} else {
|
|
319
|
-
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
// core/telemetry/select-telemetry-attributes.ts
|
|
324
|
-
function selectTelemetryAttributes({
|
|
325
|
-
telemetry,
|
|
326
|
-
attributes
|
|
327
|
-
}) {
|
|
328
|
-
if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) {
|
|
329
|
-
return {};
|
|
330
|
-
}
|
|
331
|
-
return Object.entries(attributes).reduce((attributes2, [key, value]) => {
|
|
332
|
-
if (value === void 0) {
|
|
333
|
-
return attributes2;
|
|
334
|
-
}
|
|
335
|
-
if (typeof value === "object" && "input" in value && typeof value.input === "function") {
|
|
336
|
-
if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) {
|
|
337
|
-
return attributes2;
|
|
338
|
-
}
|
|
339
|
-
const result = value.input();
|
|
340
|
-
return result === void 0 ? attributes2 : { ...attributes2, [key]: result };
|
|
341
|
-
}
|
|
342
|
-
if (typeof value === "object" && "output" in value && typeof value.output === "function") {
|
|
343
|
-
if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) {
|
|
344
|
-
return attributes2;
|
|
345
|
-
}
|
|
346
|
-
const result = value.output();
|
|
347
|
-
return result === void 0 ? attributes2 : { ...attributes2, [key]: result };
|
|
348
|
-
}
|
|
349
|
-
return { ...attributes2, [key]: value };
|
|
350
|
-
}, {});
|
|
351
|
-
}
|
|
352
|
-
var imageMimeTypeSignatures = [
|
|
353
|
-
{
|
|
354
|
-
mimeType: "image/gif",
|
|
355
|
-
bytesPrefix: [71, 73, 70],
|
|
356
|
-
base64Prefix: "R0lG"
|
|
357
|
-
},
|
|
358
|
-
{
|
|
359
|
-
mimeType: "image/png",
|
|
360
|
-
bytesPrefix: [137, 80, 78, 71],
|
|
361
|
-
base64Prefix: "iVBORw"
|
|
362
|
-
},
|
|
363
|
-
{
|
|
364
|
-
mimeType: "image/jpeg",
|
|
365
|
-
bytesPrefix: [255, 216],
|
|
366
|
-
base64Prefix: "/9j/"
|
|
367
|
-
},
|
|
368
|
-
{
|
|
369
|
-
mimeType: "image/webp",
|
|
370
|
-
bytesPrefix: [82, 73, 70, 70],
|
|
371
|
-
base64Prefix: "UklGRg"
|
|
372
|
-
},
|
|
373
|
-
{
|
|
374
|
-
mimeType: "image/bmp",
|
|
375
|
-
bytesPrefix: [66, 77],
|
|
376
|
-
base64Prefix: "Qk"
|
|
377
|
-
},
|
|
378
|
-
{
|
|
379
|
-
mimeType: "image/tiff",
|
|
380
|
-
bytesPrefix: [73, 73, 42, 0],
|
|
381
|
-
base64Prefix: "SUkqAA"
|
|
382
|
-
},
|
|
383
|
-
{
|
|
384
|
-
mimeType: "image/tiff",
|
|
385
|
-
bytesPrefix: [77, 77, 0, 42],
|
|
386
|
-
base64Prefix: "TU0AKg"
|
|
387
|
-
},
|
|
388
|
-
{
|
|
389
|
-
mimeType: "image/avif",
|
|
390
|
-
bytesPrefix: [
|
|
391
|
-
0,
|
|
392
|
-
0,
|
|
393
|
-
0,
|
|
394
|
-
32,
|
|
395
|
-
102,
|
|
396
|
-
116,
|
|
397
|
-
121,
|
|
398
|
-
112,
|
|
399
|
-
97,
|
|
400
|
-
118,
|
|
401
|
-
105,
|
|
402
|
-
102
|
|
403
|
-
],
|
|
404
|
-
base64Prefix: "AAAAIGZ0eXBhdmlm"
|
|
405
|
-
},
|
|
406
|
-
{
|
|
407
|
-
mimeType: "image/heic",
|
|
408
|
-
bytesPrefix: [
|
|
409
|
-
0,
|
|
410
|
-
0,
|
|
411
|
-
0,
|
|
412
|
-
32,
|
|
413
|
-
102,
|
|
414
|
-
116,
|
|
415
|
-
121,
|
|
416
|
-
112,
|
|
417
|
-
104,
|
|
418
|
-
101,
|
|
419
|
-
105,
|
|
420
|
-
99
|
|
421
|
-
],
|
|
422
|
-
base64Prefix: "AAAAIGZ0eXBoZWlj"
|
|
423
|
-
}
|
|
424
|
-
];
|
|
425
|
-
var stripID3 = (data) => {
|
|
426
|
-
const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
|
|
427
|
-
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
|
|
428
|
-
return bytes.slice(id3Size + 10);
|
|
429
|
-
};
|
|
430
|
-
function stripID3TagsIfPresent(data) {
|
|
431
|
-
const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I'
|
|
432
|
-
data[1] === 68 && // 'D'
|
|
433
|
-
data[2] === 51;
|
|
434
|
-
return hasId3 ? stripID3(data) : data;
|
|
435
|
-
}
|
|
436
|
-
function detectMimeType({
|
|
437
|
-
data,
|
|
438
|
-
signatures
|
|
439
|
-
}) {
|
|
440
|
-
const processedData = stripID3TagsIfPresent(data);
|
|
441
|
-
for (const signature of signatures) {
|
|
442
|
-
if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(
|
|
443
|
-
(byte, index) => processedData[index] === byte
|
|
444
|
-
)) {
|
|
445
|
-
return signature.mimeType;
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
return void 0;
|
|
449
|
-
}
|
|
450
|
-
var name4 = "AI_NoObjectGeneratedError";
|
|
451
|
-
var marker4 = `vercel.ai.error.${name4}`;
|
|
452
|
-
var symbol4 = Symbol.for(marker4);
|
|
453
|
-
var _a4;
|
|
454
|
-
var NoObjectGeneratedError = class extends AISDKError {
|
|
455
|
-
constructor({
|
|
456
|
-
message = "No object generated.",
|
|
457
|
-
cause,
|
|
458
|
-
text: text2,
|
|
459
|
-
response,
|
|
460
|
-
usage,
|
|
461
|
-
finishReason
|
|
462
|
-
}) {
|
|
463
|
-
super({ name: name4, message, cause });
|
|
464
|
-
this[_a4] = true;
|
|
465
|
-
this.text = text2;
|
|
466
|
-
this.response = response;
|
|
467
|
-
this.usage = usage;
|
|
468
|
-
this.finishReason = finishReason;
|
|
469
|
-
}
|
|
470
|
-
static isInstance(error) {
|
|
471
|
-
return AISDKError.hasMarker(error, marker4);
|
|
472
|
-
}
|
|
473
|
-
};
|
|
474
|
-
_a4 = symbol4;
|
|
475
|
-
var name5 = "AI_DownloadError";
|
|
476
|
-
var marker5 = `vercel.ai.error.${name5}`;
|
|
477
|
-
var symbol5 = Symbol.for(marker5);
|
|
478
|
-
var _a5;
|
|
479
|
-
var DownloadError = class extends AISDKError {
|
|
480
|
-
constructor({
|
|
481
|
-
url,
|
|
482
|
-
statusCode,
|
|
483
|
-
statusText,
|
|
484
|
-
cause,
|
|
485
|
-
message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
|
|
486
|
-
}) {
|
|
487
|
-
super({ name: name5, message, cause });
|
|
488
|
-
this[_a5] = true;
|
|
489
|
-
this.url = url;
|
|
490
|
-
this.statusCode = statusCode;
|
|
491
|
-
this.statusText = statusText;
|
|
492
|
-
}
|
|
493
|
-
static isInstance(error) {
|
|
494
|
-
return AISDKError.hasMarker(error, marker5);
|
|
495
|
-
}
|
|
496
|
-
};
|
|
497
|
-
_a5 = symbol5;
|
|
498
|
-
|
|
499
|
-
// util/download.ts
|
|
500
|
-
async function download({ url }) {
|
|
501
|
-
var _a17;
|
|
502
|
-
const urlText = url.toString();
|
|
503
|
-
try {
|
|
504
|
-
const response = await fetch(urlText);
|
|
505
|
-
if (!response.ok) {
|
|
506
|
-
throw new DownloadError({
|
|
507
|
-
url: urlText,
|
|
508
|
-
statusCode: response.status,
|
|
509
|
-
statusText: response.statusText
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
return {
|
|
513
|
-
data: new Uint8Array(await response.arrayBuffer()),
|
|
514
|
-
mimeType: (_a17 = response.headers.get("content-type")) != null ? _a17 : void 0
|
|
515
|
-
};
|
|
516
|
-
} catch (error) {
|
|
517
|
-
if (DownloadError.isInstance(error)) {
|
|
518
|
-
throw error;
|
|
519
|
-
}
|
|
520
|
-
throw new DownloadError({ url: urlText, cause: error });
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
var name6 = "AI_InvalidDataContentError";
|
|
524
|
-
var marker6 = `vercel.ai.error.${name6}`;
|
|
525
|
-
var symbol6 = Symbol.for(marker6);
|
|
526
|
-
var _a6;
|
|
527
|
-
var InvalidDataContentError = class extends AISDKError {
|
|
528
|
-
constructor({
|
|
529
|
-
content,
|
|
530
|
-
cause,
|
|
531
|
-
message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
|
|
532
|
-
}) {
|
|
533
|
-
super({ name: name6, message, cause });
|
|
534
|
-
this[_a6] = true;
|
|
535
|
-
this.content = content;
|
|
536
|
-
}
|
|
537
|
-
static isInstance(error) {
|
|
538
|
-
return AISDKError.hasMarker(error, marker6);
|
|
539
|
-
}
|
|
540
|
-
};
|
|
541
|
-
_a6 = symbol6;
|
|
542
|
-
var dataContentSchema = z.union([
|
|
543
|
-
z.string(),
|
|
544
|
-
z.instanceof(Uint8Array),
|
|
545
|
-
z.instanceof(ArrayBuffer),
|
|
546
|
-
z.custom(
|
|
547
|
-
// Buffer might not be available in some environments such as CloudFlare:
|
|
548
|
-
(value) => {
|
|
549
|
-
var _a17, _b;
|
|
550
|
-
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
|
551
|
-
},
|
|
552
|
-
{ message: "Must be a Buffer" }
|
|
553
|
-
)
|
|
554
|
-
]);
|
|
555
|
-
function convertDataContentToBase64String(content) {
|
|
556
|
-
if (typeof content === "string") {
|
|
557
|
-
return content;
|
|
558
|
-
}
|
|
559
|
-
if (content instanceof ArrayBuffer) {
|
|
560
|
-
return convertUint8ArrayToBase64(new Uint8Array(content));
|
|
561
|
-
}
|
|
562
|
-
return convertUint8ArrayToBase64(content);
|
|
563
|
-
}
|
|
564
|
-
function convertDataContentToUint8Array(content) {
|
|
565
|
-
if (content instanceof Uint8Array) {
|
|
566
|
-
return content;
|
|
567
|
-
}
|
|
568
|
-
if (typeof content === "string") {
|
|
569
|
-
try {
|
|
570
|
-
return convertBase64ToUint8Array(content);
|
|
571
|
-
} catch (error) {
|
|
572
|
-
throw new InvalidDataContentError({
|
|
573
|
-
message: "Invalid data content. Content string is not a base64-encoded media.",
|
|
574
|
-
content,
|
|
575
|
-
cause: error
|
|
576
|
-
});
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
if (content instanceof ArrayBuffer) {
|
|
580
|
-
return new Uint8Array(content);
|
|
581
|
-
}
|
|
582
|
-
throw new InvalidDataContentError({ content });
|
|
583
|
-
}
|
|
584
|
-
function convertUint8ArrayToText(uint8Array) {
|
|
585
|
-
try {
|
|
586
|
-
return new TextDecoder().decode(uint8Array);
|
|
587
|
-
} catch (error) {
|
|
588
|
-
throw new Error("Error decoding Uint8Array to text");
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
var name7 = "AI_InvalidMessageRoleError";
|
|
592
|
-
var marker7 = `vercel.ai.error.${name7}`;
|
|
593
|
-
var symbol7 = Symbol.for(marker7);
|
|
594
|
-
var _a7;
|
|
595
|
-
var InvalidMessageRoleError = class extends AISDKError {
|
|
596
|
-
constructor({
|
|
597
|
-
role,
|
|
598
|
-
message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
|
|
599
|
-
}) {
|
|
600
|
-
super({ name: name7, message });
|
|
601
|
-
this[_a7] = true;
|
|
602
|
-
this.role = role;
|
|
603
|
-
}
|
|
604
|
-
static isInstance(error) {
|
|
605
|
-
return AISDKError.hasMarker(error, marker7);
|
|
606
|
-
}
|
|
607
|
-
};
|
|
608
|
-
_a7 = symbol7;
|
|
609
|
-
|
|
610
|
-
// core/prompt/split-data-url.ts
|
|
611
|
-
function splitDataUrl(dataUrl) {
|
|
612
|
-
try {
|
|
613
|
-
const [header, base64Content] = dataUrl.split(",");
|
|
614
|
-
return {
|
|
615
|
-
mimeType: header.split(";")[0].split(":")[1],
|
|
616
|
-
base64Content
|
|
617
|
-
};
|
|
618
|
-
} catch (error) {
|
|
619
|
-
return {
|
|
620
|
-
mimeType: void 0,
|
|
621
|
-
base64Content: void 0
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// core/prompt/convert-to-language-model-prompt.ts
|
|
627
|
-
async function convertToLanguageModelPrompt({
|
|
628
|
-
prompt,
|
|
629
|
-
modelSupportsImageUrls = true,
|
|
630
|
-
modelSupportsUrl = () => false,
|
|
631
|
-
downloadImplementation = download
|
|
632
|
-
}) {
|
|
633
|
-
const downloadedAssets = await downloadAssets(
|
|
634
|
-
prompt.messages,
|
|
635
|
-
downloadImplementation,
|
|
636
|
-
modelSupportsImageUrls,
|
|
637
|
-
modelSupportsUrl
|
|
638
|
-
);
|
|
639
|
-
return [
|
|
640
|
-
...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
|
|
641
|
-
...prompt.messages.map(
|
|
642
|
-
(message) => convertToLanguageModelMessage(message, downloadedAssets)
|
|
643
|
-
)
|
|
644
|
-
];
|
|
645
|
-
}
|
|
646
|
-
function convertToLanguageModelMessage(message, downloadedAssets) {
|
|
647
|
-
var _a17, _b, _c, _d, _e, _f;
|
|
648
|
-
const role = message.role;
|
|
649
|
-
switch (role) {
|
|
650
|
-
case "system": {
|
|
651
|
-
return {
|
|
652
|
-
role: "system",
|
|
653
|
-
content: message.content,
|
|
654
|
-
providerMetadata: (_a17 = message.providerOptions) != null ? _a17 : message.experimental_providerMetadata
|
|
655
|
-
};
|
|
656
|
-
}
|
|
657
|
-
case "user": {
|
|
658
|
-
if (typeof message.content === "string") {
|
|
659
|
-
return {
|
|
660
|
-
role: "user",
|
|
661
|
-
content: [{ type: "text", text: message.content }],
|
|
662
|
-
providerMetadata: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
|
|
663
|
-
};
|
|
664
|
-
}
|
|
665
|
-
return {
|
|
666
|
-
role: "user",
|
|
667
|
-
content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
|
|
668
|
-
providerMetadata: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
case "assistant": {
|
|
672
|
-
if (typeof message.content === "string") {
|
|
673
|
-
return {
|
|
674
|
-
role: "assistant",
|
|
675
|
-
content: [{ type: "text", text: message.content }],
|
|
676
|
-
providerMetadata: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
return {
|
|
680
|
-
role: "assistant",
|
|
681
|
-
content: message.content.filter(
|
|
682
|
-
// remove empty text parts:
|
|
683
|
-
(part) => part.type !== "text" || part.text !== ""
|
|
684
|
-
).map((part) => {
|
|
685
|
-
var _a18;
|
|
686
|
-
const providerOptions = (_a18 = part.providerOptions) != null ? _a18 : part.experimental_providerMetadata;
|
|
687
|
-
switch (part.type) {
|
|
688
|
-
case "file": {
|
|
689
|
-
return {
|
|
690
|
-
type: "file",
|
|
691
|
-
data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
|
|
692
|
-
filename: part.filename,
|
|
693
|
-
mimeType: part.mimeType,
|
|
694
|
-
providerMetadata: providerOptions
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
case "reasoning": {
|
|
698
|
-
return {
|
|
699
|
-
type: "reasoning",
|
|
700
|
-
text: part.text,
|
|
701
|
-
signature: part.signature,
|
|
702
|
-
providerMetadata: providerOptions
|
|
703
|
-
};
|
|
704
|
-
}
|
|
705
|
-
case "redacted-reasoning": {
|
|
706
|
-
return {
|
|
707
|
-
type: "redacted-reasoning",
|
|
708
|
-
data: part.data,
|
|
709
|
-
providerMetadata: providerOptions
|
|
710
|
-
};
|
|
711
|
-
}
|
|
712
|
-
case "text": {
|
|
713
|
-
return {
|
|
714
|
-
type: "text",
|
|
715
|
-
text: part.text,
|
|
716
|
-
providerMetadata: providerOptions
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
case "tool-call": {
|
|
720
|
-
return {
|
|
721
|
-
type: "tool-call",
|
|
722
|
-
toolCallId: part.toolCallId,
|
|
723
|
-
toolName: part.toolName,
|
|
724
|
-
args: part.args,
|
|
725
|
-
providerMetadata: providerOptions
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
}),
|
|
730
|
-
providerMetadata: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
case "tool": {
|
|
734
|
-
return {
|
|
735
|
-
role: "tool",
|
|
736
|
-
content: message.content.map((part) => {
|
|
737
|
-
var _a18;
|
|
738
|
-
return {
|
|
739
|
-
type: "tool-result",
|
|
740
|
-
toolCallId: part.toolCallId,
|
|
741
|
-
toolName: part.toolName,
|
|
742
|
-
result: part.result,
|
|
743
|
-
content: part.experimental_content,
|
|
744
|
-
isError: part.isError,
|
|
745
|
-
providerMetadata: (_a18 = part.providerOptions) != null ? _a18 : part.experimental_providerMetadata
|
|
746
|
-
};
|
|
747
|
-
}),
|
|
748
|
-
providerMetadata: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
|
|
749
|
-
};
|
|
750
|
-
}
|
|
751
|
-
default: {
|
|
752
|
-
const _exhaustiveCheck = role;
|
|
753
|
-
throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
|
|
758
|
-
const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
|
|
759
|
-
(content) => Array.isArray(content)
|
|
760
|
-
).flat().filter(
|
|
761
|
-
(part) => part.type === "image" || part.type === "file"
|
|
762
|
-
).filter(
|
|
763
|
-
(part) => !(part.type === "image" && modelSupportsImageUrls === true)
|
|
764
|
-
).map((part) => part.type === "image" ? part.image : part.data).map(
|
|
765
|
-
(part) => (
|
|
766
|
-
// support string urls:
|
|
767
|
-
typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
|
|
768
|
-
)
|
|
769
|
-
).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
|
|
770
|
-
const downloadedImages = await Promise.all(
|
|
771
|
-
urls.map(async (url) => ({
|
|
772
|
-
url,
|
|
773
|
-
data: await downloadImplementation({ url })
|
|
774
|
-
}))
|
|
775
|
-
);
|
|
776
|
-
return Object.fromEntries(
|
|
777
|
-
downloadedImages.map(({ url, data }) => [url.toString(), data])
|
|
778
|
-
);
|
|
779
|
-
}
|
|
780
|
-
function convertPartToLanguageModelPart(part, downloadedAssets) {
|
|
781
|
-
var _a17, _b, _c, _d;
|
|
782
|
-
if (part.type === "text") {
|
|
783
|
-
return {
|
|
784
|
-
type: "text",
|
|
785
|
-
text: part.text,
|
|
786
|
-
providerMetadata: (_a17 = part.providerOptions) != null ? _a17 : part.experimental_providerMetadata
|
|
787
|
-
};
|
|
788
|
-
}
|
|
789
|
-
let mimeType = part.mimeType;
|
|
790
|
-
let data;
|
|
791
|
-
let content;
|
|
792
|
-
let normalizedData;
|
|
793
|
-
const type = part.type;
|
|
794
|
-
switch (type) {
|
|
795
|
-
case "image":
|
|
796
|
-
data = part.image;
|
|
797
|
-
break;
|
|
798
|
-
case "file":
|
|
799
|
-
data = part.data;
|
|
800
|
-
break;
|
|
801
|
-
default:
|
|
802
|
-
throw new Error(`Unsupported part type: ${type}`);
|
|
803
|
-
}
|
|
804
|
-
try {
|
|
805
|
-
content = typeof data === "string" ? new URL(data) : data;
|
|
806
|
-
} catch (error) {
|
|
807
|
-
content = data;
|
|
808
|
-
}
|
|
809
|
-
if (content instanceof URL) {
|
|
810
|
-
if (content.protocol === "data:") {
|
|
811
|
-
const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(
|
|
812
|
-
content.toString()
|
|
813
|
-
);
|
|
814
|
-
if (dataUrlMimeType == null || base64Content == null) {
|
|
815
|
-
throw new Error(`Invalid data URL format in part ${type}`);
|
|
816
|
-
}
|
|
817
|
-
mimeType = dataUrlMimeType;
|
|
818
|
-
normalizedData = convertDataContentToUint8Array(base64Content);
|
|
819
|
-
} else {
|
|
820
|
-
const downloadedFile = downloadedAssets[content.toString()];
|
|
821
|
-
if (downloadedFile) {
|
|
822
|
-
normalizedData = downloadedFile.data;
|
|
823
|
-
mimeType != null ? mimeType : mimeType = downloadedFile.mimeType;
|
|
824
|
-
} else {
|
|
825
|
-
normalizedData = content;
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
} else {
|
|
829
|
-
normalizedData = convertDataContentToUint8Array(content);
|
|
830
|
-
}
|
|
831
|
-
switch (type) {
|
|
832
|
-
case "image": {
|
|
833
|
-
if (normalizedData instanceof Uint8Array) {
|
|
834
|
-
mimeType = (_b = detectMimeType({
|
|
835
|
-
data: normalizedData,
|
|
836
|
-
signatures: imageMimeTypeSignatures
|
|
837
|
-
})) != null ? _b : mimeType;
|
|
838
|
-
}
|
|
839
|
-
return {
|
|
840
|
-
type: "image",
|
|
841
|
-
image: normalizedData,
|
|
842
|
-
mimeType,
|
|
843
|
-
providerMetadata: (_c = part.providerOptions) != null ? _c : part.experimental_providerMetadata
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
case "file": {
|
|
847
|
-
if (mimeType == null) {
|
|
848
|
-
throw new Error(`Mime type is missing for file part`);
|
|
849
|
-
}
|
|
850
|
-
return {
|
|
851
|
-
type: "file",
|
|
852
|
-
data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
|
|
853
|
-
filename: part.filename,
|
|
854
|
-
mimeType,
|
|
855
|
-
providerMetadata: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
|
|
856
|
-
};
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
// core/prompt/prepare-call-settings.ts
|
|
862
|
-
function prepareCallSettings({
|
|
863
|
-
maxTokens,
|
|
864
|
-
temperature,
|
|
865
|
-
topP,
|
|
866
|
-
topK,
|
|
867
|
-
presencePenalty,
|
|
868
|
-
frequencyPenalty,
|
|
869
|
-
stopSequences,
|
|
870
|
-
seed
|
|
871
|
-
}) {
|
|
872
|
-
if (maxTokens != null) {
|
|
873
|
-
if (!Number.isInteger(maxTokens)) {
|
|
874
|
-
throw new InvalidArgumentError({
|
|
875
|
-
parameter: "maxTokens",
|
|
876
|
-
value: maxTokens,
|
|
877
|
-
message: "maxTokens must be an integer"
|
|
878
|
-
});
|
|
879
|
-
}
|
|
880
|
-
if (maxTokens < 1) {
|
|
881
|
-
throw new InvalidArgumentError({
|
|
882
|
-
parameter: "maxTokens",
|
|
883
|
-
value: maxTokens,
|
|
884
|
-
message: "maxTokens must be >= 1"
|
|
885
|
-
});
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
if (temperature != null) {
|
|
889
|
-
if (typeof temperature !== "number") {
|
|
890
|
-
throw new InvalidArgumentError({
|
|
891
|
-
parameter: "temperature",
|
|
892
|
-
value: temperature,
|
|
893
|
-
message: "temperature must be a number"
|
|
894
|
-
});
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
if (topP != null) {
|
|
898
|
-
if (typeof topP !== "number") {
|
|
899
|
-
throw new InvalidArgumentError({
|
|
900
|
-
parameter: "topP",
|
|
901
|
-
value: topP,
|
|
902
|
-
message: "topP must be a number"
|
|
903
|
-
});
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
if (topK != null) {
|
|
907
|
-
if (typeof topK !== "number") {
|
|
908
|
-
throw new InvalidArgumentError({
|
|
909
|
-
parameter: "topK",
|
|
910
|
-
value: topK,
|
|
911
|
-
message: "topK must be a number"
|
|
912
|
-
});
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
if (presencePenalty != null) {
|
|
916
|
-
if (typeof presencePenalty !== "number") {
|
|
917
|
-
throw new InvalidArgumentError({
|
|
918
|
-
parameter: "presencePenalty",
|
|
919
|
-
value: presencePenalty,
|
|
920
|
-
message: "presencePenalty must be a number"
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
if (frequencyPenalty != null) {
|
|
925
|
-
if (typeof frequencyPenalty !== "number") {
|
|
926
|
-
throw new InvalidArgumentError({
|
|
927
|
-
parameter: "frequencyPenalty",
|
|
928
|
-
value: frequencyPenalty,
|
|
929
|
-
message: "frequencyPenalty must be a number"
|
|
930
|
-
});
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
if (seed != null) {
|
|
934
|
-
if (!Number.isInteger(seed)) {
|
|
935
|
-
throw new InvalidArgumentError({
|
|
936
|
-
parameter: "seed",
|
|
937
|
-
value: seed,
|
|
938
|
-
message: "seed must be an integer"
|
|
939
|
-
});
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
return {
|
|
943
|
-
maxTokens,
|
|
944
|
-
// TODO v5 remove default 0 for temperature
|
|
945
|
-
temperature: temperature != null ? temperature : 0,
|
|
946
|
-
topP,
|
|
947
|
-
topK,
|
|
948
|
-
presencePenalty,
|
|
949
|
-
frequencyPenalty,
|
|
950
|
-
stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
|
|
951
|
-
seed
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
// core/prompt/attachments-to-parts.ts
|
|
956
|
-
function attachmentsToParts(attachments) {
|
|
957
|
-
var _a17, _b, _c;
|
|
958
|
-
const parts = [];
|
|
959
|
-
for (const attachment of attachments) {
|
|
960
|
-
let url;
|
|
961
|
-
try {
|
|
962
|
-
url = new URL(attachment.url);
|
|
963
|
-
} catch (error) {
|
|
964
|
-
throw new Error(`Invalid URL: ${attachment.url}`);
|
|
965
|
-
}
|
|
966
|
-
switch (url.protocol) {
|
|
967
|
-
case "http:":
|
|
968
|
-
case "https:": {
|
|
969
|
-
if ((_a17 = attachment.contentType) == null ? void 0 : _a17.startsWith("image/")) {
|
|
970
|
-
parts.push({ type: "image", image: url });
|
|
971
|
-
} else {
|
|
972
|
-
if (!attachment.contentType) {
|
|
973
|
-
throw new Error(
|
|
974
|
-
"If the attachment is not an image, it must specify a content type"
|
|
975
|
-
);
|
|
976
|
-
}
|
|
977
|
-
parts.push({
|
|
978
|
-
type: "file",
|
|
979
|
-
data: url,
|
|
980
|
-
mimeType: attachment.contentType
|
|
981
|
-
});
|
|
982
|
-
}
|
|
983
|
-
break;
|
|
984
|
-
}
|
|
985
|
-
case "data:": {
|
|
986
|
-
let header;
|
|
987
|
-
let base64Content;
|
|
988
|
-
let mimeType;
|
|
989
|
-
try {
|
|
990
|
-
[header, base64Content] = attachment.url.split(",");
|
|
991
|
-
mimeType = header.split(";")[0].split(":")[1];
|
|
992
|
-
} catch (error) {
|
|
993
|
-
throw new Error(`Error processing data URL: ${attachment.url}`);
|
|
994
|
-
}
|
|
995
|
-
if (mimeType == null || base64Content == null) {
|
|
996
|
-
throw new Error(`Invalid data URL format: ${attachment.url}`);
|
|
997
|
-
}
|
|
998
|
-
if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
|
|
999
|
-
parts.push({
|
|
1000
|
-
type: "image",
|
|
1001
|
-
image: convertDataContentToUint8Array(base64Content)
|
|
1002
|
-
});
|
|
1003
|
-
} else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
|
|
1004
|
-
parts.push({
|
|
1005
|
-
type: "text",
|
|
1006
|
-
text: convertUint8ArrayToText(
|
|
1007
|
-
convertDataContentToUint8Array(base64Content)
|
|
1008
|
-
)
|
|
1009
|
-
});
|
|
1010
|
-
} else {
|
|
1011
|
-
if (!attachment.contentType) {
|
|
1012
|
-
throw new Error(
|
|
1013
|
-
"If the attachment is not an image or text, it must specify a content type"
|
|
1014
|
-
);
|
|
1015
|
-
}
|
|
1016
|
-
parts.push({
|
|
1017
|
-
type: "file",
|
|
1018
|
-
data: base64Content,
|
|
1019
|
-
mimeType: attachment.contentType
|
|
1020
|
-
});
|
|
1021
|
-
}
|
|
1022
|
-
break;
|
|
1023
|
-
}
|
|
1024
|
-
default: {
|
|
1025
|
-
throw new Error(`Unsupported URL protocol: ${url.protocol}`);
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
return parts;
|
|
1030
|
-
}
|
|
1031
|
-
var name8 = "AI_MessageConversionError";
|
|
1032
|
-
var marker8 = `vercel.ai.error.${name8}`;
|
|
1033
|
-
var symbol8 = Symbol.for(marker8);
|
|
1034
|
-
var _a8;
|
|
1035
|
-
var MessageConversionError = class extends AISDKError {
|
|
1036
|
-
constructor({
|
|
1037
|
-
originalMessage,
|
|
1038
|
-
message
|
|
1039
|
-
}) {
|
|
1040
|
-
super({ name: name8, message });
|
|
1041
|
-
this[_a8] = true;
|
|
1042
|
-
this.originalMessage = originalMessage;
|
|
1043
|
-
}
|
|
1044
|
-
static isInstance(error) {
|
|
1045
|
-
return AISDKError.hasMarker(error, marker8);
|
|
1046
|
-
}
|
|
1047
|
-
};
|
|
1048
|
-
_a8 = symbol8;
|
|
1049
|
-
|
|
1050
|
-
// core/prompt/convert-to-core-messages.ts
|
|
1051
|
-
function convertToCoreMessages(messages, options) {
|
|
1052
|
-
var _a17, _b;
|
|
1053
|
-
const tools = (_a17 = options == null ? void 0 : options.tools) != null ? _a17 : {};
|
|
1054
|
-
const coreMessages = [];
|
|
1055
|
-
for (let i = 0; i < messages.length; i++) {
|
|
1056
|
-
const message = messages[i];
|
|
1057
|
-
const isLastMessage = i === messages.length - 1;
|
|
1058
|
-
const { role, content, experimental_attachments } = message;
|
|
1059
|
-
switch (role) {
|
|
1060
|
-
case "system": {
|
|
1061
|
-
coreMessages.push({
|
|
1062
|
-
role: "system",
|
|
1063
|
-
content
|
|
1064
|
-
});
|
|
1065
|
-
break;
|
|
1066
|
-
}
|
|
1067
|
-
case "user": {
|
|
1068
|
-
if (message.parts == null) {
|
|
1069
|
-
coreMessages.push({
|
|
1070
|
-
role: "user",
|
|
1071
|
-
content: experimental_attachments ? [
|
|
1072
|
-
{ type: "text", text: content },
|
|
1073
|
-
...attachmentsToParts(experimental_attachments)
|
|
1074
|
-
] : content
|
|
1075
|
-
});
|
|
1076
|
-
} else {
|
|
1077
|
-
const textParts = message.parts.filter((part) => part.type === "text").map((part) => ({
|
|
1078
|
-
type: "text",
|
|
1079
|
-
text: part.text
|
|
1080
|
-
}));
|
|
1081
|
-
coreMessages.push({
|
|
1082
|
-
role: "user",
|
|
1083
|
-
content: experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
break;
|
|
1087
|
-
}
|
|
1088
|
-
case "assistant": {
|
|
1089
|
-
if (message.parts != null) {
|
|
1090
|
-
let processBlock2 = function() {
|
|
1091
|
-
const content2 = [];
|
|
1092
|
-
for (const part of block) {
|
|
1093
|
-
switch (part.type) {
|
|
1094
|
-
case "file":
|
|
1095
|
-
case "text": {
|
|
1096
|
-
content2.push(part);
|
|
1097
|
-
break;
|
|
1098
|
-
}
|
|
1099
|
-
case "reasoning": {
|
|
1100
|
-
for (const detail of part.details) {
|
|
1101
|
-
switch (detail.type) {
|
|
1102
|
-
case "text":
|
|
1103
|
-
content2.push({
|
|
1104
|
-
type: "reasoning",
|
|
1105
|
-
text: detail.text,
|
|
1106
|
-
signature: detail.signature
|
|
1107
|
-
});
|
|
1108
|
-
break;
|
|
1109
|
-
case "redacted":
|
|
1110
|
-
content2.push({
|
|
1111
|
-
type: "redacted-reasoning",
|
|
1112
|
-
data: detail.data
|
|
1113
|
-
});
|
|
1114
|
-
break;
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
break;
|
|
1118
|
-
}
|
|
1119
|
-
case "tool-invocation":
|
|
1120
|
-
content2.push({
|
|
1121
|
-
type: "tool-call",
|
|
1122
|
-
toolCallId: part.toolInvocation.toolCallId,
|
|
1123
|
-
toolName: part.toolInvocation.toolName,
|
|
1124
|
-
args: part.toolInvocation.args
|
|
1125
|
-
});
|
|
1126
|
-
break;
|
|
1127
|
-
default: {
|
|
1128
|
-
const _exhaustiveCheck = part;
|
|
1129
|
-
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
coreMessages.push({
|
|
1134
|
-
role: "assistant",
|
|
1135
|
-
content: content2
|
|
1136
|
-
});
|
|
1137
|
-
const stepInvocations = block.filter(
|
|
1138
|
-
(part) => part.type === "tool-invocation"
|
|
1139
|
-
).map((part) => part.toolInvocation);
|
|
1140
|
-
if (stepInvocations.length > 0) {
|
|
1141
|
-
coreMessages.push({
|
|
1142
|
-
role: "tool",
|
|
1143
|
-
content: stepInvocations.map(
|
|
1144
|
-
(toolInvocation) => {
|
|
1145
|
-
if (!("result" in toolInvocation)) {
|
|
1146
|
-
throw new MessageConversionError({
|
|
1147
|
-
originalMessage: message,
|
|
1148
|
-
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
|
|
1149
|
-
});
|
|
1150
|
-
}
|
|
1151
|
-
const { toolCallId, toolName, result } = toolInvocation;
|
|
1152
|
-
const tool2 = tools[toolName];
|
|
1153
|
-
return (tool2 == null ? void 0 : tool2.experimental_toToolResultContent) != null ? {
|
|
1154
|
-
type: "tool-result",
|
|
1155
|
-
toolCallId,
|
|
1156
|
-
toolName,
|
|
1157
|
-
result: tool2.experimental_toToolResultContent(result),
|
|
1158
|
-
experimental_content: tool2.experimental_toToolResultContent(result)
|
|
1159
|
-
} : {
|
|
1160
|
-
type: "tool-result",
|
|
1161
|
-
toolCallId,
|
|
1162
|
-
toolName,
|
|
1163
|
-
result
|
|
1164
|
-
};
|
|
1165
|
-
}
|
|
1166
|
-
)
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
1169
|
-
block = [];
|
|
1170
|
-
blockHasToolInvocations = false;
|
|
1171
|
-
currentStep++;
|
|
1172
|
-
};
|
|
1173
|
-
let currentStep = 0;
|
|
1174
|
-
let blockHasToolInvocations = false;
|
|
1175
|
-
let block = [];
|
|
1176
|
-
for (const part of message.parts) {
|
|
1177
|
-
switch (part.type) {
|
|
1178
|
-
case "text": {
|
|
1179
|
-
if (blockHasToolInvocations) {
|
|
1180
|
-
processBlock2();
|
|
1181
|
-
}
|
|
1182
|
-
block.push(part);
|
|
1183
|
-
break;
|
|
1184
|
-
}
|
|
1185
|
-
case "file":
|
|
1186
|
-
case "reasoning": {
|
|
1187
|
-
block.push(part);
|
|
1188
|
-
break;
|
|
1189
|
-
}
|
|
1190
|
-
case "tool-invocation": {
|
|
1191
|
-
if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
|
|
1192
|
-
processBlock2();
|
|
1193
|
-
}
|
|
1194
|
-
block.push(part);
|
|
1195
|
-
blockHasToolInvocations = true;
|
|
1196
|
-
break;
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
processBlock2();
|
|
1201
|
-
break;
|
|
1202
|
-
}
|
|
1203
|
-
const toolInvocations = message.toolInvocations;
|
|
1204
|
-
if (toolInvocations == null || toolInvocations.length === 0) {
|
|
1205
|
-
coreMessages.push({ role: "assistant", content });
|
|
1206
|
-
break;
|
|
1207
|
-
}
|
|
1208
|
-
const maxStep = toolInvocations.reduce((max, toolInvocation) => {
|
|
1209
|
-
var _a18;
|
|
1210
|
-
return Math.max(max, (_a18 = toolInvocation.step) != null ? _a18 : 0);
|
|
1211
|
-
}, 0);
|
|
1212
|
-
for (let i2 = 0; i2 <= maxStep; i2++) {
|
|
1213
|
-
const stepInvocations = toolInvocations.filter(
|
|
1214
|
-
(toolInvocation) => {
|
|
1215
|
-
var _a18;
|
|
1216
|
-
return ((_a18 = toolInvocation.step) != null ? _a18 : 0) === i2;
|
|
1217
|
-
}
|
|
1218
|
-
);
|
|
1219
|
-
if (stepInvocations.length === 0) {
|
|
1220
|
-
continue;
|
|
1221
|
-
}
|
|
1222
|
-
coreMessages.push({
|
|
1223
|
-
role: "assistant",
|
|
1224
|
-
content: [
|
|
1225
|
-
...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
|
|
1226
|
-
...stepInvocations.map(
|
|
1227
|
-
({ toolCallId, toolName, args }) => ({
|
|
1228
|
-
type: "tool-call",
|
|
1229
|
-
toolCallId,
|
|
1230
|
-
toolName,
|
|
1231
|
-
args
|
|
1232
|
-
})
|
|
1233
|
-
)
|
|
1234
|
-
]
|
|
1235
|
-
});
|
|
1236
|
-
coreMessages.push({
|
|
1237
|
-
role: "tool",
|
|
1238
|
-
content: stepInvocations.map((toolInvocation) => {
|
|
1239
|
-
if (!("result" in toolInvocation)) {
|
|
1240
|
-
throw new MessageConversionError({
|
|
1241
|
-
originalMessage: message,
|
|
1242
|
-
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
|
|
1243
|
-
});
|
|
1244
|
-
}
|
|
1245
|
-
const { toolCallId, toolName, result } = toolInvocation;
|
|
1246
|
-
const tool2 = tools[toolName];
|
|
1247
|
-
return (tool2 == null ? void 0 : tool2.experimental_toToolResultContent) != null ? {
|
|
1248
|
-
type: "tool-result",
|
|
1249
|
-
toolCallId,
|
|
1250
|
-
toolName,
|
|
1251
|
-
result: tool2.experimental_toToolResultContent(result),
|
|
1252
|
-
experimental_content: tool2.experimental_toToolResultContent(result)
|
|
1253
|
-
} : {
|
|
1254
|
-
type: "tool-result",
|
|
1255
|
-
toolCallId,
|
|
1256
|
-
toolName,
|
|
1257
|
-
result
|
|
1258
|
-
};
|
|
1259
|
-
})
|
|
1260
|
-
});
|
|
1261
|
-
}
|
|
1262
|
-
if (content && !isLastMessage) {
|
|
1263
|
-
coreMessages.push({ role: "assistant", content });
|
|
1264
|
-
}
|
|
1265
|
-
break;
|
|
1266
|
-
}
|
|
1267
|
-
case "data": {
|
|
1268
|
-
break;
|
|
1269
|
-
}
|
|
1270
|
-
default: {
|
|
1271
|
-
const _exhaustiveCheck = role;
|
|
1272
|
-
throw new MessageConversionError({
|
|
1273
|
-
originalMessage: message,
|
|
1274
|
-
message: `Unsupported role: ${_exhaustiveCheck}`
|
|
1275
|
-
});
|
|
1276
|
-
}
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
return coreMessages;
|
|
1280
|
-
}
|
|
1281
|
-
var jsonValueSchema = z.lazy(
|
|
1282
|
-
() => z.union([
|
|
1283
|
-
z.null(),
|
|
1284
|
-
z.string(),
|
|
1285
|
-
z.number(),
|
|
1286
|
-
z.boolean(),
|
|
1287
|
-
z.record(z.string(), jsonValueSchema),
|
|
1288
|
-
z.array(jsonValueSchema)
|
|
1289
|
-
])
|
|
1290
|
-
);
|
|
1291
|
-
|
|
1292
|
-
// core/types/provider-metadata.ts
|
|
1293
|
-
var providerMetadataSchema = z.record(
|
|
1294
|
-
z.string(),
|
|
1295
|
-
z.record(z.string(), jsonValueSchema)
|
|
1296
|
-
);
|
|
1297
|
-
var toolResultContentSchema = z.array(
|
|
1298
|
-
z.union([
|
|
1299
|
-
z.object({ type: z.literal("text"), text: z.string() }),
|
|
1300
|
-
z.object({
|
|
1301
|
-
type: z.literal("image"),
|
|
1302
|
-
data: z.string(),
|
|
1303
|
-
mimeType: z.string().optional()
|
|
1304
|
-
})
|
|
1305
|
-
])
|
|
1306
|
-
);
|
|
1307
|
-
|
|
1308
|
-
// core/prompt/content-part.ts
|
|
1309
|
-
var textPartSchema = z.object({
|
|
1310
|
-
type: z.literal("text"),
|
|
1311
|
-
text: z.string(),
|
|
1312
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1313
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1314
|
-
});
|
|
1315
|
-
var imagePartSchema = z.object({
|
|
1316
|
-
type: z.literal("image"),
|
|
1317
|
-
image: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1318
|
-
mimeType: z.string().optional(),
|
|
1319
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1320
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1321
|
-
});
|
|
1322
|
-
var filePartSchema = z.object({
|
|
1323
|
-
type: z.literal("file"),
|
|
1324
|
-
data: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1325
|
-
filename: z.string().optional(),
|
|
1326
|
-
mimeType: z.string(),
|
|
1327
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1328
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1329
|
-
});
|
|
1330
|
-
var reasoningPartSchema = z.object({
|
|
1331
|
-
type: z.literal("reasoning"),
|
|
1332
|
-
text: z.string(),
|
|
1333
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1334
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1335
|
-
});
|
|
1336
|
-
var redactedReasoningPartSchema = z.object({
|
|
1337
|
-
type: z.literal("redacted-reasoning"),
|
|
1338
|
-
data: z.string(),
|
|
1339
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1340
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1341
|
-
});
|
|
1342
|
-
var toolCallPartSchema = z.object({
|
|
1343
|
-
type: z.literal("tool-call"),
|
|
1344
|
-
toolCallId: z.string(),
|
|
1345
|
-
toolName: z.string(),
|
|
1346
|
-
args: z.unknown(),
|
|
1347
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1348
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1349
|
-
});
|
|
1350
|
-
var toolResultPartSchema = z.object({
|
|
1351
|
-
type: z.literal("tool-result"),
|
|
1352
|
-
toolCallId: z.string(),
|
|
1353
|
-
toolName: z.string(),
|
|
1354
|
-
result: z.unknown(),
|
|
1355
|
-
content: toolResultContentSchema.optional(),
|
|
1356
|
-
isError: z.boolean().optional(),
|
|
1357
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1358
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1359
|
-
});
|
|
1360
|
-
|
|
1361
|
-
// core/prompt/message.ts
|
|
1362
|
-
var coreSystemMessageSchema = z.object({
|
|
1363
|
-
role: z.literal("system"),
|
|
1364
|
-
content: z.string(),
|
|
1365
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1366
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1367
|
-
});
|
|
1368
|
-
var coreUserMessageSchema = z.object({
|
|
1369
|
-
role: z.literal("user"),
|
|
1370
|
-
content: z.union([
|
|
1371
|
-
z.string(),
|
|
1372
|
-
z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
|
|
1373
|
-
]),
|
|
1374
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1375
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1376
|
-
});
|
|
1377
|
-
var coreAssistantMessageSchema = z.object({
|
|
1378
|
-
role: z.literal("assistant"),
|
|
1379
|
-
content: z.union([
|
|
1380
|
-
z.string(),
|
|
1381
|
-
z.array(
|
|
1382
|
-
z.union([
|
|
1383
|
-
textPartSchema,
|
|
1384
|
-
filePartSchema,
|
|
1385
|
-
reasoningPartSchema,
|
|
1386
|
-
redactedReasoningPartSchema,
|
|
1387
|
-
toolCallPartSchema
|
|
1388
|
-
])
|
|
1389
|
-
)
|
|
1390
|
-
]),
|
|
1391
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1392
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1393
|
-
});
|
|
1394
|
-
var coreToolMessageSchema = z.object({
|
|
1395
|
-
role: z.literal("tool"),
|
|
1396
|
-
content: z.array(toolResultPartSchema),
|
|
1397
|
-
providerOptions: providerMetadataSchema.optional(),
|
|
1398
|
-
experimental_providerMetadata: providerMetadataSchema.optional()
|
|
1399
|
-
});
|
|
1400
|
-
var coreMessageSchema = z.union([
|
|
1401
|
-
coreSystemMessageSchema,
|
|
1402
|
-
coreUserMessageSchema,
|
|
1403
|
-
coreAssistantMessageSchema,
|
|
1404
|
-
coreToolMessageSchema
|
|
1405
|
-
]);
|
|
1406
|
-
|
|
1407
|
-
// core/prompt/standardize-prompt.ts
|
|
1408
|
-
function standardizePrompt({
|
|
1409
|
-
prompt,
|
|
1410
|
-
tools
|
|
1411
|
-
}) {
|
|
1412
|
-
if (prompt.prompt == null && prompt.messages == null) {
|
|
1413
|
-
throw new InvalidPromptError({
|
|
1414
|
-
prompt,
|
|
1415
|
-
message: "prompt or messages must be defined"
|
|
1416
|
-
});
|
|
1417
|
-
}
|
|
1418
|
-
if (prompt.prompt != null && prompt.messages != null) {
|
|
1419
|
-
throw new InvalidPromptError({
|
|
1420
|
-
prompt,
|
|
1421
|
-
message: "prompt and messages cannot be defined at the same time"
|
|
1422
|
-
});
|
|
1423
|
-
}
|
|
1424
|
-
if (prompt.system != null && typeof prompt.system !== "string") {
|
|
1425
|
-
throw new InvalidPromptError({
|
|
1426
|
-
prompt,
|
|
1427
|
-
message: "system must be a string"
|
|
1428
|
-
});
|
|
1429
|
-
}
|
|
1430
|
-
if (prompt.prompt != null) {
|
|
1431
|
-
if (typeof prompt.prompt !== "string") {
|
|
1432
|
-
throw new InvalidPromptError({
|
|
1433
|
-
prompt,
|
|
1434
|
-
message: "prompt must be a string"
|
|
1435
|
-
});
|
|
1436
|
-
}
|
|
1437
|
-
return {
|
|
1438
|
-
type: "prompt",
|
|
1439
|
-
system: prompt.system,
|
|
1440
|
-
messages: [
|
|
1441
|
-
{
|
|
1442
|
-
role: "user",
|
|
1443
|
-
content: prompt.prompt
|
|
1444
|
-
}
|
|
1445
|
-
]
|
|
1446
|
-
};
|
|
1447
|
-
}
|
|
1448
|
-
if (prompt.messages != null) {
|
|
1449
|
-
const promptType = detectPromptType(prompt.messages);
|
|
1450
|
-
const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
|
|
1451
|
-
tools
|
|
1452
|
-
}) : prompt.messages;
|
|
1453
|
-
if (messages.length === 0) {
|
|
1454
|
-
throw new InvalidPromptError({
|
|
1455
|
-
prompt,
|
|
1456
|
-
message: "messages must not be empty"
|
|
1457
|
-
});
|
|
1458
|
-
}
|
|
1459
|
-
const validationResult = safeValidateTypes({
|
|
1460
|
-
value: messages,
|
|
1461
|
-
schema: z.array(coreMessageSchema)
|
|
1462
|
-
});
|
|
1463
|
-
if (!validationResult.success) {
|
|
1464
|
-
throw new InvalidPromptError({
|
|
1465
|
-
prompt,
|
|
1466
|
-
message: [
|
|
1467
|
-
"message must be a CoreMessage or a UI message",
|
|
1468
|
-
`Validation error: ${validationResult.error.message}`
|
|
1469
|
-
].join("\n"),
|
|
1470
|
-
cause: validationResult.error
|
|
1471
|
-
});
|
|
1472
|
-
}
|
|
1473
|
-
return {
|
|
1474
|
-
type: "messages",
|
|
1475
|
-
messages,
|
|
1476
|
-
system: prompt.system
|
|
1477
|
-
};
|
|
1478
|
-
}
|
|
1479
|
-
throw new Error("unreachable");
|
|
1480
|
-
}
|
|
1481
|
-
function detectPromptType(prompt) {
|
|
1482
|
-
if (!Array.isArray(prompt)) {
|
|
1483
|
-
throw new InvalidPromptError({
|
|
1484
|
-
prompt,
|
|
1485
|
-
message: [
|
|
1486
|
-
"messages must be an array of CoreMessage or UIMessage",
|
|
1487
|
-
`Received non-array value: ${JSON.stringify(prompt)}`
|
|
1488
|
-
].join("\n"),
|
|
1489
|
-
cause: prompt
|
|
1490
|
-
});
|
|
1491
|
-
}
|
|
1492
|
-
if (prompt.length === 0) {
|
|
1493
|
-
return "messages";
|
|
1494
|
-
}
|
|
1495
|
-
const characteristics = prompt.map(detectSingleMessageCharacteristics);
|
|
1496
|
-
if (characteristics.some((c) => c === "has-ui-specific-parts")) {
|
|
1497
|
-
return "ui-messages";
|
|
1498
|
-
}
|
|
1499
|
-
const nonMessageIndex = characteristics.findIndex(
|
|
1500
|
-
(c) => c !== "has-core-specific-parts" && c !== "message"
|
|
1501
|
-
);
|
|
1502
|
-
if (nonMessageIndex === -1) {
|
|
1503
|
-
return "messages";
|
|
1504
|
-
}
|
|
1505
|
-
throw new InvalidPromptError({
|
|
1506
|
-
prompt,
|
|
1507
|
-
message: [
|
|
1508
|
-
"messages must be an array of CoreMessage or UIMessage",
|
|
1509
|
-
`Received message of type: "${characteristics[nonMessageIndex]}" at index ${nonMessageIndex}`,
|
|
1510
|
-
`messages[${nonMessageIndex}]: ${JSON.stringify(prompt[nonMessageIndex])}`
|
|
1511
|
-
].join("\n"),
|
|
1512
|
-
cause: prompt
|
|
1513
|
-
});
|
|
1514
|
-
}
|
|
1515
|
-
function detectSingleMessageCharacteristics(message) {
|
|
1516
|
-
if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
|
|
1517
|
-
message.role === "data" || // UI-only role
|
|
1518
|
-
"toolInvocations" in message || // UI-specific field
|
|
1519
|
-
"parts" in message || // UI-specific field
|
|
1520
|
-
"experimental_attachments" in message)) {
|
|
1521
|
-
return "has-ui-specific-parts";
|
|
1522
|
-
} else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
|
|
1523
|
-
"experimental_providerMetadata" in message || "providerOptions" in message)) {
|
|
1524
|
-
return "has-core-specific-parts";
|
|
1525
|
-
} else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
|
|
1526
|
-
return "message";
|
|
1527
|
-
} else {
|
|
1528
|
-
return "other";
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
// core/types/usage.ts
|
|
1533
|
-
function calculateLanguageModelUsage({
|
|
1534
|
-
promptTokens,
|
|
1535
|
-
completionTokens
|
|
1536
|
-
}) {
|
|
1537
|
-
return {
|
|
1538
|
-
promptTokens,
|
|
1539
|
-
completionTokens,
|
|
1540
|
-
totalTokens: promptTokens + completionTokens
|
|
1541
|
-
};
|
|
1542
|
-
}
|
|
1543
|
-
|
|
1544
|
-
// core/generate-object/inject-json-instruction.ts
|
|
1545
|
-
var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
|
|
1546
|
-
var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
|
|
1547
|
-
var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
|
|
1548
|
-
function injectJsonInstruction({
|
|
1549
|
-
prompt,
|
|
1550
|
-
schema,
|
|
1551
|
-
schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
|
|
1552
|
-
schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
|
|
1553
|
-
}) {
|
|
1554
|
-
return [
|
|
1555
|
-
prompt != null && prompt.length > 0 ? prompt : void 0,
|
|
1556
|
-
prompt != null && prompt.length > 0 ? "" : void 0,
|
|
1557
|
-
// add a newline if prompt is not null
|
|
1558
|
-
schemaPrefix,
|
|
1559
|
-
schema != null ? JSON.stringify(schema) : void 0,
|
|
1560
|
-
schemaSuffix
|
|
1561
|
-
].filter((line) => line != null).join("\n");
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
// core/util/async-iterable-stream.ts
|
|
1565
|
-
function createAsyncIterableStream(source) {
|
|
1566
|
-
const stream = source.pipeThrough(new TransformStream());
|
|
1567
|
-
stream[Symbol.asyncIterator] = () => {
|
|
1568
|
-
const reader = stream.getReader();
|
|
1569
|
-
return {
|
|
1570
|
-
async next() {
|
|
1571
|
-
const { done, value } = await reader.read();
|
|
1572
|
-
return done ? { done: true, value: void 0 } : { done: false, value };
|
|
1573
|
-
}
|
|
1574
|
-
};
|
|
1575
|
-
};
|
|
1576
|
-
return stream;
|
|
1577
|
-
}
|
|
1578
|
-
|
|
1579
|
-
// core/generate-object/output-strategy.ts
|
|
1580
|
-
var noSchemaOutputStrategy = {
|
|
1581
|
-
type: "no-schema",
|
|
1582
|
-
jsonSchema: void 0,
|
|
1583
|
-
validatePartialResult({ value, textDelta }) {
|
|
1584
|
-
return { success: true, value: { partial: value, textDelta } };
|
|
1585
|
-
},
|
|
1586
|
-
validateFinalResult(value, context) {
|
|
1587
|
-
return value === void 0 ? {
|
|
1588
|
-
success: false,
|
|
1589
|
-
error: new NoObjectGeneratedError({
|
|
1590
|
-
message: "No object generated: response did not match schema.",
|
|
1591
|
-
text: context.text,
|
|
1592
|
-
response: context.response,
|
|
1593
|
-
usage: context.usage,
|
|
1594
|
-
finishReason: context.finishReason
|
|
1595
|
-
})
|
|
1596
|
-
} : { success: true, value };
|
|
1597
|
-
},
|
|
1598
|
-
createElementStream() {
|
|
1599
|
-
throw new UnsupportedFunctionalityError({
|
|
1600
|
-
functionality: "element streams in no-schema mode"
|
|
1601
|
-
});
|
|
1602
|
-
}
|
|
1603
|
-
};
|
|
1604
|
-
var objectOutputStrategy = (schema) => ({
|
|
1605
|
-
type: "object",
|
|
1606
|
-
jsonSchema: schema.jsonSchema,
|
|
1607
|
-
validatePartialResult({ value, textDelta }) {
|
|
1608
|
-
return {
|
|
1609
|
-
success: true,
|
|
1610
|
-
value: {
|
|
1611
|
-
// Note: currently no validation of partial results:
|
|
1612
|
-
partial: value,
|
|
1613
|
-
textDelta
|
|
1614
|
-
}
|
|
1615
|
-
};
|
|
1616
|
-
},
|
|
1617
|
-
validateFinalResult(value) {
|
|
1618
|
-
return safeValidateTypes({ value, schema });
|
|
1619
|
-
},
|
|
1620
|
-
createElementStream() {
|
|
1621
|
-
throw new UnsupportedFunctionalityError({
|
|
1622
|
-
functionality: "element streams in object mode"
|
|
1623
|
-
});
|
|
1624
|
-
}
|
|
1625
|
-
});
|
|
1626
|
-
var arrayOutputStrategy = (schema) => {
|
|
1627
|
-
const { $schema, ...itemSchema } = schema.jsonSchema;
|
|
1628
|
-
return {
|
|
1629
|
-
type: "enum",
|
|
1630
|
-
// wrap in object that contains array of elements, since most LLMs will not
|
|
1631
|
-
// be able to generate an array directly:
|
|
1632
|
-
// possible future optimization: use arrays directly when model supports grammar-guided generation
|
|
1633
|
-
jsonSchema: {
|
|
1634
|
-
$schema: "http://json-schema.org/draft-07/schema#",
|
|
1635
|
-
type: "object",
|
|
1636
|
-
properties: {
|
|
1637
|
-
elements: { type: "array", items: itemSchema }
|
|
1638
|
-
},
|
|
1639
|
-
required: ["elements"],
|
|
1640
|
-
additionalProperties: false
|
|
1641
|
-
},
|
|
1642
|
-
validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {
|
|
1643
|
-
var _a17;
|
|
1644
|
-
if (!isJSONObject(value) || !isJSONArray(value.elements)) {
|
|
1645
|
-
return {
|
|
1646
|
-
success: false,
|
|
1647
|
-
error: new TypeValidationError({
|
|
1648
|
-
value,
|
|
1649
|
-
cause: "value must be an object that contains an array of elements"
|
|
1650
|
-
})
|
|
1651
|
-
};
|
|
1652
|
-
}
|
|
1653
|
-
const inputArray = value.elements;
|
|
1654
|
-
const resultArray = [];
|
|
1655
|
-
for (let i = 0; i < inputArray.length; i++) {
|
|
1656
|
-
const element = inputArray[i];
|
|
1657
|
-
const result = safeValidateTypes({ value: element, schema });
|
|
1658
|
-
if (i === inputArray.length - 1 && !isFinalDelta) {
|
|
1659
|
-
continue;
|
|
1660
|
-
}
|
|
1661
|
-
if (!result.success) {
|
|
1662
|
-
return result;
|
|
1663
|
-
}
|
|
1664
|
-
resultArray.push(result.value);
|
|
1665
|
-
}
|
|
1666
|
-
const publishedElementCount = (_a17 = latestObject == null ? void 0 : latestObject.length) != null ? _a17 : 0;
|
|
1667
|
-
let textDelta = "";
|
|
1668
|
-
if (isFirstDelta) {
|
|
1669
|
-
textDelta += "[";
|
|
1670
|
-
}
|
|
1671
|
-
if (publishedElementCount > 0) {
|
|
1672
|
-
textDelta += ",";
|
|
1673
|
-
}
|
|
1674
|
-
textDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(",");
|
|
1675
|
-
if (isFinalDelta) {
|
|
1676
|
-
textDelta += "]";
|
|
1677
|
-
}
|
|
1678
|
-
return {
|
|
1679
|
-
success: true,
|
|
1680
|
-
value: {
|
|
1681
|
-
partial: resultArray,
|
|
1682
|
-
textDelta
|
|
1683
|
-
}
|
|
1684
|
-
};
|
|
1685
|
-
},
|
|
1686
|
-
validateFinalResult(value) {
|
|
1687
|
-
if (!isJSONObject(value) || !isJSONArray(value.elements)) {
|
|
1688
|
-
return {
|
|
1689
|
-
success: false,
|
|
1690
|
-
error: new TypeValidationError({
|
|
1691
|
-
value,
|
|
1692
|
-
cause: "value must be an object that contains an array of elements"
|
|
1693
|
-
})
|
|
1694
|
-
};
|
|
1695
|
-
}
|
|
1696
|
-
const inputArray = value.elements;
|
|
1697
|
-
for (const element of inputArray) {
|
|
1698
|
-
const result = safeValidateTypes({ value: element, schema });
|
|
1699
|
-
if (!result.success) {
|
|
1700
|
-
return result;
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
return { success: true, value: inputArray };
|
|
1704
|
-
},
|
|
1705
|
-
createElementStream(originalStream) {
|
|
1706
|
-
let publishedElements = 0;
|
|
1707
|
-
return createAsyncIterableStream(
|
|
1708
|
-
originalStream.pipeThrough(
|
|
1709
|
-
new TransformStream({
|
|
1710
|
-
transform(chunk, controller) {
|
|
1711
|
-
switch (chunk.type) {
|
|
1712
|
-
case "object": {
|
|
1713
|
-
const array = chunk.object;
|
|
1714
|
-
for (; publishedElements < array.length; publishedElements++) {
|
|
1715
|
-
controller.enqueue(array[publishedElements]);
|
|
1716
|
-
}
|
|
1717
|
-
break;
|
|
1718
|
-
}
|
|
1719
|
-
case "text-delta":
|
|
1720
|
-
case "finish":
|
|
1721
|
-
case "error":
|
|
1722
|
-
break;
|
|
1723
|
-
default: {
|
|
1724
|
-
const _exhaustiveCheck = chunk;
|
|
1725
|
-
throw new Error(
|
|
1726
|
-
`Unsupported chunk type: ${_exhaustiveCheck}`
|
|
1727
|
-
);
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
}
|
|
1731
|
-
})
|
|
1732
|
-
)
|
|
1733
|
-
);
|
|
1734
|
-
}
|
|
1735
|
-
};
|
|
1736
|
-
};
|
|
1737
|
-
var enumOutputStrategy = (enumValues) => {
|
|
1738
|
-
return {
|
|
1739
|
-
type: "enum",
|
|
1740
|
-
// wrap in object that contains result, since most LLMs will not
|
|
1741
|
-
// be able to generate an enum value directly:
|
|
1742
|
-
// possible future optimization: use enums directly when model supports top-level enums
|
|
1743
|
-
jsonSchema: {
|
|
1744
|
-
$schema: "http://json-schema.org/draft-07/schema#",
|
|
1745
|
-
type: "object",
|
|
1746
|
-
properties: {
|
|
1747
|
-
result: { type: "string", enum: enumValues }
|
|
1748
|
-
},
|
|
1749
|
-
required: ["result"],
|
|
1750
|
-
additionalProperties: false
|
|
1751
|
-
},
|
|
1752
|
-
validateFinalResult(value) {
|
|
1753
|
-
if (!isJSONObject(value) || typeof value.result !== "string") {
|
|
1754
|
-
return {
|
|
1755
|
-
success: false,
|
|
1756
|
-
error: new TypeValidationError({
|
|
1757
|
-
value,
|
|
1758
|
-
cause: 'value must be an object that contains a string in the "result" property.'
|
|
1759
|
-
})
|
|
1760
|
-
};
|
|
1761
|
-
}
|
|
1762
|
-
const result = value.result;
|
|
1763
|
-
return enumValues.includes(result) ? { success: true, value: result } : {
|
|
1764
|
-
success: false,
|
|
1765
|
-
error: new TypeValidationError({
|
|
1766
|
-
value,
|
|
1767
|
-
cause: "value must be a string in the enum"
|
|
1768
|
-
})
|
|
1769
|
-
};
|
|
1770
|
-
},
|
|
1771
|
-
validatePartialResult() {
|
|
1772
|
-
throw new UnsupportedFunctionalityError({
|
|
1773
|
-
functionality: "partial results in enum mode"
|
|
1774
|
-
});
|
|
1775
|
-
},
|
|
1776
|
-
createElementStream() {
|
|
1777
|
-
throw new UnsupportedFunctionalityError({
|
|
1778
|
-
functionality: "element streams in enum mode"
|
|
1779
|
-
});
|
|
1780
|
-
}
|
|
1781
|
-
};
|
|
1782
|
-
};
|
|
1783
|
-
function getOutputStrategy({
|
|
1784
|
-
output,
|
|
1785
|
-
schema,
|
|
1786
|
-
enumValues
|
|
1787
|
-
}) {
|
|
1788
|
-
switch (output) {
|
|
1789
|
-
case "object":
|
|
1790
|
-
return objectOutputStrategy(asSchema(schema));
|
|
1791
|
-
case "array":
|
|
1792
|
-
return arrayOutputStrategy(asSchema(schema));
|
|
1793
|
-
case "enum":
|
|
1794
|
-
return enumOutputStrategy(enumValues);
|
|
1795
|
-
case "no-schema":
|
|
1796
|
-
return noSchemaOutputStrategy;
|
|
1797
|
-
default: {
|
|
1798
|
-
const _exhaustiveCheck = output;
|
|
1799
|
-
throw new Error(`Unsupported output: ${_exhaustiveCheck}`);
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
|
|
1804
|
-
// core/generate-object/validate-object-generation-input.ts
|
|
1805
|
-
function validateObjectGenerationInput({
|
|
1806
|
-
output,
|
|
1807
|
-
mode,
|
|
1808
|
-
schema,
|
|
1809
|
-
schemaName,
|
|
1810
|
-
schemaDescription,
|
|
1811
|
-
enumValues
|
|
1812
|
-
}) {
|
|
1813
|
-
if (output != null && output !== "object" && output !== "array" && output !== "enum" && output !== "no-schema") {
|
|
1814
|
-
throw new InvalidArgumentError({
|
|
1815
|
-
parameter: "output",
|
|
1816
|
-
value: output,
|
|
1817
|
-
message: "Invalid output type."
|
|
1818
|
-
});
|
|
1819
|
-
}
|
|
1820
|
-
if (output === "no-schema") {
|
|
1821
|
-
if (mode === "auto" || mode === "tool") {
|
|
1822
|
-
throw new InvalidArgumentError({
|
|
1823
|
-
parameter: "mode",
|
|
1824
|
-
value: mode,
|
|
1825
|
-
message: 'Mode must be "json" for no-schema output.'
|
|
1826
|
-
});
|
|
1827
|
-
}
|
|
1828
|
-
if (schema != null) {
|
|
1829
|
-
throw new InvalidArgumentError({
|
|
1830
|
-
parameter: "schema",
|
|
1831
|
-
value: schema,
|
|
1832
|
-
message: "Schema is not supported for no-schema output."
|
|
1833
|
-
});
|
|
1834
|
-
}
|
|
1835
|
-
if (schemaDescription != null) {
|
|
1836
|
-
throw new InvalidArgumentError({
|
|
1837
|
-
parameter: "schemaDescription",
|
|
1838
|
-
value: schemaDescription,
|
|
1839
|
-
message: "Schema description is not supported for no-schema output."
|
|
1840
|
-
});
|
|
1841
|
-
}
|
|
1842
|
-
if (schemaName != null) {
|
|
1843
|
-
throw new InvalidArgumentError({
|
|
1844
|
-
parameter: "schemaName",
|
|
1845
|
-
value: schemaName,
|
|
1846
|
-
message: "Schema name is not supported for no-schema output."
|
|
1847
|
-
});
|
|
1848
|
-
}
|
|
1849
|
-
if (enumValues != null) {
|
|
1850
|
-
throw new InvalidArgumentError({
|
|
1851
|
-
parameter: "enumValues",
|
|
1852
|
-
value: enumValues,
|
|
1853
|
-
message: "Enum values are not supported for no-schema output."
|
|
1854
|
-
});
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
if (output === "object") {
|
|
1858
|
-
if (schema == null) {
|
|
1859
|
-
throw new InvalidArgumentError({
|
|
1860
|
-
parameter: "schema",
|
|
1861
|
-
value: schema,
|
|
1862
|
-
message: "Schema is required for object output."
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
if (enumValues != null) {
|
|
1866
|
-
throw new InvalidArgumentError({
|
|
1867
|
-
parameter: "enumValues",
|
|
1868
|
-
value: enumValues,
|
|
1869
|
-
message: "Enum values are not supported for object output."
|
|
1870
|
-
});
|
|
1871
|
-
}
|
|
1872
|
-
}
|
|
1873
|
-
if (output === "array") {
|
|
1874
|
-
if (schema == null) {
|
|
1875
|
-
throw new InvalidArgumentError({
|
|
1876
|
-
parameter: "schema",
|
|
1877
|
-
value: schema,
|
|
1878
|
-
message: "Element schema is required for array output."
|
|
1879
|
-
});
|
|
1880
|
-
}
|
|
1881
|
-
if (enumValues != null) {
|
|
1882
|
-
throw new InvalidArgumentError({
|
|
1883
|
-
parameter: "enumValues",
|
|
1884
|
-
value: enumValues,
|
|
1885
|
-
message: "Enum values are not supported for array output."
|
|
1886
|
-
});
|
|
1887
|
-
}
|
|
1888
|
-
}
|
|
1889
|
-
if (output === "enum") {
|
|
1890
|
-
if (schema != null) {
|
|
1891
|
-
throw new InvalidArgumentError({
|
|
1892
|
-
parameter: "schema",
|
|
1893
|
-
value: schema,
|
|
1894
|
-
message: "Schema is not supported for enum output."
|
|
1895
|
-
});
|
|
1896
|
-
}
|
|
1897
|
-
if (schemaDescription != null) {
|
|
1898
|
-
throw new InvalidArgumentError({
|
|
1899
|
-
parameter: "schemaDescription",
|
|
1900
|
-
value: schemaDescription,
|
|
1901
|
-
message: "Schema description is not supported for enum output."
|
|
1902
|
-
});
|
|
1903
|
-
}
|
|
1904
|
-
if (schemaName != null) {
|
|
1905
|
-
throw new InvalidArgumentError({
|
|
1906
|
-
parameter: "schemaName",
|
|
1907
|
-
value: schemaName,
|
|
1908
|
-
message: "Schema name is not supported for enum output."
|
|
1909
|
-
});
|
|
1910
|
-
}
|
|
1911
|
-
if (enumValues == null) {
|
|
1912
|
-
throw new InvalidArgumentError({
|
|
1913
|
-
parameter: "enumValues",
|
|
1914
|
-
value: enumValues,
|
|
1915
|
-
message: "Enum values are required for enum output."
|
|
1916
|
-
});
|
|
1917
|
-
}
|
|
1918
|
-
for (const value of enumValues) {
|
|
1919
|
-
if (typeof value !== "string") {
|
|
1920
|
-
throw new InvalidArgumentError({
|
|
1921
|
-
parameter: "enumValues",
|
|
1922
|
-
value,
|
|
1923
|
-
message: "Enum values must be strings."
|
|
1924
|
-
});
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
}
|
|
1928
|
-
}
|
|
1929
|
-
|
|
1930
|
-
// core/prompt/stringify-for-telemetry.ts
|
|
1931
|
-
function stringifyForTelemetry(prompt) {
|
|
1932
|
-
const processedPrompt = prompt.map((message) => {
|
|
1933
|
-
return {
|
|
1934
|
-
...message,
|
|
1935
|
-
content: typeof message.content === "string" ? message.content : message.content.map(processPart)
|
|
1936
|
-
};
|
|
1937
|
-
});
|
|
1938
|
-
return JSON.stringify(processedPrompt);
|
|
1939
|
-
}
|
|
1940
|
-
function processPart(part) {
|
|
1941
|
-
if (part.type === "image") {
|
|
1942
|
-
return {
|
|
1943
|
-
...part,
|
|
1944
|
-
image: part.image instanceof Uint8Array ? convertDataContentToBase64String(part.image) : part.image
|
|
1945
|
-
};
|
|
1946
|
-
}
|
|
1947
|
-
return part;
|
|
1948
|
-
}
|
|
1949
|
-
|
|
1950
|
-
// core/generate-object/generate-object.ts
|
|
1951
|
-
var originalGenerateId = createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
1952
|
-
async function generateObject({
|
|
1953
|
-
model,
|
|
1954
|
-
enum: enumValues,
|
|
1955
|
-
// rename bc enum is reserved by typescript
|
|
1956
|
-
schema: inputSchema,
|
|
1957
|
-
schemaName,
|
|
1958
|
-
schemaDescription,
|
|
1959
|
-
mode,
|
|
1960
|
-
output = "object",
|
|
1961
|
-
system,
|
|
1962
|
-
prompt,
|
|
1963
|
-
messages,
|
|
1964
|
-
maxRetries: maxRetriesArg,
|
|
1965
|
-
abortSignal,
|
|
1966
|
-
headers,
|
|
1967
|
-
experimental_repairText: repairText,
|
|
1968
|
-
experimental_telemetry: telemetry,
|
|
1969
|
-
experimental_providerMetadata,
|
|
1970
|
-
providerOptions = experimental_providerMetadata,
|
|
1971
|
-
_internal: {
|
|
1972
|
-
generateId: generateId3 = originalGenerateId,
|
|
1973
|
-
currentDate = () => /* @__PURE__ */ new Date()
|
|
1974
|
-
} = {},
|
|
1975
|
-
...settings
|
|
1976
|
-
}) {
|
|
1977
|
-
if (typeof model === "string" || model.specificationVersion !== "v1") {
|
|
1978
|
-
throw new UnsupportedModelVersionError();
|
|
1979
|
-
}
|
|
1980
|
-
validateObjectGenerationInput({
|
|
1981
|
-
output,
|
|
1982
|
-
mode,
|
|
1983
|
-
schema: inputSchema,
|
|
1984
|
-
schemaName,
|
|
1985
|
-
schemaDescription,
|
|
1986
|
-
enumValues
|
|
1987
|
-
});
|
|
1988
|
-
const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
|
|
1989
|
-
const outputStrategy = getOutputStrategy({
|
|
1990
|
-
output,
|
|
1991
|
-
schema: inputSchema,
|
|
1992
|
-
enumValues
|
|
1993
|
-
});
|
|
1994
|
-
if (outputStrategy.type === "no-schema" && mode === void 0) {
|
|
1995
|
-
mode = "json";
|
|
1996
|
-
}
|
|
1997
|
-
const baseTelemetryAttributes = getBaseTelemetryAttributes({
|
|
1998
|
-
model,
|
|
1999
|
-
telemetry,
|
|
2000
|
-
headers,
|
|
2001
|
-
settings: { ...settings, maxRetries }
|
|
2002
|
-
});
|
|
2003
|
-
const tracer = getTracer(telemetry);
|
|
2004
|
-
return recordSpan({
|
|
2005
|
-
name: "ai.generateObject",
|
|
2006
|
-
attributes: selectTelemetryAttributes({
|
|
2007
|
-
telemetry,
|
|
2008
|
-
attributes: {
|
|
2009
|
-
...assembleOperationName({
|
|
2010
|
-
operationId: "ai.generateObject",
|
|
2011
|
-
telemetry
|
|
2012
|
-
}),
|
|
2013
|
-
...baseTelemetryAttributes,
|
|
2014
|
-
// specific settings that only make sense on the outer level:
|
|
2015
|
-
"ai.prompt": {
|
|
2016
|
-
input: () => JSON.stringify({ system, prompt, messages })
|
|
2017
|
-
},
|
|
2018
|
-
"ai.schema": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,
|
|
2019
|
-
"ai.schema.name": schemaName,
|
|
2020
|
-
"ai.schema.description": schemaDescription,
|
|
2021
|
-
"ai.settings.output": outputStrategy.type,
|
|
2022
|
-
"ai.settings.mode": mode
|
|
2023
|
-
}
|
|
2024
|
-
}),
|
|
2025
|
-
tracer,
|
|
2026
|
-
fn: async (span) => {
|
|
2027
|
-
var _a17, _b, _c, _d;
|
|
2028
|
-
if (mode === "auto" || mode == null) {
|
|
2029
|
-
mode = model.defaultObjectGenerationMode;
|
|
2030
|
-
}
|
|
2031
|
-
let result;
|
|
2032
|
-
let finishReason;
|
|
2033
|
-
let usage;
|
|
2034
|
-
let warnings;
|
|
2035
|
-
let rawResponse;
|
|
2036
|
-
let response;
|
|
2037
|
-
let request;
|
|
2038
|
-
let logprobs;
|
|
2039
|
-
let resultProviderMetadata;
|
|
2040
|
-
switch (mode) {
|
|
2041
|
-
case "json": {
|
|
2042
|
-
const standardizedPrompt = standardizePrompt({
|
|
2043
|
-
prompt: {
|
|
2044
|
-
system: outputStrategy.jsonSchema == null ? injectJsonInstruction({ prompt: system }) : model.supportsStructuredOutputs ? system : injectJsonInstruction({
|
|
2045
|
-
prompt: system,
|
|
2046
|
-
schema: outputStrategy.jsonSchema
|
|
2047
|
-
}),
|
|
2048
|
-
prompt,
|
|
2049
|
-
messages
|
|
2050
|
-
},
|
|
2051
|
-
tools: void 0
|
|
2052
|
-
});
|
|
2053
|
-
const promptMessages = await convertToLanguageModelPrompt({
|
|
2054
|
-
prompt: standardizedPrompt,
|
|
2055
|
-
modelSupportsImageUrls: model.supportsImageUrls,
|
|
2056
|
-
modelSupportsUrl: (_a17 = model.supportsUrl) == null ? void 0 : _a17.bind(model)
|
|
2057
|
-
// support 'this' context
|
|
2058
|
-
});
|
|
2059
|
-
const generateResult = await retry(
|
|
2060
|
-
() => recordSpan({
|
|
2061
|
-
name: "ai.generateObject.doGenerate",
|
|
2062
|
-
attributes: selectTelemetryAttributes({
|
|
2063
|
-
telemetry,
|
|
2064
|
-
attributes: {
|
|
2065
|
-
...assembleOperationName({
|
|
2066
|
-
operationId: "ai.generateObject.doGenerate",
|
|
2067
|
-
telemetry
|
|
2068
|
-
}),
|
|
2069
|
-
...baseTelemetryAttributes,
|
|
2070
|
-
"ai.prompt.format": {
|
|
2071
|
-
input: () => standardizedPrompt.type
|
|
2072
|
-
},
|
|
2073
|
-
"ai.prompt.messages": {
|
|
2074
|
-
input: () => JSON.stringify(promptMessages)
|
|
2075
|
-
},
|
|
2076
|
-
"ai.settings.mode": mode,
|
|
2077
|
-
// standardized gen-ai llm span attributes:
|
|
2078
|
-
"gen_ai.system": model.provider,
|
|
2079
|
-
"gen_ai.request.model": model.modelId,
|
|
2080
|
-
"gen_ai.request.frequency_penalty": settings.frequencyPenalty,
|
|
2081
|
-
"gen_ai.request.max_tokens": settings.maxTokens,
|
|
2082
|
-
"gen_ai.request.presence_penalty": settings.presencePenalty,
|
|
2083
|
-
"gen_ai.request.temperature": settings.temperature,
|
|
2084
|
-
"gen_ai.request.top_k": settings.topK,
|
|
2085
|
-
"gen_ai.request.top_p": settings.topP
|
|
2086
|
-
}
|
|
2087
|
-
}),
|
|
2088
|
-
tracer,
|
|
2089
|
-
fn: async (span2) => {
|
|
2090
|
-
var _a18, _b2, _c2, _d2, _e, _f;
|
|
2091
|
-
const result2 = await model.doGenerate({
|
|
2092
|
-
mode: {
|
|
2093
|
-
type: "object-json",
|
|
2094
|
-
schema: outputStrategy.jsonSchema,
|
|
2095
|
-
name: schemaName,
|
|
2096
|
-
description: schemaDescription
|
|
2097
|
-
},
|
|
2098
|
-
...prepareCallSettings(settings),
|
|
2099
|
-
inputFormat: standardizedPrompt.type,
|
|
2100
|
-
prompt: promptMessages,
|
|
2101
|
-
providerMetadata: providerOptions,
|
|
2102
|
-
abortSignal,
|
|
2103
|
-
headers
|
|
2104
|
-
});
|
|
2105
|
-
const responseData = {
|
|
2106
|
-
id: (_b2 = (_a18 = result2.response) == null ? void 0 : _a18.id) != null ? _b2 : generateId3(),
|
|
2107
|
-
timestamp: (_d2 = (_c2 = result2.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : currentDate(),
|
|
2108
|
-
modelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId
|
|
2109
|
-
};
|
|
2110
|
-
if (result2.text === void 0) {
|
|
2111
|
-
throw new NoObjectGeneratedError({
|
|
2112
|
-
message: "No object generated: the model did not return a response.",
|
|
2113
|
-
response: responseData,
|
|
2114
|
-
usage: calculateLanguageModelUsage(result2.usage),
|
|
2115
|
-
finishReason: result2.finishReason
|
|
2116
|
-
});
|
|
2117
|
-
}
|
|
2118
|
-
span2.setAttributes(
|
|
2119
|
-
selectTelemetryAttributes({
|
|
2120
|
-
telemetry,
|
|
2121
|
-
attributes: {
|
|
2122
|
-
"ai.response.finishReason": result2.finishReason,
|
|
2123
|
-
"ai.response.object": { output: () => result2.text },
|
|
2124
|
-
"ai.response.id": responseData.id,
|
|
2125
|
-
"ai.response.model": responseData.modelId,
|
|
2126
|
-
"ai.response.timestamp": responseData.timestamp.toISOString(),
|
|
2127
|
-
"ai.response.providerMetadata": JSON.stringify(
|
|
2128
|
-
result2.providerMetadata
|
|
2129
|
-
),
|
|
2130
|
-
"ai.usage.promptTokens": result2.usage.promptTokens,
|
|
2131
|
-
"ai.usage.completionTokens": result2.usage.completionTokens,
|
|
2132
|
-
// standardized gen-ai llm span attributes:
|
|
2133
|
-
"gen_ai.response.finish_reasons": [result2.finishReason],
|
|
2134
|
-
"gen_ai.response.id": responseData.id,
|
|
2135
|
-
"gen_ai.response.model": responseData.modelId,
|
|
2136
|
-
"gen_ai.usage.prompt_tokens": result2.usage.promptTokens,
|
|
2137
|
-
"gen_ai.usage.completion_tokens": result2.usage.completionTokens
|
|
2138
|
-
}
|
|
2139
|
-
})
|
|
2140
|
-
);
|
|
2141
|
-
return { ...result2, objectText: result2.text, responseData };
|
|
2142
|
-
}
|
|
2143
|
-
})
|
|
2144
|
-
);
|
|
2145
|
-
result = generateResult.objectText;
|
|
2146
|
-
finishReason = generateResult.finishReason;
|
|
2147
|
-
usage = generateResult.usage;
|
|
2148
|
-
warnings = generateResult.warnings;
|
|
2149
|
-
rawResponse = generateResult.rawResponse;
|
|
2150
|
-
logprobs = generateResult.logprobs;
|
|
2151
|
-
resultProviderMetadata = generateResult.providerMetadata;
|
|
2152
|
-
request = (_b = generateResult.request) != null ? _b : {};
|
|
2153
|
-
response = generateResult.responseData;
|
|
2154
|
-
break;
|
|
2155
|
-
}
|
|
2156
|
-
case "tool": {
|
|
2157
|
-
const standardizedPrompt = standardizePrompt({
|
|
2158
|
-
prompt: { system, prompt, messages },
|
|
2159
|
-
tools: void 0
|
|
2160
|
-
});
|
|
2161
|
-
const promptMessages = await convertToLanguageModelPrompt({
|
|
2162
|
-
prompt: standardizedPrompt,
|
|
2163
|
-
modelSupportsImageUrls: model.supportsImageUrls,
|
|
2164
|
-
modelSupportsUrl: (_c = model.supportsUrl) == null ? void 0 : _c.bind(model)
|
|
2165
|
-
// support 'this' context,
|
|
2166
|
-
});
|
|
2167
|
-
const inputFormat = standardizedPrompt.type;
|
|
2168
|
-
const generateResult = await retry(
|
|
2169
|
-
() => recordSpan({
|
|
2170
|
-
name: "ai.generateObject.doGenerate",
|
|
2171
|
-
attributes: selectTelemetryAttributes({
|
|
2172
|
-
telemetry,
|
|
2173
|
-
attributes: {
|
|
2174
|
-
...assembleOperationName({
|
|
2175
|
-
operationId: "ai.generateObject.doGenerate",
|
|
2176
|
-
telemetry
|
|
2177
|
-
}),
|
|
2178
|
-
...baseTelemetryAttributes,
|
|
2179
|
-
"ai.prompt.format": {
|
|
2180
|
-
input: () => inputFormat
|
|
2181
|
-
},
|
|
2182
|
-
"ai.prompt.messages": {
|
|
2183
|
-
input: () => stringifyForTelemetry(promptMessages)
|
|
2184
|
-
},
|
|
2185
|
-
"ai.settings.mode": mode,
|
|
2186
|
-
// standardized gen-ai llm span attributes:
|
|
2187
|
-
"gen_ai.system": model.provider,
|
|
2188
|
-
"gen_ai.request.model": model.modelId,
|
|
2189
|
-
"gen_ai.request.frequency_penalty": settings.frequencyPenalty,
|
|
2190
|
-
"gen_ai.request.max_tokens": settings.maxTokens,
|
|
2191
|
-
"gen_ai.request.presence_penalty": settings.presencePenalty,
|
|
2192
|
-
"gen_ai.request.temperature": settings.temperature,
|
|
2193
|
-
"gen_ai.request.top_k": settings.topK,
|
|
2194
|
-
"gen_ai.request.top_p": settings.topP
|
|
2195
|
-
}
|
|
2196
|
-
}),
|
|
2197
|
-
tracer,
|
|
2198
|
-
fn: async (span2) => {
|
|
2199
|
-
var _a18, _b2, _c2, _d2, _e, _f, _g, _h;
|
|
2200
|
-
const result2 = await model.doGenerate({
|
|
2201
|
-
mode: {
|
|
2202
|
-
type: "object-tool",
|
|
2203
|
-
tool: {
|
|
2204
|
-
type: "function",
|
|
2205
|
-
name: schemaName != null ? schemaName : "json",
|
|
2206
|
-
description: schemaDescription != null ? schemaDescription : "Respond with a JSON object.",
|
|
2207
|
-
parameters: outputStrategy.jsonSchema
|
|
2208
|
-
}
|
|
2209
|
-
},
|
|
2210
|
-
...prepareCallSettings(settings),
|
|
2211
|
-
inputFormat,
|
|
2212
|
-
prompt: promptMessages,
|
|
2213
|
-
providerMetadata: providerOptions,
|
|
2214
|
-
abortSignal,
|
|
2215
|
-
headers
|
|
2216
|
-
});
|
|
2217
|
-
const objectText = (_b2 = (_a18 = result2.toolCalls) == null ? void 0 : _a18[0]) == null ? void 0 : _b2.args;
|
|
2218
|
-
const responseData = {
|
|
2219
|
-
id: (_d2 = (_c2 = result2.response) == null ? void 0 : _c2.id) != null ? _d2 : generateId3(),
|
|
2220
|
-
timestamp: (_f = (_e = result2.response) == null ? void 0 : _e.timestamp) != null ? _f : currentDate(),
|
|
2221
|
-
modelId: (_h = (_g = result2.response) == null ? void 0 : _g.modelId) != null ? _h : model.modelId
|
|
2222
|
-
};
|
|
2223
|
-
if (objectText === void 0) {
|
|
2224
|
-
throw new NoObjectGeneratedError({
|
|
2225
|
-
message: "No object generated: the tool was not called.",
|
|
2226
|
-
response: responseData,
|
|
2227
|
-
usage: calculateLanguageModelUsage(result2.usage),
|
|
2228
|
-
finishReason: result2.finishReason
|
|
2229
|
-
});
|
|
2230
|
-
}
|
|
2231
|
-
span2.setAttributes(
|
|
2232
|
-
selectTelemetryAttributes({
|
|
2233
|
-
telemetry,
|
|
2234
|
-
attributes: {
|
|
2235
|
-
"ai.response.finishReason": result2.finishReason,
|
|
2236
|
-
"ai.response.object": { output: () => objectText },
|
|
2237
|
-
"ai.response.id": responseData.id,
|
|
2238
|
-
"ai.response.model": responseData.modelId,
|
|
2239
|
-
"ai.response.timestamp": responseData.timestamp.toISOString(),
|
|
2240
|
-
"ai.response.providerMetadata": JSON.stringify(
|
|
2241
|
-
result2.providerMetadata
|
|
2242
|
-
),
|
|
2243
|
-
"ai.usage.promptTokens": result2.usage.promptTokens,
|
|
2244
|
-
"ai.usage.completionTokens": result2.usage.completionTokens,
|
|
2245
|
-
// standardized gen-ai llm span attributes:
|
|
2246
|
-
"gen_ai.response.finish_reasons": [result2.finishReason],
|
|
2247
|
-
"gen_ai.response.id": responseData.id,
|
|
2248
|
-
"gen_ai.response.model": responseData.modelId,
|
|
2249
|
-
"gen_ai.usage.input_tokens": result2.usage.promptTokens,
|
|
2250
|
-
"gen_ai.usage.output_tokens": result2.usage.completionTokens
|
|
2251
|
-
}
|
|
2252
|
-
})
|
|
2253
|
-
);
|
|
2254
|
-
return { ...result2, objectText, responseData };
|
|
2255
|
-
}
|
|
2256
|
-
})
|
|
2257
|
-
);
|
|
2258
|
-
result = generateResult.objectText;
|
|
2259
|
-
finishReason = generateResult.finishReason;
|
|
2260
|
-
usage = generateResult.usage;
|
|
2261
|
-
warnings = generateResult.warnings;
|
|
2262
|
-
rawResponse = generateResult.rawResponse;
|
|
2263
|
-
logprobs = generateResult.logprobs;
|
|
2264
|
-
resultProviderMetadata = generateResult.providerMetadata;
|
|
2265
|
-
request = (_d = generateResult.request) != null ? _d : {};
|
|
2266
|
-
response = generateResult.responseData;
|
|
2267
|
-
break;
|
|
2268
|
-
}
|
|
2269
|
-
case void 0: {
|
|
2270
|
-
throw new Error(
|
|
2271
|
-
"Model does not have a default object generation mode."
|
|
2272
|
-
);
|
|
2273
|
-
}
|
|
2274
|
-
default: {
|
|
2275
|
-
const _exhaustiveCheck = mode;
|
|
2276
|
-
throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
|
|
2277
|
-
}
|
|
2278
|
-
}
|
|
2279
|
-
function processResult(result2) {
|
|
2280
|
-
const parseResult = safeParseJSON({ text: result2 });
|
|
2281
|
-
if (!parseResult.success) {
|
|
2282
|
-
throw new NoObjectGeneratedError({
|
|
2283
|
-
message: "No object generated: could not parse the response.",
|
|
2284
|
-
cause: parseResult.error,
|
|
2285
|
-
text: result2,
|
|
2286
|
-
response,
|
|
2287
|
-
usage: calculateLanguageModelUsage(usage),
|
|
2288
|
-
finishReason
|
|
2289
|
-
});
|
|
2290
|
-
}
|
|
2291
|
-
const validationResult = outputStrategy.validateFinalResult(
|
|
2292
|
-
parseResult.value,
|
|
2293
|
-
{
|
|
2294
|
-
text: result2,
|
|
2295
|
-
response,
|
|
2296
|
-
usage: calculateLanguageModelUsage(usage)
|
|
2297
|
-
}
|
|
2298
|
-
);
|
|
2299
|
-
if (!validationResult.success) {
|
|
2300
|
-
throw new NoObjectGeneratedError({
|
|
2301
|
-
message: "No object generated: response did not match schema.",
|
|
2302
|
-
cause: validationResult.error,
|
|
2303
|
-
text: result2,
|
|
2304
|
-
response,
|
|
2305
|
-
usage: calculateLanguageModelUsage(usage),
|
|
2306
|
-
finishReason
|
|
2307
|
-
});
|
|
2308
|
-
}
|
|
2309
|
-
return validationResult.value;
|
|
2310
|
-
}
|
|
2311
|
-
let object2;
|
|
2312
|
-
try {
|
|
2313
|
-
object2 = processResult(result);
|
|
2314
|
-
} catch (error) {
|
|
2315
|
-
if (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError.isInstance(error.cause) || TypeValidationError.isInstance(error.cause))) {
|
|
2316
|
-
const repairedText = await repairText({
|
|
2317
|
-
text: result,
|
|
2318
|
-
error: error.cause
|
|
2319
|
-
});
|
|
2320
|
-
if (repairedText === null) {
|
|
2321
|
-
throw error;
|
|
2322
|
-
}
|
|
2323
|
-
object2 = processResult(repairedText);
|
|
2324
|
-
} else {
|
|
2325
|
-
throw error;
|
|
2326
|
-
}
|
|
2327
|
-
}
|
|
2328
|
-
span.setAttributes(
|
|
2329
|
-
selectTelemetryAttributes({
|
|
2330
|
-
telemetry,
|
|
2331
|
-
attributes: {
|
|
2332
|
-
"ai.response.finishReason": finishReason,
|
|
2333
|
-
"ai.response.object": {
|
|
2334
|
-
output: () => JSON.stringify(object2)
|
|
2335
|
-
},
|
|
2336
|
-
"ai.usage.promptTokens": usage.promptTokens,
|
|
2337
|
-
"ai.usage.completionTokens": usage.completionTokens
|
|
2338
|
-
}
|
|
2339
|
-
})
|
|
2340
|
-
);
|
|
2341
|
-
return new DefaultGenerateObjectResult({
|
|
2342
|
-
object: object2,
|
|
2343
|
-
finishReason,
|
|
2344
|
-
usage: calculateLanguageModelUsage(usage),
|
|
2345
|
-
warnings,
|
|
2346
|
-
request,
|
|
2347
|
-
response: {
|
|
2348
|
-
...response,
|
|
2349
|
-
headers: rawResponse == null ? void 0 : rawResponse.headers,
|
|
2350
|
-
body: rawResponse == null ? void 0 : rawResponse.body
|
|
2351
|
-
},
|
|
2352
|
-
logprobs,
|
|
2353
|
-
providerMetadata: resultProviderMetadata
|
|
2354
|
-
});
|
|
2355
|
-
}
|
|
2356
|
-
});
|
|
2357
|
-
}
|
|
2358
|
-
var DefaultGenerateObjectResult = class {
|
|
2359
|
-
constructor(options) {
|
|
2360
|
-
this.object = options.object;
|
|
2361
|
-
this.finishReason = options.finishReason;
|
|
2362
|
-
this.usage = options.usage;
|
|
2363
|
-
this.warnings = options.warnings;
|
|
2364
|
-
this.providerMetadata = options.providerMetadata;
|
|
2365
|
-
this.experimental_providerMetadata = options.providerMetadata;
|
|
2366
|
-
this.response = options.response;
|
|
2367
|
-
this.request = options.request;
|
|
2368
|
-
this.logprobs = options.logprobs;
|
|
2369
|
-
}
|
|
2370
|
-
toJsonResponse(init) {
|
|
2371
|
-
var _a17;
|
|
2372
|
-
return new Response(JSON.stringify(this.object), {
|
|
2373
|
-
status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
|
|
2374
|
-
headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
|
|
2375
|
-
contentType: "application/json; charset=utf-8"
|
|
2376
|
-
})
|
|
2377
|
-
});
|
|
2378
|
-
}
|
|
2379
|
-
};
|
|
2380
|
-
|
|
2381
|
-
// core/generate-object/stream-object.ts
|
|
2382
|
-
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2383
|
-
|
|
2384
|
-
// core/generate-text/generate-text.ts
|
|
2385
|
-
createIdGenerator({
|
|
2386
|
-
prefix: "aitxt",
|
|
2387
|
-
size: 24
|
|
2388
|
-
});
|
|
2389
|
-
createIdGenerator({
|
|
2390
|
-
prefix: "msg",
|
|
2391
|
-
size: 24
|
|
2392
|
-
});
|
|
2393
|
-
|
|
2394
|
-
// core/generate-text/output.ts
|
|
2395
|
-
var output_exports = {};
|
|
2396
|
-
__export(output_exports, {
|
|
2397
|
-
object: () => object,
|
|
2398
|
-
text: () => text
|
|
2399
|
-
});
|
|
2400
|
-
|
|
2401
|
-
// core/generate-text/output.ts
|
|
2402
|
-
var text = () => ({
|
|
2403
|
-
type: "text",
|
|
2404
|
-
responseFormat: () => ({ type: "text" }),
|
|
2405
|
-
injectIntoSystemPrompt({ system }) {
|
|
2406
|
-
return system;
|
|
2407
|
-
},
|
|
2408
|
-
parsePartial({ text: text2 }) {
|
|
2409
|
-
return { partial: text2 };
|
|
2410
|
-
},
|
|
2411
|
-
parseOutput({ text: text2 }) {
|
|
2412
|
-
return text2;
|
|
2413
|
-
}
|
|
2414
|
-
});
|
|
2415
|
-
var object = ({
|
|
2416
|
-
schema: inputSchema
|
|
2417
|
-
}) => {
|
|
2418
|
-
const schema = asSchema(inputSchema);
|
|
2419
|
-
return {
|
|
2420
|
-
type: "object",
|
|
2421
|
-
responseFormat: ({ model }) => ({
|
|
2422
|
-
type: "json",
|
|
2423
|
-
schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
|
|
2424
|
-
}),
|
|
2425
|
-
injectIntoSystemPrompt({ system, model }) {
|
|
2426
|
-
return model.supportsStructuredOutputs ? system : injectJsonInstruction({
|
|
2427
|
-
prompt: system,
|
|
2428
|
-
schema: schema.jsonSchema
|
|
2429
|
-
});
|
|
2430
|
-
},
|
|
2431
|
-
parsePartial({ text: text2 }) {
|
|
2432
|
-
const result = parsePartialJson(text2);
|
|
2433
|
-
switch (result.state) {
|
|
2434
|
-
case "failed-parse":
|
|
2435
|
-
case "undefined-input":
|
|
2436
|
-
return void 0;
|
|
2437
|
-
case "repaired-parse":
|
|
2438
|
-
case "successful-parse":
|
|
2439
|
-
return {
|
|
2440
|
-
// Note: currently no validation of partial results:
|
|
2441
|
-
partial: result.value
|
|
2442
|
-
};
|
|
2443
|
-
default: {
|
|
2444
|
-
const _exhaustiveCheck = result.state;
|
|
2445
|
-
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
},
|
|
2449
|
-
parseOutput({ text: text2 }, context) {
|
|
2450
|
-
const parseResult = safeParseJSON({ text: text2 });
|
|
2451
|
-
if (!parseResult.success) {
|
|
2452
|
-
throw new NoObjectGeneratedError({
|
|
2453
|
-
message: "No object generated: could not parse the response.",
|
|
2454
|
-
cause: parseResult.error,
|
|
2455
|
-
text: text2,
|
|
2456
|
-
response: context.response,
|
|
2457
|
-
usage: context.usage,
|
|
2458
|
-
finishReason: context.finishReason
|
|
2459
|
-
});
|
|
2460
|
-
}
|
|
2461
|
-
const validationResult = safeValidateTypes({
|
|
2462
|
-
value: parseResult.value,
|
|
2463
|
-
schema
|
|
2464
|
-
});
|
|
2465
|
-
if (!validationResult.success) {
|
|
2466
|
-
throw new NoObjectGeneratedError({
|
|
2467
|
-
message: "No object generated: response did not match schema.",
|
|
2468
|
-
cause: validationResult.error,
|
|
2469
|
-
text: text2,
|
|
2470
|
-
response: context.response,
|
|
2471
|
-
usage: context.usage,
|
|
2472
|
-
finishReason: context.finishReason
|
|
2473
|
-
});
|
|
2474
|
-
}
|
|
2475
|
-
return validationResult.value;
|
|
2476
|
-
}
|
|
2477
|
-
};
|
|
2478
|
-
};
|
|
2479
|
-
|
|
2480
|
-
// core/util/merge-streams.ts
|
|
2481
|
-
function mergeStreams(stream1, stream2) {
|
|
2482
|
-
const reader1 = stream1.getReader();
|
|
2483
|
-
const reader2 = stream2.getReader();
|
|
2484
|
-
let lastRead1 = void 0;
|
|
2485
|
-
let lastRead2 = void 0;
|
|
2486
|
-
let stream1Done = false;
|
|
2487
|
-
let stream2Done = false;
|
|
2488
|
-
async function readStream1(controller) {
|
|
2489
|
-
try {
|
|
2490
|
-
if (lastRead1 == null) {
|
|
2491
|
-
lastRead1 = reader1.read();
|
|
2492
|
-
}
|
|
2493
|
-
const result = await lastRead1;
|
|
2494
|
-
lastRead1 = void 0;
|
|
2495
|
-
if (!result.done) {
|
|
2496
|
-
controller.enqueue(result.value);
|
|
2497
|
-
} else {
|
|
2498
|
-
controller.close();
|
|
2499
|
-
}
|
|
2500
|
-
} catch (error) {
|
|
2501
|
-
controller.error(error);
|
|
2502
|
-
}
|
|
2503
|
-
}
|
|
2504
|
-
async function readStream2(controller) {
|
|
2505
|
-
try {
|
|
2506
|
-
if (lastRead2 == null) {
|
|
2507
|
-
lastRead2 = reader2.read();
|
|
2508
|
-
}
|
|
2509
|
-
const result = await lastRead2;
|
|
2510
|
-
lastRead2 = void 0;
|
|
2511
|
-
if (!result.done) {
|
|
2512
|
-
controller.enqueue(result.value);
|
|
2513
|
-
} else {
|
|
2514
|
-
controller.close();
|
|
2515
|
-
}
|
|
2516
|
-
} catch (error) {
|
|
2517
|
-
controller.error(error);
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
return new ReadableStream({
|
|
2521
|
-
async pull(controller) {
|
|
2522
|
-
try {
|
|
2523
|
-
if (stream1Done) {
|
|
2524
|
-
await readStream2(controller);
|
|
2525
|
-
return;
|
|
2526
|
-
}
|
|
2527
|
-
if (stream2Done) {
|
|
2528
|
-
await readStream1(controller);
|
|
2529
|
-
return;
|
|
2530
|
-
}
|
|
2531
|
-
if (lastRead1 == null) {
|
|
2532
|
-
lastRead1 = reader1.read();
|
|
2533
|
-
}
|
|
2534
|
-
if (lastRead2 == null) {
|
|
2535
|
-
lastRead2 = reader2.read();
|
|
2536
|
-
}
|
|
2537
|
-
const { result, reader } = await Promise.race([
|
|
2538
|
-
lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
|
|
2539
|
-
lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
|
|
2540
|
-
]);
|
|
2541
|
-
if (!result.done) {
|
|
2542
|
-
controller.enqueue(result.value);
|
|
2543
|
-
}
|
|
2544
|
-
if (reader === reader1) {
|
|
2545
|
-
lastRead1 = void 0;
|
|
2546
|
-
if (result.done) {
|
|
2547
|
-
await readStream2(controller);
|
|
2548
|
-
stream1Done = true;
|
|
2549
|
-
}
|
|
2550
|
-
} else {
|
|
2551
|
-
lastRead2 = void 0;
|
|
2552
|
-
if (result.done) {
|
|
2553
|
-
stream2Done = true;
|
|
2554
|
-
await readStream1(controller);
|
|
2555
|
-
}
|
|
2556
|
-
}
|
|
2557
|
-
} catch (error) {
|
|
2558
|
-
controller.error(error);
|
|
2559
|
-
}
|
|
2560
|
-
},
|
|
2561
|
-
cancel() {
|
|
2562
|
-
reader1.cancel();
|
|
2563
|
-
reader2.cancel();
|
|
2564
|
-
}
|
|
2565
|
-
});
|
|
2566
|
-
}
|
|
2567
|
-
|
|
2568
|
-
// core/generate-text/stream-text.ts
|
|
2569
|
-
createIdGenerator({
|
|
2570
|
-
prefix: "aitxt",
|
|
2571
|
-
size: 24
|
|
2572
|
-
});
|
|
2573
|
-
createIdGenerator({
|
|
2574
|
-
prefix: "msg",
|
|
2575
|
-
size: 24
|
|
2576
|
-
});
|
|
2577
|
-
var ClientOrServerImplementationSchema = z.object({
|
|
2578
|
-
name: z.string(),
|
|
2579
|
-
version: z.string()
|
|
2580
|
-
}).passthrough();
|
|
2581
|
-
var BaseParamsSchema = z.object({
|
|
2582
|
-
_meta: z.optional(z.object({}).passthrough())
|
|
2583
|
-
}).passthrough();
|
|
2584
|
-
var ResultSchema = BaseParamsSchema;
|
|
2585
|
-
var RequestSchema = z.object({
|
|
2586
|
-
method: z.string(),
|
|
2587
|
-
params: z.optional(BaseParamsSchema)
|
|
2588
|
-
});
|
|
2589
|
-
var ServerCapabilitiesSchema = z.object({
|
|
2590
|
-
experimental: z.optional(z.object({}).passthrough()),
|
|
2591
|
-
logging: z.optional(z.object({}).passthrough()),
|
|
2592
|
-
prompts: z.optional(
|
|
2593
|
-
z.object({
|
|
2594
|
-
listChanged: z.optional(z.boolean())
|
|
2595
|
-
}).passthrough()
|
|
2596
|
-
),
|
|
2597
|
-
resources: z.optional(
|
|
2598
|
-
z.object({
|
|
2599
|
-
subscribe: z.optional(z.boolean()),
|
|
2600
|
-
listChanged: z.optional(z.boolean())
|
|
2601
|
-
}).passthrough()
|
|
2602
|
-
),
|
|
2603
|
-
tools: z.optional(
|
|
2604
|
-
z.object({
|
|
2605
|
-
listChanged: z.optional(z.boolean())
|
|
2606
|
-
}).passthrough()
|
|
2607
|
-
)
|
|
2608
|
-
}).passthrough();
|
|
2609
|
-
ResultSchema.extend({
|
|
2610
|
-
protocolVersion: z.string(),
|
|
2611
|
-
capabilities: ServerCapabilitiesSchema,
|
|
2612
|
-
serverInfo: ClientOrServerImplementationSchema,
|
|
2613
|
-
instructions: z.optional(z.string())
|
|
2614
|
-
});
|
|
2615
|
-
var PaginatedResultSchema = ResultSchema.extend({
|
|
2616
|
-
nextCursor: z.optional(z.string())
|
|
2617
|
-
});
|
|
2618
|
-
var ToolSchema = z.object({
|
|
2619
|
-
name: z.string(),
|
|
2620
|
-
description: z.optional(z.string()),
|
|
2621
|
-
inputSchema: z.object({
|
|
2622
|
-
type: z.literal("object"),
|
|
2623
|
-
properties: z.optional(z.object({}).passthrough())
|
|
2624
|
-
}).passthrough()
|
|
2625
|
-
}).passthrough();
|
|
2626
|
-
PaginatedResultSchema.extend({
|
|
2627
|
-
tools: z.array(ToolSchema)
|
|
2628
|
-
});
|
|
2629
|
-
var TextContentSchema = z.object({
|
|
2630
|
-
type: z.literal("text"),
|
|
2631
|
-
text: z.string()
|
|
2632
|
-
}).passthrough();
|
|
2633
|
-
var ImageContentSchema = z.object({
|
|
2634
|
-
type: z.literal("image"),
|
|
2635
|
-
data: z.string().base64(),
|
|
2636
|
-
mimeType: z.string()
|
|
2637
|
-
}).passthrough();
|
|
2638
|
-
var ResourceContentsSchema = z.object({
|
|
2639
|
-
/**
|
|
2640
|
-
* The URI of this resource.
|
|
2641
|
-
*/
|
|
2642
|
-
uri: z.string(),
|
|
2643
|
-
/**
|
|
2644
|
-
* The MIME type of this resource, if known.
|
|
2645
|
-
*/
|
|
2646
|
-
mimeType: z.optional(z.string())
|
|
2647
|
-
}).passthrough();
|
|
2648
|
-
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2649
|
-
text: z.string()
|
|
2650
|
-
});
|
|
2651
|
-
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2652
|
-
blob: z.string().base64()
|
|
2653
|
-
});
|
|
2654
|
-
var EmbeddedResourceSchema = z.object({
|
|
2655
|
-
type: z.literal("resource"),
|
|
2656
|
-
resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
|
|
2657
|
-
}).passthrough();
|
|
2658
|
-
ResultSchema.extend({
|
|
2659
|
-
content: z.array(
|
|
2660
|
-
z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
|
|
2661
|
-
),
|
|
2662
|
-
isError: z.boolean().default(false).optional()
|
|
2663
|
-
}).or(
|
|
2664
|
-
ResultSchema.extend({
|
|
2665
|
-
toolResult: z.unknown()
|
|
2666
|
-
})
|
|
2667
|
-
);
|
|
2668
|
-
|
|
2669
|
-
// core/tool/mcp/json-rpc-message.ts
|
|
2670
|
-
var JSONRPC_VERSION = "2.0";
|
|
2671
|
-
var JSONRPCRequestSchema = z.object({
|
|
2672
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2673
|
-
id: z.union([z.string(), z.number().int()])
|
|
2674
|
-
}).merge(RequestSchema).strict();
|
|
2675
|
-
var JSONRPCResponseSchema = z.object({
|
|
2676
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2677
|
-
id: z.union([z.string(), z.number().int()]),
|
|
2678
|
-
result: ResultSchema
|
|
2679
|
-
}).strict();
|
|
2680
|
-
var JSONRPCErrorSchema = z.object({
|
|
2681
|
-
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2682
|
-
id: z.union([z.string(), z.number().int()]),
|
|
2683
|
-
error: z.object({
|
|
2684
|
-
code: z.number().int(),
|
|
2685
|
-
message: z.string(),
|
|
2686
|
-
data: z.optional(z.unknown())
|
|
2687
|
-
})
|
|
2688
|
-
}).strict();
|
|
2689
|
-
var JSONRPCNotificationSchema = z.object({
|
|
2690
|
-
jsonrpc: z.literal(JSONRPC_VERSION)
|
|
2691
|
-
}).merge(
|
|
2692
|
-
z.object({
|
|
2693
|
-
method: z.string(),
|
|
2694
|
-
params: z.optional(BaseParamsSchema)
|
|
2695
|
-
})
|
|
2696
|
-
).strict();
|
|
2697
|
-
z.union([
|
|
2698
|
-
JSONRPCRequestSchema,
|
|
2699
|
-
JSONRPCNotificationSchema,
|
|
2700
|
-
JSONRPCResponseSchema,
|
|
2701
|
-
JSONRPCErrorSchema
|
|
2702
|
-
]);
|
|
2703
|
-
|
|
2704
|
-
// streams/langchain-adapter.ts
|
|
2705
|
-
var langchain_adapter_exports = {};
|
|
2706
|
-
__export(langchain_adapter_exports, {
|
|
2707
|
-
mergeIntoDataStream: () => mergeIntoDataStream,
|
|
2708
|
-
toDataStream: () => toDataStream,
|
|
2709
|
-
toDataStreamResponse: () => toDataStreamResponse
|
|
2710
|
-
});
|
|
2711
|
-
|
|
2712
|
-
// streams/stream-callbacks.ts
|
|
2713
|
-
function createCallbacksTransformer(callbacks = {}) {
|
|
2714
|
-
const textEncoder = new TextEncoder();
|
|
2715
|
-
let aggregatedResponse = "";
|
|
2716
|
-
return new TransformStream({
|
|
2717
|
-
async start() {
|
|
2718
|
-
if (callbacks.onStart)
|
|
2719
|
-
await callbacks.onStart();
|
|
2720
|
-
},
|
|
2721
|
-
async transform(message, controller) {
|
|
2722
|
-
controller.enqueue(textEncoder.encode(message));
|
|
2723
|
-
aggregatedResponse += message;
|
|
2724
|
-
if (callbacks.onToken)
|
|
2725
|
-
await callbacks.onToken(message);
|
|
2726
|
-
if (callbacks.onText && typeof message === "string") {
|
|
2727
|
-
await callbacks.onText(message);
|
|
2728
|
-
}
|
|
2729
|
-
},
|
|
2730
|
-
async flush() {
|
|
2731
|
-
if (callbacks.onCompletion) {
|
|
2732
|
-
await callbacks.onCompletion(aggregatedResponse);
|
|
2733
|
-
}
|
|
2734
|
-
if (callbacks.onFinal) {
|
|
2735
|
-
await callbacks.onFinal(aggregatedResponse);
|
|
2736
|
-
}
|
|
2737
|
-
}
|
|
2738
|
-
});
|
|
2739
|
-
}
|
|
2740
|
-
|
|
2741
|
-
// streams/langchain-adapter.ts
|
|
2742
|
-
function toDataStreamInternal(stream, callbacks) {
|
|
2743
|
-
return stream.pipeThrough(
|
|
2744
|
-
new TransformStream({
|
|
2745
|
-
transform: async (value, controller) => {
|
|
2746
|
-
var _a17;
|
|
2747
|
-
if (typeof value === "string") {
|
|
2748
|
-
controller.enqueue(value);
|
|
2749
|
-
return;
|
|
2750
|
-
}
|
|
2751
|
-
if ("event" in value) {
|
|
2752
|
-
if (value.event === "on_chat_model_stream") {
|
|
2753
|
-
forwardAIMessageChunk(
|
|
2754
|
-
(_a17 = value.data) == null ? void 0 : _a17.chunk,
|
|
2755
|
-
controller
|
|
2756
|
-
);
|
|
2757
|
-
}
|
|
2758
|
-
return;
|
|
2759
|
-
}
|
|
2760
|
-
forwardAIMessageChunk(value, controller);
|
|
2761
|
-
}
|
|
2762
|
-
})
|
|
2763
|
-
).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
|
|
2764
|
-
new TransformStream({
|
|
2765
|
-
transform: async (chunk, controller) => {
|
|
2766
|
-
controller.enqueue(formatDataStreamPart("text", chunk));
|
|
2767
|
-
}
|
|
2768
|
-
})
|
|
2769
|
-
);
|
|
2770
|
-
}
|
|
2771
|
-
function toDataStream(stream, callbacks) {
|
|
2772
|
-
return toDataStreamInternal(stream, callbacks).pipeThrough(
|
|
2773
|
-
new TextEncoderStream()
|
|
2774
|
-
);
|
|
2775
|
-
}
|
|
2776
|
-
function toDataStreamResponse(stream, options) {
|
|
2777
|
-
var _a17;
|
|
2778
|
-
const dataStream = toDataStreamInternal(
|
|
2779
|
-
stream,
|
|
2780
|
-
options == null ? void 0 : options.callbacks
|
|
2781
|
-
).pipeThrough(new TextEncoderStream());
|
|
2782
|
-
const data = options == null ? void 0 : options.data;
|
|
2783
|
-
const init = options == null ? void 0 : options.init;
|
|
2784
|
-
const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
|
|
2785
|
-
return new Response(responseStream, {
|
|
2786
|
-
status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
|
|
2787
|
-
statusText: init == null ? void 0 : init.statusText,
|
|
2788
|
-
headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
|
|
2789
|
-
contentType: "text/plain; charset=utf-8",
|
|
2790
|
-
dataStreamVersion: "v1"
|
|
2791
|
-
})
|
|
2792
|
-
});
|
|
2793
|
-
}
|
|
2794
|
-
function mergeIntoDataStream(stream, options) {
|
|
2795
|
-
options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
|
|
2796
|
-
}
|
|
2797
|
-
function forwardAIMessageChunk(chunk, controller) {
|
|
2798
|
-
if (typeof chunk.content === "string") {
|
|
2799
|
-
controller.enqueue(chunk.content);
|
|
2800
|
-
} else {
|
|
2801
|
-
const content = chunk.content;
|
|
2802
|
-
for (const item of content) {
|
|
2803
|
-
if (item.type === "text") {
|
|
2804
|
-
controller.enqueue(item.text);
|
|
2805
|
-
}
|
|
2806
|
-
}
|
|
2807
|
-
}
|
|
2808
|
-
}
|
|
2809
|
-
|
|
2810
|
-
// streams/llamaindex-adapter.ts
|
|
2811
|
-
var llamaindex_adapter_exports = {};
|
|
2812
|
-
__export(llamaindex_adapter_exports, {
|
|
2813
|
-
mergeIntoDataStream: () => mergeIntoDataStream2,
|
|
2814
|
-
toDataStream: () => toDataStream2,
|
|
2815
|
-
toDataStreamResponse: () => toDataStreamResponse2
|
|
2816
|
-
});
|
|
2817
|
-
function toDataStreamInternal2(stream, callbacks) {
|
|
2818
|
-
const trimStart = trimStartOfStream();
|
|
2819
|
-
return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(
|
|
2820
|
-
new TransformStream({
|
|
2821
|
-
async transform(message, controller) {
|
|
2822
|
-
controller.enqueue(trimStart(message.delta));
|
|
2823
|
-
}
|
|
2824
|
-
})
|
|
2825
|
-
).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
|
|
2826
|
-
new TransformStream({
|
|
2827
|
-
transform: async (chunk, controller) => {
|
|
2828
|
-
controller.enqueue(formatDataStreamPart("text", chunk));
|
|
2829
|
-
}
|
|
2830
|
-
})
|
|
2831
|
-
);
|
|
2832
|
-
}
|
|
2833
|
-
function toDataStream2(stream, callbacks) {
|
|
2834
|
-
return toDataStreamInternal2(stream, callbacks).pipeThrough(
|
|
2835
|
-
new TextEncoderStream()
|
|
2836
|
-
);
|
|
2837
|
-
}
|
|
2838
|
-
function toDataStreamResponse2(stream, options = {}) {
|
|
2839
|
-
var _a17;
|
|
2840
|
-
const { init, data, callbacks } = options;
|
|
2841
|
-
const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
|
|
2842
|
-
new TextEncoderStream()
|
|
2843
|
-
);
|
|
2844
|
-
const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
|
|
2845
|
-
return new Response(responseStream, {
|
|
2846
|
-
status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
|
|
2847
|
-
statusText: init == null ? void 0 : init.statusText,
|
|
2848
|
-
headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
|
|
2849
|
-
contentType: "text/plain; charset=utf-8",
|
|
2850
|
-
dataStreamVersion: "v1"
|
|
2851
|
-
})
|
|
2852
|
-
});
|
|
2853
|
-
}
|
|
2854
|
-
function mergeIntoDataStream2(stream, options) {
|
|
2855
|
-
options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
|
|
2856
|
-
}
|
|
2857
|
-
function trimStartOfStream() {
|
|
2858
|
-
let isStreamStart = true;
|
|
2859
|
-
return (text2) => {
|
|
2860
|
-
if (isStreamStart) {
|
|
2861
|
-
text2 = text2.trimStart();
|
|
2862
|
-
if (text2)
|
|
2863
|
-
isStreamStart = false;
|
|
2864
|
-
}
|
|
2865
|
-
return text2;
|
|
2866
|
-
};
|
|
2867
|
-
}
|
|
2868
|
-
|
|
2869
|
-
export { AISDKError, APICallError, DownloadError, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, JSONParseError, langchain_adapter_exports as LangChainAdapter, llamaindex_adapter_exports as LlamaIndexAdapter, MessageConversionError, NoObjectGeneratedError, output_exports as Output, RetryError, TypeValidationError, UnsupportedFunctionalityError, UnsupportedModelVersionError, convertToCoreMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, createIdGenerator, formatDataStreamPart, generateObject };
|
|
2870
|
-
//# sourceMappingURL=index.js.map
|