@opencode/ai 2.2.5 → 2.2.7
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 +228 -72
- package/dist/ai-client.d.ts +2 -2
- package/dist/ai-client.js +2 -1
- package/dist/cache-policy.d.ts +1 -1
- package/dist/cache-policy.js +16 -4
- package/dist/decision-client.d.ts +3 -3
- package/dist/decision.d.ts +30 -125
- package/dist/decision.js +27 -15
- package/dist/effect.d.ts +10 -15
- package/dist/effect.js +6 -6
- package/dist/effort-updates.d.ts +3 -3
- package/dist/effort-updates.js +2 -2
- package/dist/embedding-client.d.ts +21 -0
- package/dist/embedding-client.js +30 -0
- package/dist/embedding.d.ts +111 -0
- package/dist/embedding.js +75 -0
- package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
- package/dist/experimental/cloudflare-run-extraction.js +4 -1
- package/dist/experimental/extraction.d.ts +10 -40
- package/dist/experimental/extraction.js +14 -13
- package/dist/experimental.d.ts +8 -8
- package/dist/experimental.js +4 -4
- package/dist/generation.d.ts +0 -2
- package/dist/generation.js +2 -2
- package/dist/image-client.d.ts +13 -7
- package/dist/image-client.js +1 -1
- package/dist/image.d.ts +357 -465
- package/dist/image.js +17 -18
- package/dist/index.d.ts +35 -467
- package/dist/index.js +23 -17
- package/dist/llm.d.ts +65 -266
- package/dist/llm.js +101 -92
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +136 -0
- package/dist/media-model.d.ts +1 -1
- package/dist/media-model.js +8 -6
- package/dist/media.d.ts +9 -0
- package/dist/media.js +37 -2
- package/dist/protocols/alibaba-chat.d.ts +9 -1
- package/dist/protocols/alibaba-chat.js +3 -3
- package/dist/protocols/alibaba-images.d.ts +2 -2
- package/dist/protocols/alibaba-messages.js +3 -3
- package/dist/protocols/alibaba-responses.js +8 -20
- package/dist/protocols/anthropic-messages.d.ts +1 -1
- package/dist/protocols/anthropic-messages.js +57 -176
- package/dist/protocols/assemblyai-transcription.d.ts +2 -2
- package/dist/protocols/bedrock-converse.js +10 -16
- package/dist/protocols/cartesia-speech.d.ts +2 -2
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
- package/dist/protocols/cohere-chat.js +9 -12
- package/dist/protocols/deepgram-speech.d.ts +2 -2
- package/dist/protocols/deepgram-transcription.d.ts +2 -2
- package/dist/protocols/elevenlabs-speech.d.ts +2 -2
- package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
- package/dist/protocols/gemini.d.ts +3 -0
- package/dist/protocols/gemini.js +54 -72
- package/dist/protocols/google-embed-content.d.ts +34 -0
- package/dist/protocols/google-embed-content.js +110 -0
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-interactions.d.ts +3 -4
- package/dist/protocols/google-interactions.js +44 -30
- package/dist/protocols/google-speech.d.ts +2 -2
- package/dist/protocols/google-transcription.d.ts +2 -2
- package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
- package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
- package/dist/protocols/google-video.d.ts +2 -2
- package/dist/protocols/index.d.ts +3 -0
- package/dist/protocols/index.js +3 -0
- package/dist/protocols/meta-images.d.ts +2 -2
- package/dist/protocols/meta-responses.js +26 -23
- package/dist/protocols/minimax-images.d.ts +2 -2
- package/dist/protocols/mistral-chat.js +7 -10
- package/dist/protocols/open-responses-channel.js +6 -19
- package/dist/protocols/open-responses-continuation.d.ts +1 -5
- package/dist/protocols/open-responses-continuation.js +1 -3
- package/dist/protocols/open-responses.d.ts +2 -22
- package/dist/protocols/open-responses.js +41 -23
- package/dist/protocols/openai-chat.d.ts +27 -23
- package/dist/protocols/openai-chat.js +62 -57
- package/dist/protocols/openai-compatible-chat.d.ts +2 -1
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-compatible-responses.js +1 -1
- package/dist/protocols/openai-decisions.js +15 -2
- package/dist/protocols/openai-embeddings.d.ts +16 -0
- package/dist/protocols/openai-embeddings.js +76 -0
- package/dist/protocols/openai-images.d.ts +2 -2
- package/dist/protocols/openai-responses.js +10 -29
- package/dist/protocols/openai-speech.d.ts +2 -2
- package/dist/protocols/openai-transcription.d.ts +2 -2
- package/dist/protocols/runway-video.d.ts +2 -2
- package/dist/protocols/shared.d.ts +14 -7
- package/dist/protocols/shared.js +40 -15
- package/dist/protocols/system-one.d.ts +4 -4
- package/dist/protocols/system-one.js +8 -1
- package/dist/protocols/utils/bedrock-cache.js +2 -5
- package/dist/protocols/utils/bedrock-media.d.ts +0 -3
- package/dist/protocols/utils/cache.d.ts +3 -0
- package/dist/protocols/utils/cache.js +15 -2
- package/dist/protocols/utils/image-sizing.d.ts +1 -1
- package/dist/protocols/utils/responses-checkpoint.js +1 -1
- package/dist/protocols/utils/responses-compaction.d.ts +1 -1
- package/dist/protocols/utils/responses-compaction.js +6 -5
- package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
- package/dist/protocols/utils/responses-hosted-tools.js +31 -0
- package/dist/protocols/utils/tool-stream.d.ts +5 -271
- package/dist/protocols/utils/tool-stream.js +3 -13
- package/dist/protocols/venice-chat.d.ts +7 -1
- package/dist/protocols/venice-chat.js +4 -4
- package/dist/protocols/xai-images.d.ts +2 -2
- package/dist/protocols/xai-responses.js +5 -25
- package/dist/protocols/xai-video.d.ts +2 -2
- package/dist/protocols/zai-chat.d.ts +9 -1
- package/dist/protocols/zai-chat.js +1 -1
- package/dist/protocols/zai-images.d.ts +2 -2
- package/dist/protocols/zai-messages.js +3 -3
- package/dist/provider-error.d.ts +0 -1
- package/dist/provider-error.js +7 -80
- package/dist/providers/alibaba/embeddings.d.ts +2 -0
- package/dist/providers/alibaba/embeddings.js +1 -0
- package/dist/providers/alibaba.d.ts +70 -4
- package/dist/providers/alibaba.js +20 -2
- package/dist/providers/amazon-bedrock-mantle.d.ts +7 -3
- package/dist/providers/amazon-bedrock-mantle.js +6 -3
- package/dist/providers/amazon-bedrock.d.ts +6 -7
- package/dist/providers/amazon-bedrock.js +1 -1
- package/dist/providers/anthropic-compatible.d.ts +7 -8
- package/dist/providers/anthropic-compatible.js +2 -5
- package/dist/providers/anthropic.d.ts +8 -9
- package/dist/providers/anthropic.js +2 -7
- package/dist/providers/assemblyai.d.ts +2 -2
- package/dist/providers/assemblyai.js +2 -7
- package/dist/providers/azure/embeddings.d.ts +2 -0
- package/dist/providers/azure/embeddings.js +1 -0
- package/dist/providers/azure/messages.d.ts +2 -0
- package/dist/providers/azure/messages.js +1 -0
- package/dist/providers/azure.d.ts +325 -7
- package/dist/providers/azure.js +40 -9
- package/dist/providers/baseten.d.ts +7 -5
- package/dist/providers/baseten.js +7 -21
- package/dist/providers/cartesia.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +7 -5
- package/dist/providers/cerebras.js +4 -15
- package/dist/providers/cloudflare-ai-gateway.d.ts +23 -13
- package/dist/providers/cloudflare-ai-gateway.js +28 -40
- package/dist/providers/cloudflare-shared.d.ts +9 -0
- package/dist/providers/cloudflare-shared.js +25 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +6 -4
- package/dist/providers/cloudflare-workers-ai.js +4 -20
- package/dist/providers/cohere/chat.js +2 -7
- package/dist/providers/cohere/embeddings.d.ts +2 -0
- package/dist/providers/cohere/embeddings.js +1 -0
- package/dist/providers/cohere.d.ts +14 -5
- package/dist/providers/cohere.js +23 -13
- package/dist/providers/deepgram.d.ts +2 -2
- package/dist/providers/deepgram.js +2 -7
- package/dist/providers/deepinfra/embeddings.d.ts +2 -0
- package/dist/providers/deepinfra/embeddings.js +1 -0
- package/dist/providers/deepinfra.d.ts +10 -5
- package/dist/providers/deepinfra.js +20 -14
- package/dist/providers/deepseek.d.ts +7 -5
- package/dist/providers/deepseek.js +3 -14
- package/dist/providers/digitalocean/embeddings.d.ts +2 -0
- package/dist/providers/digitalocean/embeddings.js +1 -0
- package/dist/providers/digitalocean.d.ts +18 -5
- package/dist/providers/digitalocean.js +28 -14
- package/dist/providers/elevenlabs.d.ts +2 -2
- package/dist/providers/elevenlabs.js +2 -7
- package/dist/providers/fireworks/embeddings.d.ts +2 -0
- package/dist/providers/fireworks/embeddings.js +1 -0
- package/dist/providers/fireworks.d.ts +10 -5
- package/dist/providers/fireworks.js +17 -14
- package/dist/providers/google/embeddings.d.ts +2 -0
- package/dist/providers/google/embeddings.js +1 -0
- package/dist/providers/google/interactions.d.ts +1 -1
- package/dist/providers/google/interactions.js +2 -7
- package/dist/providers/google-vertex/embeddings.d.ts +2 -0
- package/dist/providers/google-vertex/embeddings.js +1 -0
- package/dist/providers/google-vertex-chat.d.ts +4 -3
- package/dist/providers/google-vertex-chat.js +3 -29
- package/dist/providers/google-vertex-interactions.d.ts +3 -3
- package/dist/providers/google-vertex-messages.d.ts +3 -3
- package/dist/providers/google-vertex-messages.js +3 -29
- package/dist/providers/google-vertex-mistral.d.ts +3 -3
- package/dist/providers/google-vertex-mistral.js +3 -29
- package/dist/providers/google-vertex-responses.d.ts +3 -3
- package/dist/providers/google-vertex-responses.js +4 -30
- package/dist/providers/google-vertex-shared.d.ts +31 -0
- package/dist/providers/google-vertex-shared.js +25 -0
- package/dist/providers/google-vertex.d.ts +10 -3
- package/dist/providers/google-vertex.js +52 -0
- package/dist/providers/google.d.ts +21 -13
- package/dist/providers/google.js +23 -19
- package/dist/providers/groq.d.ts +10 -5
- package/dist/providers/groq.js +4 -15
- package/dist/providers/meta.d.ts +6 -5
- package/dist/providers/meta.js +10 -23
- package/dist/providers/minimax/chat.js +2 -7
- package/dist/providers/minimax/responses.js +2 -7
- package/dist/providers/minimax.d.ts +6 -5
- package/dist/providers/minimax.js +7 -22
- package/dist/providers/mistral.d.ts +10 -11
- package/dist/providers/mistral.js +3 -14
- package/dist/providers/moonshot/messages.js +2 -7
- package/dist/providers/moonshot/responses.js +2 -7
- package/dist/providers/moonshot.d.ts +6 -5
- package/dist/providers/moonshot.js +4 -16
- package/dist/providers/openai/embeddings.d.ts +2 -0
- package/dist/providers/openai/embeddings.js +1 -0
- package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
- package/dist/providers/openai-compatible/embeddings.js +1 -0
- package/dist/providers/openai-compatible-responses.d.ts +6 -7
- package/dist/providers/openai-compatible-responses.js +2 -8
- package/dist/providers/openai-compatible.d.ts +10 -7
- package/dist/providers/openai-compatible.js +17 -10
- package/dist/providers/openai.d.ts +11 -4
- package/dist/providers/openai.js +17 -3
- package/dist/providers/opencode.d.ts +4 -4
- package/dist/providers/opencode.js +6 -2
- package/dist/providers/openrouter/embeddings.d.ts +2 -0
- package/dist/providers/openrouter/embeddings.js +1 -0
- package/dist/providers/openrouter.d.ts +24 -5
- package/dist/providers/openrouter.js +31 -24
- package/dist/providers/runway.d.ts +1 -1
- package/dist/providers/settings.d.ts +40 -0
- package/dist/providers/settings.js +19 -0
- package/dist/providers/togetherai.d.ts +7 -5
- package/dist/providers/togetherai.js +5 -15
- package/dist/providers/typesafe-ai.d.ts +4 -4
- package/dist/providers/typesafe-ai.js +6 -2
- package/dist/providers/venice.d.ts +5 -4
- package/dist/providers/venice.js +6 -2
- package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
- package/dist/providers/vercel-ai-gateway.d.ts +9 -5
- package/dist/providers/vercel-ai-gateway.js +30 -29
- package/dist/providers/xai.d.ts +5 -4
- package/dist/providers/xai.js +4 -12
- package/dist/providers/zai-coding-plan/messages.js +2 -7
- package/dist/providers/zai-coding-plan/responses.js +2 -7
- package/dist/providers/zai-coding-plan.d.ts +6 -5
- package/dist/providers/zai-coding-plan.js +8 -15
- package/dist/providers/zai.d.ts +6 -5
- package/dist/providers/zai.js +10 -22
- package/dist/public.d.ts +14 -0
- package/dist/public.js +6 -0
- package/dist/route/auth-options.d.ts +9 -5
- package/dist/route/auth-options.js +10 -7
- package/dist/route/client.d.ts +50 -37
- package/dist/route/client.js +42 -53
- package/dist/route/decision.d.ts +8 -8
- package/dist/route/decision.js +3 -3
- package/dist/route/embedding.d.ts +61 -0
- package/dist/route/embedding.js +88 -0
- package/dist/route/executor.d.ts +5 -0
- package/dist/route/executor.js +10 -0
- package/dist/route/index.d.ts +5 -7
- package/dist/route/index.js +1 -1
- package/dist/route/media.d.ts +7 -11
- package/dist/route/media.js +22 -26
- package/dist/route/transport/http.js +6 -5
- package/dist/route/transport/websocket.js +7 -1
- package/dist/schema/errors.d.ts +16 -17
- package/dist/schema/errors.js +63 -12
- package/dist/schema/events.d.ts +2563 -2954
- package/dist/schema/events.js +54 -109
- package/dist/schema/messages.d.ts +194 -137
- package/dist/schema/messages.js +66 -83
- package/dist/schema/options.d.ts +112 -65
- package/dist/schema/options.js +52 -101
- package/dist/speech-client.d.ts +7 -7
- package/dist/speech.d.ts +306 -316
- package/dist/speech.js +16 -14
- package/dist/testing.d.ts +31 -175
- package/dist/testing.js +60 -5
- package/dist/tool-history.d.ts +1 -1
- package/dist/tool-history.js +3 -10
- package/dist/tool-runtime.d.ts +9 -2
- package/dist/tool-runtime.js +17 -31
- package/dist/tool.d.ts +39 -43
- package/dist/tool.js +16 -26
- package/dist/transcription-client.d.ts +7 -7
- package/dist/transcription.d.ts +314 -265
- package/dist/transcription.js +16 -14
- package/dist/utils/provider-codes.d.ts +3 -0
- package/dist/utils/provider-codes.js +41 -0
- package/dist/video-client.d.ts +7 -7
- package/dist/video-client.js +1 -1
- package/dist/video.d.ts +269 -287
- package/dist/video.js +16 -14
- package/package.json +309 -257
- package/dist/experimental/testing.d.ts +0 -3
- package/dist/experimental/testing.js +0 -3
- package/dist/testing/decision.d.ts +0 -16
- package/dist/testing/decision.js +0 -20
- package/dist/testing/image.d.ts +0 -14
- package/dist/testing/image.js +0 -12
- package/dist/testing/media.d.ts +0 -18
- package/dist/testing/media.js +0 -36
- package/dist/testing/script.d.ts +0 -28
- package/dist/testing/script.js +0 -60
- package/dist/testing/speech.d.ts +0 -14
- package/dist/testing/speech.js +0 -12
- package/dist/testing/transcription.d.ts +0 -14
- package/dist/testing/transcription.js +0 -12
- package/dist/testing/video.d.ts +0 -14
- package/dist/testing/video.js +0 -12
package/dist/loop.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import { AIError, LLMResponse, Message, Usage, LLMEvent, type FinishReasonDetails, type LLMRequest } from "./schema/index.js";
|
|
3
|
+
import type { DispatchResult, PendingCall } from "./tool-runtime.js";
|
|
4
|
+
/**
|
|
5
|
+
* Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
|
|
6
|
+
* gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
|
|
7
|
+
* the output token limit, which may have cut its calls off.
|
|
8
|
+
*/
|
|
9
|
+
export declare const pendingCalls: (response: LLMResponse, answerTool?: string) => ReadonlyArray<PendingCall>;
|
|
10
|
+
/** The step's assistant message followed by one tool message per call, in call order. */
|
|
11
|
+
export declare const stepMessages: (response: LLMResponse, calls: ReadonlyArray<PendingCall>, results: ReadonlyArray<DispatchResult>) => ReadonlyArray<Message>;
|
|
12
|
+
/**
|
|
13
|
+
* The request for the step after `response`, with its messages and tool results appended. A caller's forced
|
|
14
|
+
* `toolChoice` applies to the first step only; with `keepForcedChoice` (the answer tool's) it stays.
|
|
15
|
+
*/
|
|
16
|
+
export declare const nextRequest: (request: LLMRequest, response: LLMResponse, calls: ReadonlyArray<PendingCall>, results: ReadonlyArray<DispatchResult>, keepForcedChoice: boolean) => LLMRequest;
|
|
17
|
+
/** Sum usage across steps. */
|
|
18
|
+
export declare const addUsage: (total: Usage | undefined, step: Usage | undefined) => Usage | undefined;
|
|
19
|
+
/** The result of `collect`: every step of a stream from `stream` or `loop`, folded into one value. */
|
|
20
|
+
export interface Collected {
|
|
21
|
+
/** Text of the final step. */
|
|
22
|
+
readonly text: string;
|
|
23
|
+
/** One response per model call, in order. */
|
|
24
|
+
readonly steps: ReadonlyArray<LLMResponse>;
|
|
25
|
+
/** Each step's assistant message followed by its tool results, ready to append to the request's messages. */
|
|
26
|
+
readonly messages: ReadonlyArray<Message>;
|
|
27
|
+
/** Usage from the terminal `finish`, summed across steps for a loop. */
|
|
28
|
+
readonly usage?: Usage;
|
|
29
|
+
readonly finishReason: FinishReasonDetails;
|
|
30
|
+
}
|
|
31
|
+
type FinishOf<Event> = Extract<Event, {
|
|
32
|
+
readonly type: "finish";
|
|
33
|
+
}>;
|
|
34
|
+
/** `Collected`, plus `object` when the stream was started with `schema`. */
|
|
35
|
+
export type CollectResult<Event> = "object" extends keyof FinishOf<Event> ? Collected & Pick<FinishOf<Event>, "object"> : Collected;
|
|
36
|
+
/** Run a stream from `stream` or `loop` to the end and fold its events into the final result. */
|
|
37
|
+
export declare function collect<Event extends LLMEvent, E, R>(events: Stream.Stream<Event, E, R>): Effect.Effect<CollectResult<Event>, E | AIError, R>;
|
|
38
|
+
export {};
|
package/dist/loop.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import { AIError, AssistantMessage, InvalidProviderOutputError, LLMResponse, ResponseFold, Message, Usage, LLMEvent, ToolCallPart, ToolChoice, } from "./schema/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
|
|
5
|
+
* gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
|
|
6
|
+
* the output token limit, which may have cut its calls off.
|
|
7
|
+
*/
|
|
8
|
+
export const pendingCalls = (response, answerTool) => {
|
|
9
|
+
if (response.finishReason.normalized === "length")
|
|
10
|
+
return [];
|
|
11
|
+
if (answerTool !== undefined && response.toolCalls.some((call) => call.name === answerTool))
|
|
12
|
+
return [];
|
|
13
|
+
return [
|
|
14
|
+
...response.toolCalls.filter((call) => call.providerExecuted !== true).map((call) => ({ call })),
|
|
15
|
+
...response.events.filter(LLMEvent.is.toolInputError).map((event) => ({
|
|
16
|
+
call: invalidCall(event),
|
|
17
|
+
error: `Invalid tool arguments: the input is not valid JSON. Received: ${event.raw}`,
|
|
18
|
+
})),
|
|
19
|
+
];
|
|
20
|
+
};
|
|
21
|
+
/** The call to replay for input that was not valid JSON. Providers require an object input, so it is empty. */
|
|
22
|
+
const invalidCall = (event) => ToolCallPart.make({ id: event.id, name: event.name, namespace: event.namespace, input: {} });
|
|
23
|
+
/** Add the replayed calls for invalid input to the assistant message, so each tool result has its call. */
|
|
24
|
+
const withInvalidCalls = (message, calls) => calls.length === 0 ? message : new AssistantMessage({ ...message, content: [...message.content, ...calls] });
|
|
25
|
+
/** The step's assistant message followed by one tool message per call, in call order. */
|
|
26
|
+
export const stepMessages = (response, calls, results) => [
|
|
27
|
+
withInvalidCalls(response.message, calls.flatMap((item) => (item.error === undefined ? [] : [item.call]))),
|
|
28
|
+
...calls.map((item, i) => Message.tool({
|
|
29
|
+
id: item.call.id,
|
|
30
|
+
name: item.call.name,
|
|
31
|
+
namespace: item.call.namespace,
|
|
32
|
+
result: results[i].result,
|
|
33
|
+
providerMetadata: item.call.providerMetadata,
|
|
34
|
+
})),
|
|
35
|
+
];
|
|
36
|
+
/**
|
|
37
|
+
* The request for the step after `response`, with its messages and tool results appended. A caller's forced
|
|
38
|
+
* `toolChoice` applies to the first step only; with `keepForcedChoice` (the answer tool's) it stays.
|
|
39
|
+
*/
|
|
40
|
+
export const nextRequest = (request, response, calls, results, keepForcedChoice) => ({
|
|
41
|
+
...request,
|
|
42
|
+
toolChoice: !keepForcedChoice && (request.toolChoice?.type === "required" || request.toolChoice?.type === "tool")
|
|
43
|
+
? new ToolChoice({ type: "auto", disableParallelToolUse: request.toolChoice.disableParallelToolUse })
|
|
44
|
+
: request.toolChoice,
|
|
45
|
+
messages: [...request.messages, ...stepMessages(response, calls, results)],
|
|
46
|
+
});
|
|
47
|
+
/** Sum usage across steps. */
|
|
48
|
+
export const addUsage = (total, step) => {
|
|
49
|
+
if (total === undefined || step === undefined)
|
|
50
|
+
return total ?? step;
|
|
51
|
+
const sum = (key) => (total[key] === undefined && step[key] === undefined ? undefined : (total[key] ?? 0) + (step[key] ?? 0));
|
|
52
|
+
return new Usage({
|
|
53
|
+
// Context size describes the latest call, not a running total.
|
|
54
|
+
contextTokens: step.contextTokens ?? total.contextTokens,
|
|
55
|
+
inputTokens: sum("inputTokens"),
|
|
56
|
+
outputTokens: sum("outputTokens"),
|
|
57
|
+
nonCachedInputTokens: sum("nonCachedInputTokens"),
|
|
58
|
+
cacheReadInputTokens: sum("cacheReadInputTokens"),
|
|
59
|
+
cacheWriteInputTokens: sum("cacheWriteInputTokens"),
|
|
60
|
+
reasoningTokens: sum("reasoningTokens"),
|
|
61
|
+
totalTokens: sum("totalTokens"),
|
|
62
|
+
cost: sum("cost"),
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
export function collect(events) {
|
|
66
|
+
return Effect.suspend(() => {
|
|
67
|
+
const steps = [];
|
|
68
|
+
const messages = [];
|
|
69
|
+
let step = ResponseFold.empty();
|
|
70
|
+
// Between a `step-finish` and the next `step-start`, tool results come from the loop running tools.
|
|
71
|
+
let betweenSteps = false;
|
|
72
|
+
// The last step's assistant message, and its calls with invalid input that the loop may answer.
|
|
73
|
+
let assistant = -1;
|
|
74
|
+
let invalid = [];
|
|
75
|
+
let finish;
|
|
76
|
+
const close = (reason, usage) => {
|
|
77
|
+
if (step.events.length === 0)
|
|
78
|
+
return;
|
|
79
|
+
const response = new LLMResponse({
|
|
80
|
+
message: step.message,
|
|
81
|
+
events: step.events,
|
|
82
|
+
usage: usage ?? step.usage,
|
|
83
|
+
finishReason: reason,
|
|
84
|
+
});
|
|
85
|
+
steps.push(response);
|
|
86
|
+
assistant = messages.push(response.message) - 1;
|
|
87
|
+
invalid = step.events.filter(LLMEvent.is.toolInputError).map(invalidCall);
|
|
88
|
+
step = ResponseFold.empty();
|
|
89
|
+
};
|
|
90
|
+
return Stream.runForEach(events, (event) => Effect.sync(() => {
|
|
91
|
+
if (event.type === "finish") {
|
|
92
|
+
close(event.reason, event.usage);
|
|
93
|
+
finish = event;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (event.type === "tool-result" && betweenSteps) {
|
|
97
|
+
const call = invalid.find((item) => item.id === event.id);
|
|
98
|
+
const previous = messages[assistant];
|
|
99
|
+
if (call && previous.role === "assistant")
|
|
100
|
+
messages[assistant] = withInvalidCalls(previous, [call]);
|
|
101
|
+
messages.push(Message.tool({
|
|
102
|
+
id: event.id,
|
|
103
|
+
name: event.name,
|
|
104
|
+
namespace: event.namespace,
|
|
105
|
+
result: event.result,
|
|
106
|
+
providerMetadata: event.providerMetadata,
|
|
107
|
+
}));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (event.type === "step-start")
|
|
111
|
+
betweenSteps = false;
|
|
112
|
+
step = ResponseFold.reduce(step, event);
|
|
113
|
+
if (event.type !== "step-finish")
|
|
114
|
+
return;
|
|
115
|
+
close(event.reason, event.usage);
|
|
116
|
+
betweenSteps = true;
|
|
117
|
+
})).pipe(Effect.flatMap(() => {
|
|
118
|
+
if (finish === undefined)
|
|
119
|
+
return Effect.fail(new AIError({
|
|
120
|
+
reason: new InvalidProviderOutputError({
|
|
121
|
+
message: "The stream ended without a finish event.",
|
|
122
|
+
classification: "incomplete-stream",
|
|
123
|
+
}),
|
|
124
|
+
}));
|
|
125
|
+
const result = {
|
|
126
|
+
text: steps.at(-1)?.text ?? "",
|
|
127
|
+
steps,
|
|
128
|
+
messages,
|
|
129
|
+
usage: finish.usage,
|
|
130
|
+
finishReason: finish.reason,
|
|
131
|
+
...("object" in finish ? { object: finish.object } : {}),
|
|
132
|
+
};
|
|
133
|
+
return Effect.succeed(result);
|
|
134
|
+
}));
|
|
135
|
+
});
|
|
136
|
+
}
|
package/dist/media-model.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { Effect } from "effect";
|
|
|
2
2
|
import { Endpoint } from "./route/endpoint.js";
|
|
3
3
|
import { MediaRoute } from "./route/media.js";
|
|
4
4
|
import type { MediaProtocol } from "./route/media-protocol.js";
|
|
5
|
-
import { AIError,
|
|
5
|
+
import { AIError, ModelID, ProviderID, type HttpOptions, type ProviderOptions } from "./schema/index.js";
|
|
6
6
|
/**
|
|
7
7
|
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
|
|
8
8
|
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
|
package/dist/media-model.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import { Endpoint } from "./route/endpoint.js";
|
|
3
3
|
import { MediaRoute } from "./route/media.js";
|
|
4
|
-
import { AIError,
|
|
4
|
+
import { AIError, InvalidRequestError, ModelID, ProviderID, } from "./schema/index.js";
|
|
5
5
|
/**
|
|
6
6
|
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
|
|
7
7
|
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
|
|
@@ -41,10 +41,12 @@ const isQueuedInput = (route) => route.protocol.kind === "queued";
|
|
|
41
41
|
/** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
|
|
42
42
|
export const tryRequest = (make) => Effect.try({
|
|
43
43
|
try: make,
|
|
44
|
-
catch: (error) =>
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
catch: (error) => error instanceof AIError
|
|
45
|
+
? error
|
|
46
|
+
: new AIError({
|
|
47
|
+
reason: new InvalidRequestError({
|
|
48
|
+
message: error instanceof Error ? error.message : String(error),
|
|
49
|
+
cause: error,
|
|
50
|
+
}),
|
|
48
51
|
}),
|
|
49
|
-
}),
|
|
50
52
|
});
|
package/dist/media.d.ts
CHANGED
|
@@ -200,6 +200,15 @@ export declare const ref: (provider: string | ProviderID, id: string, mediaType?
|
|
|
200
200
|
export declare const parseDataUrl: (value: string, options?: AssetOptions) => Asset | undefined;
|
|
201
201
|
/** Parse a `data:<mime>;base64,<data>` URL. Malformed input throws a typed `AIError` because constructors are sync. */
|
|
202
202
|
export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => Asset;
|
|
203
|
+
/** Plain file data: bytes, a URL, or a string holding a data URL, an http(s) URL or base64. */
|
|
204
|
+
export type Data = Uint8Array | ArrayBuffer | URL | string;
|
|
205
|
+
/** What file inputs accept: an `Asset` or plain `Data`. */
|
|
206
|
+
export type Input = Asset | Data;
|
|
207
|
+
/**
|
|
208
|
+
* Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
|
|
209
|
+
* bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
|
|
210
|
+
*/
|
|
211
|
+
export declare const make: (input: Input, mediaType?: string) => Asset;
|
|
203
212
|
/** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
|
|
204
213
|
export declare const file: (path: string, options?: AssetOptions) => Effect.Effect<Asset, AIError, FileSystem.FileSystem>;
|
|
205
214
|
/** Materialize an asset and write its bytes through `FileSystem`. */
|
package/dist/media.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export * as Media from "./media.js";
|
|
2
|
-
import { Effect, FileSystem, Schema, SchemaGetter } from "effect";
|
|
2
|
+
import { Effect, FileSystem, Result, Schema, SchemaGetter } from "effect";
|
|
3
3
|
import { Base64 } from "effect/encoding";
|
|
4
4
|
import { HttpClientRequest } from "effect/http";
|
|
5
5
|
import { ProviderID } from "./schema/ids.js";
|
|
@@ -191,7 +191,7 @@ export const url = (value, options) => {
|
|
|
191
191
|
return from({ type: "url", url: value, mediaType, expiresAt }, rest);
|
|
192
192
|
};
|
|
193
193
|
export const ref = (provider, id, mediaType, options) => from({ type: "ref", provider: ProviderID.make(provider), id, mediaType }, options);
|
|
194
|
-
const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/
|
|
194
|
+
const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/is;
|
|
195
195
|
/** Parse a `data:<mime>;base64,<data>` URL, or `undefined` when the value is not a base64 data URL. */
|
|
196
196
|
export const parseDataUrl = (value, options) => {
|
|
197
197
|
const match = DATA_URL.exec(value);
|
|
@@ -204,6 +204,41 @@ export const fromDataUrl = (dataUrl, options) => {
|
|
|
204
204
|
throw invalid("Media data URLs must contain a MIME type and base64 data");
|
|
205
205
|
return asset;
|
|
206
206
|
};
|
|
207
|
+
/**
|
|
208
|
+
* Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
|
|
209
|
+
* bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
|
|
210
|
+
*/
|
|
211
|
+
export const make = (input, mediaType) => {
|
|
212
|
+
if (input instanceof Asset)
|
|
213
|
+
return input;
|
|
214
|
+
if (input instanceof ArrayBuffer)
|
|
215
|
+
return make(new Uint8Array(input), mediaType);
|
|
216
|
+
if (input instanceof Uint8Array)
|
|
217
|
+
return bytes(input, mediaType ?? requireMediaType(detectMediaType(input)));
|
|
218
|
+
const value = input instanceof URL ? input.href : input;
|
|
219
|
+
if (/^data:/i.test(value)) {
|
|
220
|
+
const match = DATA_URL.exec(value);
|
|
221
|
+
if (match === null)
|
|
222
|
+
throw invalid("Media data URLs must contain a MIME type and base64 data");
|
|
223
|
+
return base64(match[2], mediaType ?? match[1]);
|
|
224
|
+
}
|
|
225
|
+
if (input instanceof URL || /^https?:\/\//i.test(value))
|
|
226
|
+
return url(value, { mediaType });
|
|
227
|
+
if (!BASE64.test(value))
|
|
228
|
+
throw invalid("Media strings must be base64, a data URL or an http(s) URL; read files with Media.file");
|
|
229
|
+
return base64(value, mediaType ?? requireMediaType(sniffBase64(value)));
|
|
230
|
+
};
|
|
231
|
+
const BASE64 = /^[A-Za-z0-9+/\-_\s]*={0,2}\s*$/;
|
|
232
|
+
// 64 characters decode to 48 bytes, enough for every signature `detectMediaType` reads.
|
|
233
|
+
const sniffBase64 = (value) => {
|
|
234
|
+
const head = Result.getOrUndefined(Base64.decode(value.slice(0, 64)));
|
|
235
|
+
return head === undefined ? undefined : detectMediaType(head);
|
|
236
|
+
};
|
|
237
|
+
const requireMediaType = (detected) => {
|
|
238
|
+
if (detected === undefined)
|
|
239
|
+
throw invalid("Media data needs a mediaType because its type cannot be detected");
|
|
240
|
+
return detected;
|
|
241
|
+
};
|
|
207
242
|
/** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
|
|
208
243
|
export const file = (path, options) => Effect.gen(function* () {
|
|
209
244
|
const fs = yield* FileSystem.FileSystem;
|
|
@@ -29,10 +29,14 @@ declare const Options: Schema.Struct<{
|
|
|
29
29
|
export type OptionsInput = typeof Options.Type;
|
|
30
30
|
export declare const compatibility: {
|
|
31
31
|
maxTokensField: "max_completion_tokens";
|
|
32
|
-
supportsStrictMode: false;
|
|
33
32
|
reasoningField: string;
|
|
34
33
|
zaiToolStream: false;
|
|
35
34
|
};
|
|
35
|
+
export declare const capabilities: {
|
|
36
|
+
tools: {
|
|
37
|
+
strict: false;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
36
40
|
export declare const protocol: Protocol<{
|
|
37
41
|
readonly model: string;
|
|
38
42
|
readonly messages: readonly ({
|
|
@@ -133,6 +137,7 @@ export declare const protocol: Protocol<{
|
|
|
133
137
|
readonly reasoning?: string | undefined;
|
|
134
138
|
readonly reasoning_text?: string | undefined;
|
|
135
139
|
readonly reasoning_details?: unknown;
|
|
140
|
+
readonly reasoning_opaque?: string | undefined;
|
|
136
141
|
})[];
|
|
137
142
|
readonly tools?: readonly ({
|
|
138
143
|
readonly type: "function";
|
|
@@ -239,6 +244,7 @@ export declare const protocol: Protocol<{
|
|
|
239
244
|
readonly reasoning?: string | null | undefined;
|
|
240
245
|
readonly reasoning_text?: string | null | undefined;
|
|
241
246
|
readonly reasoning_details?: unknown;
|
|
247
|
+
readonly reasoning_opaque?: string | null | undefined;
|
|
242
248
|
readonly tool_calls?: readonly {
|
|
243
249
|
readonly index?: number | null | undefined;
|
|
244
250
|
readonly id?: string | null | undefined;
|
|
@@ -264,6 +270,7 @@ export declare const protocol: Protocol<{
|
|
|
264
270
|
readonly prompt_cache_hit_tokens?: number | null | undefined;
|
|
265
271
|
readonly cache_read_input_tokens?: number | null | undefined;
|
|
266
272
|
readonly cache_created_input_tokens?: number | null | undefined;
|
|
273
|
+
readonly reasoning_tokens?: number | null | undefined;
|
|
267
274
|
readonly prompt_tokens_details?: {
|
|
268
275
|
readonly [x: string]: unknown;
|
|
269
276
|
readonly cached_tokens?: number | null | undefined;
|
|
@@ -286,6 +293,7 @@ export declare const protocol: Protocol<{
|
|
|
286
293
|
readonly prompt_cache_hit_tokens?: number | null | undefined;
|
|
287
294
|
readonly cache_read_input_tokens?: number | null | undefined;
|
|
288
295
|
readonly cache_created_input_tokens?: number | null | undefined;
|
|
296
|
+
readonly reasoning_tokens?: number | null | undefined;
|
|
289
297
|
readonly prompt_tokens_details?: {
|
|
290
298
|
readonly [x: string]: unknown;
|
|
291
299
|
readonly cached_tokens?: number | null | undefined;
|
|
@@ -29,10 +29,10 @@ const Options = Schema.Struct({
|
|
|
29
29
|
});
|
|
30
30
|
export const compatibility = {
|
|
31
31
|
maxTokensField: "max_completion_tokens",
|
|
32
|
-
supportsStrictMode: false,
|
|
33
32
|
reasoningField: "reasoning_content",
|
|
34
33
|
zaiToolStream: false,
|
|
35
34
|
};
|
|
35
|
+
export const capabilities = { tools: { strict: false } };
|
|
36
36
|
export const protocol = Protocol.make({
|
|
37
37
|
id: "alibaba-chat",
|
|
38
38
|
body: {
|
|
@@ -58,7 +58,7 @@ export const protocol = Protocol.make({
|
|
|
58
58
|
// Alibaba also rejects an explicit budget that is not below `max_completion_tokens`.
|
|
59
59
|
thinking_budget: opts.thinkingBudget === undefined
|
|
60
60
|
? undefined
|
|
61
|
-
: ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.
|
|
61
|
+
: ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.maxTokens),
|
|
62
62
|
preserve_thinking: opts.preserveThinking,
|
|
63
63
|
clear_thinking: opts.clearThinking,
|
|
64
64
|
thinking: opts.thinking,
|
|
@@ -66,7 +66,7 @@ export const protocol = Protocol.make({
|
|
|
66
66
|
parallel_tool_calls: opts.parallelToolCalls ??
|
|
67
67
|
(req.toolChoice?.disableParallelToolUse === undefined ? undefined : !req.toolChoice.disableParallelToolUse),
|
|
68
68
|
repetition_penalty: opts.repetitionPenalty,
|
|
69
|
-
top_k: req.
|
|
69
|
+
top_k: req.topK,
|
|
70
70
|
response_format: opts.responseFormat,
|
|
71
71
|
enable_search: opts.enableSearch,
|
|
72
72
|
search_options: opts.searchOptions,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ImageModel, ImageResponse, type
|
|
1
|
+
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js";
|
|
2
2
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
3
3
|
import { MediaRoute } from "../route/media.js";
|
|
4
4
|
export declare const PATH = "/services/aigc/multimodal-generation/generation";
|
|
@@ -13,7 +13,7 @@ export type AlibabaImageOptions = {
|
|
|
13
13
|
readonly thinkingMode?: boolean;
|
|
14
14
|
readonly enableSequential?: boolean;
|
|
15
15
|
} & Record<string, unknown>;
|
|
16
|
-
export type Request =
|
|
16
|
+
export type Request = ImageRequest<ImageModel<AlibabaImageOptions>>;
|
|
17
17
|
export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
|
|
18
18
|
export declare const model: (input: MediaRoute.ModelInput) => ImageModel<AlibabaImageOptions>;
|
|
19
19
|
export declare const AlibabaImages: {
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import { Protocol } from "../route/protocol.js";
|
|
3
|
-
import { LLMRequest } from "../schema/index.js";
|
|
4
3
|
import { AnthropicMessages } from "./anthropic-messages.js";
|
|
5
4
|
import { ProviderShared } from "./shared.js";
|
|
6
5
|
import { OpenResponsesOptions } from "./utils/open-responses-options.js";
|
|
@@ -22,9 +21,10 @@ export const protocol = Protocol.make({
|
|
|
22
21
|
from: Effect.fn("AlibabaMessages.fromRequest")(function* (req) {
|
|
23
22
|
const opts = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(req.providerOptions ?? {});
|
|
24
23
|
// Model Studio accepts enabled thinking without Anthropic's mandatory token budget.
|
|
25
|
-
const body = yield* AnthropicMessages.protocol.body.from(
|
|
24
|
+
const body = yield* AnthropicMessages.protocol.body.from({
|
|
25
|
+
...req,
|
|
26
26
|
providerOptions: { ...req.providerOptions, thinking: undefined },
|
|
27
|
-
})
|
|
27
|
+
});
|
|
28
28
|
const budget = opts.thinking?.budgetTokens ?? opts.thinking?.budget_tokens;
|
|
29
29
|
return {
|
|
30
30
|
...body,
|
|
@@ -32,7 +32,7 @@ const adapter = {
|
|
|
32
32
|
restoreHostedToolItem: (item) => (Schema.is(WebExtractorItem)(item) ? item : undefined),
|
|
33
33
|
};
|
|
34
34
|
const tools = {
|
|
35
|
-
web_search_call:
|
|
35
|
+
web_search_call: ResponsesHostedTools.common.web_search_call,
|
|
36
36
|
code_interpreter_call: { name: "code_interpreter", input: (item) => ({ code: item.code }) },
|
|
37
37
|
};
|
|
38
38
|
export const protocol = Protocol.make({
|
|
@@ -55,24 +55,12 @@ export const protocol = Protocol.make({
|
|
|
55
55
|
};
|
|
56
56
|
}),
|
|
57
57
|
},
|
|
58
|
-
stream: {
|
|
59
|
-
event
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if (event.item.type === "web_extractor_call") {
|
|
66
|
-
const item = yield* Schema.decodeUnknownEffect(WebExtractorItem)(event.item).pipe(Effect.mapError((cause) => ProviderShared.eventError(adapter.id, "Alibaba returned an invalid web extraction item", ProviderShared.encodeJson(event), cause)));
|
|
67
|
-
return yield* ResponsesHostedTools.onDone(state, item, {
|
|
68
|
-
web_extractor_call: { name: "web_extractor", input: () => ({ urls: item.urls, goal: item.goal }) },
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
if (ResponsesHostedTools.isItem(event.item, tools))
|
|
72
|
-
return yield* ResponsesHostedTools.onDone(state, event.item, tools);
|
|
73
|
-
return yield* OpenResponses.step(state, event);
|
|
74
|
-
}),
|
|
75
|
-
terminal: OpenResponses.terminal,
|
|
76
|
-
},
|
|
58
|
+
stream: ResponsesHostedTools.stream(adapter, tools, (state, event) => {
|
|
59
|
+
if (event.type !== "response.output_item.done" || event.item?.type !== "web_extractor_call")
|
|
60
|
+
return undefined;
|
|
61
|
+
return Schema.decodeUnknownEffect(WebExtractorItem)(event.item).pipe(Effect.mapError((cause) => ProviderShared.eventError(adapter.id, "Alibaba returned an invalid web extraction item", ProviderShared.encodeJson(event), cause)), Effect.flatMap((item) => ResponsesHostedTools.onDone(state, item, {
|
|
62
|
+
web_extractor_call: { name: "web_extractor", input: () => ({ urls: item.urls, goal: item.goal }) },
|
|
63
|
+
})));
|
|
64
|
+
}),
|
|
77
65
|
});
|
|
78
66
|
export * as AlibabaResponses from "./alibaba-responses.js";
|
|
@@ -3,7 +3,7 @@ import { Route } from "../route/client.js";
|
|
|
3
3
|
import { Framing } from "../route/framing.js";
|
|
4
4
|
import { Protocol } from "../route/protocol.js";
|
|
5
5
|
import { HttpTransport } from "../route/transport/index.js";
|
|
6
|
-
import { AIError, LLMRequest, type ProviderOptions } from "../schema/index.js";
|
|
6
|
+
import { AIError, type LLMRequest, type ProviderOptions } from "../schema/index.js";
|
|
7
7
|
import { Lifecycle } from "./utils/lifecycle.js";
|
|
8
8
|
import { ToolStream } from "./utils/tool-stream.js";
|
|
9
9
|
export declare const DEFAULT_BASE_URL = "https://api.anthropic.com/v1";
|