@opencode/ai 0.0.0-dev-57 → 0.0.0-dev-65
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 +20 -10
- package/dist/index.d.ts +24 -2
- package/dist/index.js +20 -1
- package/dist/protocols/openai-images.js +4 -3
- package/dist/protocols/utils/media-input.d.ts +4 -1
- package/dist/protocols/utils/media-input.js +8 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -55,22 +55,19 @@ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployme
|
|
|
55
55
|
`stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
|
|
56
56
|
tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs. `until` is checked
|
|
57
57
|
after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
|
|
58
|
-
them
|
|
58
|
+
them. `AI.tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and
|
|
59
|
+
`signal` aborts when the loop is interrupted.
|
|
60
|
+
`Tool.make` from `@opencode/ai/effect` is the Effect form, with a validated `success` schema:
|
|
59
61
|
|
|
60
62
|
```ts
|
|
61
63
|
import { readFile } from "node:fs/promises"
|
|
62
|
-
import {
|
|
63
|
-
import {
|
|
64
|
+
import { Schema } from "effect"
|
|
65
|
+
import { AI } from "@opencode/ai"
|
|
64
66
|
|
|
65
|
-
const read_file =
|
|
67
|
+
const read_file = AI.tool({
|
|
66
68
|
description: "Read a UTF-8 file.",
|
|
67
69
|
parameters: Schema.Struct({ path: Schema.String }),
|
|
68
|
-
|
|
69
|
-
execute: ({ path }) =>
|
|
70
|
-
Effect.tryPromise({
|
|
71
|
-
try: () => readFile(path, "utf8"),
|
|
72
|
-
catch: (error) => new ToolFailure({ message: `Failed to read ${path}`, error }),
|
|
73
|
-
}),
|
|
70
|
+
execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
|
|
74
71
|
})
|
|
75
72
|
|
|
76
73
|
const events = ai.llm.loop({
|
|
@@ -84,6 +81,19 @@ for await (const event of events) {
|
|
|
84
81
|
}
|
|
85
82
|
```
|
|
86
83
|
|
|
84
|
+
### Structured output
|
|
85
|
+
|
|
86
|
+
`generateObject` forces a tool call and decodes its input against `schema`; pass `jsonSchema` instead for an
|
|
87
|
+
unvalidated `unknown` object:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const { object } = await ai.llm.generateObject({
|
|
91
|
+
model,
|
|
92
|
+
prompt: "Pick a city.",
|
|
93
|
+
schema: Schema.Struct({ city: Schema.String }),
|
|
94
|
+
})
|
|
95
|
+
```
|
|
96
|
+
|
|
87
97
|
### Raw provider events
|
|
88
98
|
|
|
89
99
|
Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Effect, Layer } from "effect";
|
|
1
|
+
import { Effect, Layer, Schema } from "effect";
|
|
2
2
|
import { AIClient } from "./ai-client.js";
|
|
3
3
|
import { type DecisionModel, type DecisionQuestions, type DecisionRequestInput } from "./decision.js";
|
|
4
4
|
import type { AwaitOptions, Event, Snapshot } from "./generation.js";
|
|
@@ -7,9 +7,10 @@ import { LLM } from "./effect.js";
|
|
|
7
7
|
import { Media } from "./media.js";
|
|
8
8
|
import { RequestExecutor } from "./route/executor.js";
|
|
9
9
|
import { LanguageModel, type LLMRequest } from "./schema/index.js";
|
|
10
|
-
import type { LoopInput, RequestInput } from "./llm.js";
|
|
10
|
+
import type { GenerateObjectDynamicOptions, GenerateObjectOptions, GenerateObjectResponse, LoopInput, RequestInput } from "./llm.js";
|
|
11
11
|
import { type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js";
|
|
12
12
|
import { type TranscriptionModel, type TranscriptionRequest, type TranscriptionRequestInput } from "./transcription.js";
|
|
13
|
+
import { Tool, type ToolExecuteContext, type ToolSchema } from "./tool.js";
|
|
13
14
|
import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js";
|
|
14
15
|
/**
|
|
15
16
|
* Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
|
|
@@ -492,6 +493,11 @@ export declare const make: (options?: Options) => {
|
|
|
492
493
|
readonly text: string | null;
|
|
493
494
|
readonly encrypted?: never;
|
|
494
495
|
}))>;
|
|
496
|
+
/** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */
|
|
497
|
+
generateObject: {
|
|
498
|
+
<const Model extends LanguageModel, S extends ToolSchema<any>>(input: GenerateObjectOptions<S, Model>, options?: RunOptions): Promise<GenerateObjectResponse<Schema.Schema.Type<S>>>;
|
|
499
|
+
<const Model extends LanguageModel>(input: GenerateObjectDynamicOptions<Model>, options?: RunOptions): Promise<GenerateObjectResponse<unknown>>;
|
|
500
|
+
};
|
|
495
501
|
};
|
|
496
502
|
image: {
|
|
497
503
|
request: typeof import("./image.js").request;
|
|
@@ -756,6 +762,17 @@ export declare const make: (options?: Options) => {
|
|
|
756
762
|
dispose: () => Promise<void>;
|
|
757
763
|
};
|
|
758
764
|
export type Client = ReturnType<typeof make>;
|
|
765
|
+
/**
|
|
766
|
+
* Promise counterpart of `Tool.make` for `ai.llm.loop`. A throw or rejection becomes the error result the model sees, the
|
|
767
|
+
* returned value is sent unvalidated (`undefined` as `null`), and `signal` aborts when the loop is interrupted.
|
|
768
|
+
*/
|
|
769
|
+
export declare const tool: <Parameters extends ToolSchema<any>>(config: {
|
|
770
|
+
readonly description: string;
|
|
771
|
+
readonly parameters: Parameters;
|
|
772
|
+
readonly execute: (params: Schema.Schema.Type<Parameters>, context: Partial<ToolExecuteContext> & {
|
|
773
|
+
readonly signal: AbortSignal;
|
|
774
|
+
}) => unknown;
|
|
775
|
+
}) => Tool.ExecutableTool<Parameters, Schema.Unknown>;
|
|
759
776
|
/** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */
|
|
760
777
|
export declare const ai: {
|
|
761
778
|
run: <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) => Promise<A>;
|
|
@@ -1210,6 +1227,11 @@ export declare const ai: {
|
|
|
1210
1227
|
readonly text: string | null;
|
|
1211
1228
|
readonly encrypted?: never;
|
|
1212
1229
|
}))>;
|
|
1230
|
+
/** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */
|
|
1231
|
+
generateObject: {
|
|
1232
|
+
<const Model extends LanguageModel, S extends ToolSchema<any>>(input: GenerateObjectOptions<S, Model>, options?: RunOptions): Promise<GenerateObjectResponse<Schema.Schema.Type<S>>>;
|
|
1233
|
+
<const Model extends LanguageModel>(input: GenerateObjectDynamicOptions<Model>, options?: RunOptions): Promise<GenerateObjectResponse<unknown>>;
|
|
1234
|
+
};
|
|
1213
1235
|
};
|
|
1214
1236
|
image: {
|
|
1215
1237
|
request: typeof import("./image.js").request;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Effect, Layer, ManagedRuntime, Stream } from "effect";
|
|
1
|
+
import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect";
|
|
2
2
|
import { AIClient } from "./ai-client.js";
|
|
3
3
|
import { Decision } from "./decision.js";
|
|
4
4
|
import { Image } from "./image.js";
|
|
@@ -8,6 +8,7 @@ import { RequestExecutor } from "./route/executor.js";
|
|
|
8
8
|
import { AIError, InvalidRequestError, LanguageModel } from "./schema/index.js";
|
|
9
9
|
import { Speech } from "./speech.js";
|
|
10
10
|
import { Transcription, } from "./transcription.js";
|
|
11
|
+
import { Tool, ToolFailure } from "./tool.js";
|
|
11
12
|
import { fileMediaType } from "./utils/media-type.js";
|
|
12
13
|
import { Video } from "./video.js";
|
|
13
14
|
// Fails with `signal.reason` so aborted calls reject and aborted streams throw like `fetch`: an `AbortError` by default.
|
|
@@ -27,6 +28,9 @@ export const make = (options = {}) => {
|
|
|
27
28
|
/** Run any package Effect (for example `LLMClient.compact(...)`) inside this runtime. */
|
|
28
29
|
const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
|
|
29
30
|
const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
|
|
31
|
+
function generateObject(input, options) {
|
|
32
|
+
return run("schema" in input ? LLM.generateObject(input) : LLM.generateObject(input), options);
|
|
33
|
+
}
|
|
30
34
|
const handle = (generation) => ({
|
|
31
35
|
...generation.snapshot,
|
|
32
36
|
token: generation.token,
|
|
@@ -68,6 +72,8 @@ export const make = (options = {}) => {
|
|
|
68
72
|
stream: (input, options) => iterate(LLM.stream(input), options),
|
|
69
73
|
/** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */
|
|
70
74
|
loop: (input, options) => iterate(LLM.loop(input), options),
|
|
75
|
+
/** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */
|
|
76
|
+
generateObject,
|
|
71
77
|
},
|
|
72
78
|
image: {
|
|
73
79
|
request: Image.request,
|
|
@@ -103,6 +109,19 @@ export const make = (options = {}) => {
|
|
|
103
109
|
};
|
|
104
110
|
};
|
|
105
111
|
const fileError = (message, cause) => new AIError({ reason: new InvalidRequestError({ message, cause }) });
|
|
112
|
+
/**
|
|
113
|
+
* Promise counterpart of `Tool.make` for `ai.llm.loop`. A throw or rejection becomes the error result the model sees, the
|
|
114
|
+
* returned value is sent unvalidated (`undefined` as `null`), and `signal` aborts when the loop is interrupted.
|
|
115
|
+
*/
|
|
116
|
+
export const tool = (config) => Tool.make({
|
|
117
|
+
description: config.description,
|
|
118
|
+
parameters: config.parameters,
|
|
119
|
+
success: Schema.Unknown,
|
|
120
|
+
execute: (params, context) => Effect.tryPromise({
|
|
121
|
+
try: async (signal) => (await config.execute(params, { ...context, signal })) ?? null,
|
|
122
|
+
catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
|
|
123
|
+
}),
|
|
124
|
+
});
|
|
106
125
|
/** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */
|
|
107
126
|
export const ai = make();
|
|
108
127
|
export * as AI from "./index.js";
|
|
@@ -6,7 +6,7 @@ import { Framing } from "../route/framing.js";
|
|
|
6
6
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
7
7
|
import { MediaRoute } from "../route/media.js";
|
|
8
8
|
import { AIError, mergeJsonRecords, ProviderID } from "../schema/index.js";
|
|
9
|
-
import { ProviderShared } from "./shared.js";
|
|
9
|
+
import { optionalNull, ProviderShared } from "./shared.js";
|
|
10
10
|
import { ImageSizing } from "./utils/image-sizing.js";
|
|
11
11
|
import { MediaInput } from "./utils/media-input.js";
|
|
12
12
|
const route = MediaProtocol.identity({ id: "openai-images", name: "OpenAI Images", provider: "openai" });
|
|
@@ -31,7 +31,8 @@ const Settings = {
|
|
|
31
31
|
background: Schema.optional(Schema.String),
|
|
32
32
|
};
|
|
33
33
|
const OpenAIImageResponse = Schema.Struct({
|
|
34
|
-
|
|
34
|
+
// `response_format` picks `b64_json` or `url`; DALL·E and many compatible hosts default to `url`.
|
|
35
|
+
data: Schema.Array(Schema.Struct({ b64_json: optionalNull(Schema.String), url: optionalNull(Schema.String) })),
|
|
35
36
|
...Settings,
|
|
36
37
|
usage: Schema.optional(Usage),
|
|
37
38
|
});
|
|
@@ -213,7 +214,7 @@ const onDocument = Effect.fnUntraced(function* (frame) {
|
|
|
213
214
|
// Compatible hosts may omit `output_format` and ignore the requested one, so the bytes decide unreported types.
|
|
214
215
|
const format = decoded.output_format;
|
|
215
216
|
const mediaType = format === undefined ? undefined : `image/${format}`;
|
|
216
|
-
const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.
|
|
217
|
+
const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.imageOutput(invalid, `${route.name} result ${index}`, item, mediaType, {
|
|
217
218
|
info: info(format, decoded.size),
|
|
218
219
|
}));
|
|
219
220
|
if (images.length === 0)
|
|
@@ -11,7 +11,10 @@ export declare const query: (route: string, values: Record<string, unknown>) =>
|
|
|
11
11
|
export declare const refID: (asset: Media.Asset, provider: ProviderID) => string | undefined;
|
|
12
12
|
/** Decode a provider's base64 output once into an owned `bytes` asset, sniffing the type when it is not declared. */
|
|
13
13
|
export declare const decodedAsset: (invalid: (message: string, cause?: unknown) => AIError, label: string, data: string, mediaType: string | undefined, options?: Media.AssetOptions) => Effect.Effect<Media.Asset, AIError, never>;
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* One image of an OpenAI-shaped `data` array, which carries `b64_json`, a `url`, or both. `b64_json` wins; a `data:`
|
|
16
|
+
* URL decodes inline with its own media type, and any other URL stays a URL asset for the caller to download.
|
|
17
|
+
*/
|
|
15
18
|
export declare const imageOutput: (invalid: (message: string, cause?: unknown) => AIError, label: string, item: {
|
|
16
19
|
readonly b64_json?: string | null;
|
|
17
20
|
readonly url?: string | null;
|
|
@@ -31,10 +31,17 @@ export const query = (route, values) => {
|
|
|
31
31
|
export const refID = (asset, provider) => asset.source.type === "ref" && asset.source.provider === provider ? asset.source.id : undefined;
|
|
32
32
|
/** Decode a provider's base64 output once into an owned `bytes` asset, sniffing the type when it is not declared. */
|
|
33
33
|
export const decodedAsset = (invalid, label, data, mediaType, options) => Effect.fromResult(Base64.decode(data)).pipe(Effect.mapError((cause) => invalid(`${label} contains invalid base64 data`, cause)), Effect.map((bytes) => Media.bytes(bytes, mediaType, options)));
|
|
34
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* One image of an OpenAI-shaped `data` array, which carries `b64_json`, a `url`, or both. `b64_json` wins; a `data:`
|
|
36
|
+
* URL decodes inline with its own media type, and any other URL stays a URL asset for the caller to download.
|
|
37
|
+
*/
|
|
35
38
|
export const imageOutput = (invalid, label, item, mediaType, options) => {
|
|
36
39
|
if (item.b64_json)
|
|
37
40
|
return decodedAsset(invalid, label, item.b64_json, mediaType, options);
|
|
41
|
+
if (item.url?.startsWith("data:")) {
|
|
42
|
+
const asset = Media.parseDataUrl(item.url, options);
|
|
43
|
+
return asset === undefined ? Effect.fail(invalid(`${label} has an invalid data URL`)) : Effect.succeed(asset);
|
|
44
|
+
}
|
|
38
45
|
if (item.url)
|
|
39
46
|
return Effect.succeed(Media.url(item.url, { ...options, mediaType }));
|
|
40
47
|
return Effect.fail(invalid(`${label} has neither image data nor a URL`));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
-
"version": "0.0.0-dev-
|
|
3
|
+
"version": "0.0.0-dev-65",
|
|
4
4
|
"name": "@opencode/ai",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -532,7 +532,7 @@
|
|
|
532
532
|
"devDependencies": {
|
|
533
533
|
"@clack/prompts": "1.0.0-alpha.1",
|
|
534
534
|
"@effect/platform-node": "4.0.1",
|
|
535
|
-
"@opencode/http-recorder": "0.0.0-dev-
|
|
535
|
+
"@opencode/http-recorder": "0.0.0-dev-65",
|
|
536
536
|
"@tsconfig/bun": "1.0.9",
|
|
537
537
|
"@types/bun": "1.4.3",
|
|
538
538
|
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
@@ -542,7 +542,7 @@
|
|
|
542
542
|
"@aws-sdk/credential-providers": "3.1057.0",
|
|
543
543
|
"@smithy/eventstream-codec": "4.2.14",
|
|
544
544
|
"@smithy/util-utf8": "4.2.2",
|
|
545
|
-
"@opencode/schema": "0.0.0-dev-
|
|
545
|
+
"@opencode/schema": "0.0.0-dev-65",
|
|
546
546
|
"aws4fetch": "1.0.20",
|
|
547
547
|
"effect": "4.0.1",
|
|
548
548
|
"google-auth-library": "10.5.0"
|