@effect/ai-cloudflare 4.0.3 → 4.0.5

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/AGENTS.md CHANGED
@@ -370,6 +370,30 @@ Build http clients with the `HttpClient` module.
370
370
  Test handlers through an in-memory typed client with `HttpApiTest`, without
371
371
  starting an HTTP server or touching a real database.
372
372
 
373
+ ## Typed GraphQL clients with `effect/graphql`
374
+
375
+ Use the `effect/graphql` modules to call GraphQL APIs with typed
376
+ operations. Run `graphqlgen` from `@effect/graphql-generator` to generate
377
+ operations from `.graphql` documents, then build a client with
378
+ `GraphQLClient.make` and provide a transport from `GraphQLProtocol`.
379
+
380
+ - **[Getting started with GraphQL clients](./ai-docs/src/52_graphql/10_basics.ts)**:
381
+ Define a query, build a typed client service over HTTP with an auth
382
+ middleware, and page through a cursor connection.
383
+ - **[Testing code that uses a GraphQL client](./ai-docs/src/52_graphql/20_testing.ts)**:
384
+ Replace a client service with `GraphQLClient.layerTest`, answering each
385
+ operation from a handler instead of a server.
386
+ - **[Batching lookups with GraphQLResolver](./ai-docs/src/52_graphql/30_batching.ts)**:
387
+ Collect concurrent lookups by id into one `nodes(ids:)` request with
388
+ `GraphQLResolver`, instead of one request per id.
389
+ - **[Batching single-item lookups with aliases](./ai-docs/src/52_graphql/40_aliased-batching.ts)**:
390
+ When an API has no field that takes a list of keys, `GraphQLResolver.aliased`
391
+ repeats a generated operation under aliases, so concurrent lookups share one
392
+ request and keep their generated types.
393
+ - **[Handling GraphQL errors, retries and rate limits](./ai-docs/src/52_graphql/50_errors-and-retries.ts)**:
394
+ Read rate-limit headers in a middleware, tell GraphQL errors apart by their
395
+ fields, and retry timeouts and rate limits with `Effect.retry`.
396
+
373
397
  ## Working with child processes
374
398
 
375
399
  Use the `effect/process` modules to define child processes and run them with `ChildProcessSpawner`.
package/CLAUDE.md CHANGED
@@ -370,6 +370,30 @@ Build http clients with the `HttpClient` module.
370
370
  Test handlers through an in-memory typed client with `HttpApiTest`, without
371
371
  starting an HTTP server or touching a real database.
372
372
 
373
+ ## Typed GraphQL clients with `effect/graphql`
374
+
375
+ Use the `effect/graphql` modules to call GraphQL APIs with typed
376
+ operations. Run `graphqlgen` from `@effect/graphql-generator` to generate
377
+ operations from `.graphql` documents, then build a client with
378
+ `GraphQLClient.make` and provide a transport from `GraphQLProtocol`.
379
+
380
+ - **[Getting started with GraphQL clients](./ai-docs/src/52_graphql/10_basics.ts)**:
381
+ Define a query, build a typed client service over HTTP with an auth
382
+ middleware, and page through a cursor connection.
383
+ - **[Testing code that uses a GraphQL client](./ai-docs/src/52_graphql/20_testing.ts)**:
384
+ Replace a client service with `GraphQLClient.layerTest`, answering each
385
+ operation from a handler instead of a server.
386
+ - **[Batching lookups with GraphQLResolver](./ai-docs/src/52_graphql/30_batching.ts)**:
387
+ Collect concurrent lookups by id into one `nodes(ids:)` request with
388
+ `GraphQLResolver`, instead of one request per id.
389
+ - **[Batching single-item lookups with aliases](./ai-docs/src/52_graphql/40_aliased-batching.ts)**:
390
+ When an API has no field that takes a list of keys, `GraphQLResolver.aliased`
391
+ repeats a generated operation under aliases, so concurrent lookups share one
392
+ request and keep their generated types.
393
+ - **[Handling GraphQL errors, retries and rate limits](./ai-docs/src/52_graphql/50_errors-and-retries.ts)**:
394
+ Read rate-limit headers in a middleware, tell GraphQL errors apart by their
395
+ fields, and retry timeouts and rate limits with `Effect.retry`.
396
+
373
397
  ## Working with child processes
374
398
 
375
399
  Use the `effect/process` modules to define child processes and run them with `ChildProcessSpawner`.
package/README.md CHANGED
@@ -37,8 +37,23 @@ const program = DecisionModel.decide(Triage, {
37
37
  }).pipe(Effect.provide(Clef))
38
38
  ```
39
39
 
40
+ Pass `images` to include pictures with the input. Clef shows them to the model before the state:
41
+
42
+ ```ts
43
+ declare const screenshotBytes: Uint8Array
44
+
45
+ const withScreenshot = DecisionModel.decide(Triage, {
46
+ input: "Customers report this checkout error.",
47
+ images: [{ mediaType: "image/png", data: screenshotBytes }]
48
+ })
49
+ ```
50
+
51
+ Image `data` may be a `Uint8Array`, a base64 string, or a `data:` URL. Remote URLs fail with `AiError.InvalidUserInputError` because Clef does not fetch them, so download the image first. The API accepts up to 4 PNG, JPEG, or WebP images, each at most 4 MiB and 16 megapixels, with 8 MiB of decoded images in total and a 13 MiB request body.
52
+
40
53
  Use `"clef"` for the larger model. `CloudflareDecisionModel.model` provides a model descriptor with Cloudflare provider metadata. `CloudflareClient.layer` accepts an explicit account ID and redacted API token; `apiUrl` and `transformClient` customize HTTP access.
41
54
 
55
+ Instructions and descriptions can be strings, JSON objects, or JSON arrays. A rating level with a structured description takes an explicit `label`, which answers use.
56
+
42
57
  The client unwraps Cloudflare's REST envelope and maps failures to `AiError`. It does not retry automatically. Rate-limit errors include `Retry-After` when provided. The decision model validates answers and rescales small probability drift from four-decimal rounding.
43
58
 
44
59
  Cloudflare limits each request to 64 questions, classification to 2–255 choices, and ratings to 2–10 levels. See the [Clef API documentation](https://developers.cloudflare.com/workers-ai/models/clef/) for request limits.
@@ -27,8 +27,8 @@
27
27
  "@effect/sql-sqlite-wasm": "workspace:*",
28
28
  "@effect/vitest": "workspace:*",
29
29
  "effect": "workspace:*",
30
- "hono": "^4.13.12",
31
- "nodemailer": "^10.0.14"
30
+ "hono": "^4.13.13",
31
+ "nodemailer": "^10.1.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/nodemailer": "^8.0.2"
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @title Getting started with GraphQL clients
3
+ *
4
+ * Define a query, build a typed client service over HTTP with an auth
5
+ * middleware, and page through a cursor connection.
6
+ */
7
+ import { Config, Context, Effect, Layer, Redacted, Schema, Stream } from "effect"
8
+ import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql"
9
+ import { FetchHttpClient } from "effect/http"
10
+
11
+ // Operations are usually generated: write them in `.graphql` files and run
12
+ // `graphqlgen` from `@effect/graphql-generator`, which writes a `.graphql.ts`
13
+ // module like the one below next to each document.
14
+ //
15
+ // query RepoIssues($owner: String!, $name: String!, $after: String) {
16
+ // repository(owner: $owner, name: $name) {
17
+ // issues(first: 50, after: $after) {
18
+ // pageInfo { hasNextPage endCursor }
19
+ // nodes { number title }
20
+ // }
21
+ // }
22
+ // }
23
+ //
24
+ // Each nested object selection has a Schema.Struct const and a same-named
25
+ // interface for its decoded type. The const handles decoding, encoding and
26
+ // `make`; use the interface in explicit type annotations when a named type
27
+ // is useful. Inferred types and editor hovers can expand structurally rather
28
+ // than showing the names, unlike the previous Schema.Opaque classes.
29
+ export const PageInfo = Schema.Struct({
30
+ hasNextPage: Schema.Boolean,
31
+ endCursor: Schema.NullOr(Schema.String)
32
+ })
33
+ export interface PageInfo extends Schema.Struct.Type<typeof PageInfo.fields> {}
34
+
35
+ export const Issue = Schema.Struct({ number: Schema.Int, title: Schema.String })
36
+ export interface Issue extends Schema.Struct.Type<typeof Issue.fields> {}
37
+
38
+ export const IssueConnection = Schema.Struct({
39
+ pageInfo: PageInfo,
40
+ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Issue)))
41
+ })
42
+ export interface IssueConnection extends Schema.Struct.Type<typeof IssueConnection.fields> {}
43
+
44
+ export const Repository = Schema.Struct({ issues: IssueConnection })
45
+ export interface Repository extends Schema.Struct.Type<typeof Repository.fields> {}
46
+
47
+ export const RepoIssues = GraphQL.query("RepoIssues", {
48
+ document:
49
+ "query RepoIssues($owner:String!,$name:String!,$after:String){repository(owner:$owner,name:$name){issues(first:50,after:$after){pageInfo{hasNextPage endCursor}nodes{number title}}}}",
50
+ variables: {
51
+ owner: Schema.String,
52
+ name: Schema.String,
53
+ after: Schema.optional(Schema.NullOr(Schema.String))
54
+ },
55
+ result: Schema.Struct({
56
+ repository: Schema.NullOr(Repository)
57
+ })
58
+ })
59
+
60
+ // A middleware is a service that wraps every operation it is attached to.
61
+ // `mapRequest` builds one from a single request transform.
62
+ export class GitHubAuth extends GraphQLMiddleware.Service<GitHubAuth>()("app/GitHubAuth") {
63
+ static readonly layer = Layer.effect(
64
+ GitHubAuth,
65
+ Effect.gen(function*() {
66
+ const token = yield* Config.Redacted("GITHUB_TOKEN")
67
+ return GraphQLMiddleware.mapRequest((request) =>
68
+ Effect.succeed({
69
+ ...request,
70
+ headers: { ...request.headers, authorization: `Bearer ${Redacted.value(token)}` }
71
+ })
72
+ )
73
+ })
74
+ )
75
+ }
76
+
77
+ // A group is the set of operations a client exposes; the generator emits one
78
+ // per file. Attaching the middleware makes `GraphQLClient.make` require it.
79
+ export const GitHubGraphQLGroup = GraphQLGroup.make(RepoIssues).middleware(GitHubAuth)
80
+
81
+ // The client has one method per operation, named after it.
82
+ export class GitHub extends Context.Service<
83
+ GitHub,
84
+ GraphQLClient.FromGroup<typeof GitHubGraphQLGroup>
85
+ >()("app/GitHub") {
86
+ static readonly layerTest = GraphQLClient.layerTest(GitHub, GitHubGraphQLGroup)
87
+
88
+ static readonly layer = Layer.effect(GitHub, GraphQLClient.make(GitHubGraphQLGroup)).pipe(
89
+ Layer.provide(GitHubAuth.layer),
90
+ // Queries and mutations are sent as `POST`. Subscriptions use graphql-sse
91
+ // here, or graphql-ws with `GraphQLProtocol.layerWebSocket`.
92
+ Layer.provide(GraphQLProtocol.layerHttp({ url: "https://api.github.com/graphql" })),
93
+ Layer.provide(FetchHttpClient.layer)
94
+ )
95
+ }
96
+
97
+ export const program = Effect.gen(function*() {
98
+ const github = yield* GitHub
99
+
100
+ // Variables are encoded and the result decoded through the Schemas. Any
101
+ // `errors` in the response fail with a `GraphQLClientError`; pass
102
+ // `{ partial: true }` as the second argument to get them with the data.
103
+ const { repository } = yield* github.RepoIssues({ owner: "Effect-TS", name: "effect" })
104
+ yield* Effect.log(`First page has ${repository?.issues.nodes?.length ?? 0} issues`)
105
+
106
+ // `items` pages through the connection by driving `$after`, one request at
107
+ // a time and only as the stream is pulled.
108
+ const titles = yield* GraphQLClient.items(github.RepoIssues, {
109
+ variables: { owner: "Effect-TS", name: "effect" },
110
+ connection: (result) => result.repository?.issues
111
+ }).pipe(
112
+ Stream.take(120),
113
+ Stream.map((issue) => issue?.title),
114
+ Stream.runCollect
115
+ )
116
+ yield* Effect.log(`Fetched ${titles.length} issues`)
117
+ }).pipe(Effect.provide(GitHub.layer))
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @title Testing code that uses a GraphQL client
3
+ *
4
+ * Replace a client service with `GraphQLClient.layerTest`, answering each
5
+ * operation from a handler instead of a server.
6
+ */
7
+ import { assert, describe, it } from "@effect/vitest"
8
+ import { Effect } from "effect"
9
+ import { GitHub } from "./10_basics.ts"
10
+
11
+ // Code under test that depends on the `GitHub` client service.
12
+ const issueTitles = (owner: string, name: string) =>
13
+ GitHub.use((github) => github.RepoIssues({ owner, name })).pipe(
14
+ Effect.map(({ repository }) => repository?.issues.nodes?.map((issue) => issue?.title) ?? [])
15
+ )
16
+
17
+ // The service binds `GraphQLClient.layerTest(GitHub, GitHubGraphQLGroup)` once
18
+ // as a static helper. Handlers are keyed by operation name, receive the
19
+ // caller's variables and options, and return results in their decoded form.
20
+ // Nothing is encoded or decoded and no middleware runs. An operation without
21
+ // a handler dies with an `UnimplementedError` defect.
22
+ const GitHubTest = GitHub.layerTest({
23
+ RepoIssues: ({ owner, name }) =>
24
+ Effect.succeed({
25
+ repository: {
26
+ issues: {
27
+ pageInfo: { hasNextPage: false, endCursor: null },
28
+ nodes: [{ number: 1, title: `Hello from ${owner}/${name}` }]
29
+ }
30
+ }
31
+ })
32
+ })
33
+
34
+ describe("issueTitles", () => {
35
+ it.effect("returns the titles of the first page", () =>
36
+ Effect.gen(function*() {
37
+ const titles = yield* issueTitles("Effect-TS", "effect")
38
+ assert.deepStrictEqual(titles, ["Hello from Effect-TS/effect"])
39
+ }).pipe(Effect.provide(GitHubTest)))
40
+ })
41
+
42
+ // `layerTest` uses `makeTest`, which skips the protocol and cannot return
43
+ // partial data together with `errors`. To test that, or the encode and decode
44
+ // path, build the real client with `GraphQLClient.make` over a scripted
45
+ // `GraphQLProtocol` layer (see `GraphQLProtocol`).
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @title Batching lookups with GraphQLResolver
3
+ *
4
+ * Collect concurrent lookups by id into one `nodes(ids:)` request with
5
+ * `GraphQLResolver`, instead of one request per id.
6
+ */
7
+ import { type Cause, Context, Effect, Layer, RequestResolver, Schema } from "effect"
8
+ import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
9
+ import { FetchHttpClient } from "effect/http"
10
+ import { GitHubAuth } from "./10_basics.ts"
11
+
12
+ // The generator's output for `repo-nodes.graphql`:
13
+ //
14
+ // query RepoNodes($ids: [ID!]!) {
15
+ // nodes(ids: $ids) { __typename ... on Repository { nameWithOwner } }
16
+ // }
17
+ //
18
+ // Generated modules import shared codecs and the possible `__typename`s of
19
+ // each interface from the module the generator writes next to the schema
20
+ // (`import * as Shared from "../schema.graphql.ts"`); here `Shared` is
21
+ // declared inline.
22
+ const Shared = { ID: Schema.String }
23
+ declare namespace Shared {
24
+ export namespace Typename {
25
+ export type Node = "Issue" | "PullRequest" | "Repository" | "User"
26
+ }
27
+ }
28
+
29
+ export const Repository = Schema.Struct({
30
+ __typename: Schema.Literal("Repository"),
31
+ nameWithOwner: Schema.String
32
+ })
33
+ export interface Repository extends Schema.Struct.Type<typeof Repository.fields> {}
34
+
35
+ // Unselected node types are represented by `otherTypename`.
36
+ export const NodeOther = Schema.Struct({
37
+ __typename: GraphQL.otherTypename<Shared.Typename.Node>()(["Repository"])
38
+ })
39
+ export interface NodeOther extends Schema.Struct.Type<typeof NodeOther.fields> {}
40
+
41
+ /** `query RepoNodes` */
42
+ export const RepoNodes = GraphQL.query("RepoNodes", {
43
+ document: {
44
+ variables: [
45
+ { name: "ids", body: "[ID!]!" }
46
+ ],
47
+ selections: [
48
+ { name: "nodes", body: ["(ids:$", "ids", "){__typename...on Repository{nameWithOwner}}"] }
49
+ ],
50
+ fragments: []
51
+ },
52
+ variables: {
53
+ ids: Schema.Array(Shared.ID)
54
+ },
55
+ result: Schema.Struct({
56
+ nodes: Schema.Array(Schema.NullOr(Schema.Union([
57
+ Repository,
58
+ NodeOther
59
+ ])))
60
+ })
61
+ })
62
+ export declare namespace RepoNodes {
63
+ export type Variables = typeof RepoNodes.variables.Type
64
+ export type Result = typeof RepoNodes.result.Type
65
+ }
66
+
67
+ /** Every operation in repo-nodes.graphql. */
68
+ export const RepoNodesGraphQLGroup = GraphQLGroup.make(RepoNodes)
69
+
70
+ // Your code: attach the middleware to the generated group.
71
+ export const GitHubGraphQLGroup = RepoNodesGraphQLGroup.middleware(GitHubAuth)
72
+
73
+ export class GitHub extends Context.Service<
74
+ GitHub,
75
+ GraphQLClient.FromGroup<typeof GitHubGraphQLGroup> & {
76
+ getRepo(id: string): Effect.Effect<
77
+ Repository,
78
+ GraphQL.Error<typeof RepoNodes> | Cause.NoSuchElementError
79
+ >
80
+ }
81
+ >()("app/GitHub") {
82
+ static readonly layer = Layer.effect(
83
+ GitHub,
84
+ Effect.gen(function*() {
85
+ const client = yield* GraphQLClient.make(GitHubGraphQLGroup)
86
+
87
+ // Null entries and non-Repository nodes fail with NoSuchElementError.
88
+ // GitHub accepts at most 100 ids per request.
89
+ //
90
+ // GitHubAuth reads one token from config, so every lookup can share a
91
+ // batch. If a middleware `requires` a per-request service, such as the
92
+ // signed-in user, `batchKey` is required and keeps lookups for different
93
+ // users in separate calls:
94
+ //
95
+ // batchKey: (context) => Context.get(context, CurrentUser).id
96
+ const RepoById = GraphQLResolver.ordered(client.RepoNodes, {
97
+ variables: (ids: ReadonlyArray<string>) => ({ ids }),
98
+ path: ["nodes"],
99
+ typename: "Repository"
100
+ }).pipe(RequestResolver.batchN(100))
101
+ return { ...client, getRepo: GraphQLResolver.request(RepoById) }
102
+ })
103
+ ).pipe(
104
+ Layer.provide(GitHubAuth.layer),
105
+ Layer.provide(GraphQLProtocol.layerHttp({ url: "https://api.github.com/graphql" })),
106
+ Layer.provide(FetchHttpClient.layer)
107
+ )
108
+ }
109
+
110
+ export const repoNames = Effect.fn("repoNames")(function*(ids: ReadonlyArray<string>) {
111
+ const github = yield* GitHub
112
+ const repos = yield* Effect.forEach(ids, github.getRepo, { concurrency: "unbounded" })
113
+ return repos.map((repo) => repo.nameWithOwner)
114
+ })
115
+
116
+ export const program = repoNames(["R_1", "R_2"]).pipe(
117
+ Effect.provide(GitHub.layer)
118
+ )
@@ -0,0 +1,124 @@
1
+ /**
2
+ * @title Batching single-item lookups with aliases
3
+ *
4
+ * When an API has no field that takes a list of keys, `GraphQLResolver.aliased`
5
+ * repeats a generated operation under aliases, so concurrent lookups share one
6
+ * request and keep their generated types.
7
+ */
8
+ import { Context, Effect, Layer, Schema } from "effect"
9
+ import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
10
+ import { FetchHttpClient } from "effect/http"
11
+ import { GitHubAuth } from "./10_basics.ts"
12
+
13
+ // The generator's output for `pr.graphql`:
14
+ //
15
+ // query PullRequest($owner: String!, $name: String!, $number: Int!) {
16
+ // repository(owner: $owner, name: $name) {
17
+ // pullRequest(number: $number) { number title }
18
+ // }
19
+ // }
20
+ //
21
+ // Generated modules import shared codecs, such as `Int`, from the module the
22
+ // generator writes next to the schema (`import * as Shared from
23
+ // "../schema.graphql.ts"`); here `Shared` is declared inline.
24
+ const Shared = { Int: Schema.Number.check(Schema.isInt32()) }
25
+
26
+ export const PullRequestPullRequest = Schema.Struct({
27
+ number: Shared.Int,
28
+ title: Schema.String
29
+ })
30
+ export interface PullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestPullRequest.fields> {}
31
+
32
+ export const Repository = Schema.Struct({
33
+ pullRequest: Schema.NullOr(PullRequestPullRequest)
34
+ })
35
+ export interface Repository extends Schema.Struct.Type<typeof Repository.fields> {}
36
+
37
+ // The generator gives queries and mutations their document as a
38
+ // `GraphQL.DocumentTemplate`. The odd entries of each `body` are the names
39
+ // `aliased` renames per slice; joined together they are the printed document.
40
+ /** `query PullRequest` */
41
+ export const PullRequest = GraphQL.query("PullRequest", {
42
+ document: {
43
+ variables: [
44
+ { name: "owner", body: "String!" },
45
+ { name: "name", body: "String!" },
46
+ { name: "number", body: "Int!" }
47
+ ],
48
+ selections: [
49
+ {
50
+ name: "repository",
51
+ body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){number title}}"]
52
+ }
53
+ ],
54
+ fragments: []
55
+ },
56
+ variables: {
57
+ owner: Schema.String,
58
+ name: Schema.String,
59
+ number: Shared.Int
60
+ },
61
+ result: Schema.Struct({
62
+ repository: Schema.NullOr(Repository)
63
+ })
64
+ })
65
+ export declare namespace PullRequest {
66
+ export type Variables = typeof PullRequest.variables.Type
67
+ export type Result = typeof PullRequest.result.Type
68
+ }
69
+
70
+ /** Every operation in pr.graphql. */
71
+ export const PrGraphQLGroup = GraphQLGroup.make(PullRequest)
72
+
73
+ // Your code: attach the middleware to the generated group.
74
+ export const GitHubGraphQLGroup = PrGraphQLGroup.middleware(GitHubAuth)
75
+
76
+ export class GitHub extends Context.Service<
77
+ GitHub,
78
+ GraphQLClient.FromGroup<typeof GitHubGraphQLGroup> & {
79
+ readonly getPullRequest: (
80
+ variables: GraphQL.Variables<typeof PullRequest>
81
+ ) => Effect.Effect<GraphQL.Result<typeof PullRequest>, GraphQL.Error<typeof PullRequest>>
82
+ }
83
+ >()("app/GitHub") {
84
+ static readonly layer = Layer.effect(
85
+ GitHub,
86
+ Effect.gen(function*() {
87
+ const client = yield* GraphQLClient.make(GitHubGraphQLGroup)
88
+
89
+ // Concurrent calls go out as one POST whose root fields are aliased
90
+ // `_0_repository`, `_1_repository`, and so on. Each slice is decoded
91
+ // with the generated result Schema, and a GraphQL error under
92
+ // `_1_repository` fails only that call.
93
+ //
94
+ // A batch holds 10 slices by default, because GitHub's query cost and
95
+ // timeouts grow with the size of the query. Pipe
96
+ // `RequestResolver.batchN` to change it.
97
+ const PullRequests = GraphQLResolver.aliased(client.PullRequest)
98
+
99
+ // `request` turns the resolver into a lookup by the operation's
100
+ // variables, as for `ordered` and `findById`.
101
+ return { ...client, getPullRequest: GraphQLResolver.request(PullRequests) }
102
+ })
103
+ ).pipe(
104
+ Layer.provide(GitHubAuth.layer),
105
+ Layer.provide(GraphQLProtocol.layerHttp({ url: "https://api.github.com/graphql" })),
106
+ Layer.provide(FetchHttpClient.layer)
107
+ )
108
+ }
109
+
110
+ export const pullRequestTitles = Effect.fn("pullRequestTitles")(function*(numbers: ReadonlyArray<number>) {
111
+ const github = yield* GitHub
112
+ const results = yield* Effect.forEach(
113
+ numbers,
114
+ (number) => github.getPullRequest({ owner: "Effect-TS", name: "effect", number }),
115
+ { concurrency: "unbounded" }
116
+ )
117
+ // `repository` and `pullRequest` are nullable, so a missing pull request is
118
+ // `null` rather than an error that would fail every slice.
119
+ return results.map((result) => result.repository?.pullRequest?.title ?? null)
120
+ })
121
+
122
+ export const program = pullRequestTitles([1, 2, 3]).pipe(
123
+ Effect.provide(GitHub.layer)
124
+ )
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @title Handling GraphQL errors, retries and rate limits
3
+ *
4
+ * Read rate-limit headers in a middleware, tell GraphQL errors apart by their
5
+ * fields, and retry timeouts and rate limits with `Effect.retry`.
6
+ */
7
+ import { Duration, Effect, Layer, Schedule } from "effect"
8
+ import { type GraphQLClientError, GraphQLMiddleware } from "effect/graphql"
9
+ import { GitHub } from "./10_basics.ts"
10
+
11
+ // Middleware see each response's HTTP `status` and `headers` on the result
12
+ // `next` returns, including responses with GraphQL `errors`. A failed call
13
+ // keeps them, and `GraphQLClientError` exposes them as `headers` and
14
+ // `status`. Attach it with `GraphQLGroup.make(...).middleware(RateLimit)`.
15
+ export class RateLimit extends GraphQLMiddleware.Service<RateLimit>()("app/RateLimit") {
16
+ static readonly layer = Layer.succeed(RateLimit, {
17
+ execute: ({ next, request }) =>
18
+ Effect.tap(next(request), (result) => {
19
+ const remaining = Number(result.headers?.["x-ratelimit-remaining"])
20
+ return remaining < 500
21
+ ? Effect.logWarning(`GitHub rate limit: ${remaining} points left`)
22
+ : Effect.void
23
+ }),
24
+ subscribe: ({ next, request }) => next(request)
25
+ })
26
+ }
27
+
28
+ // GraphQL errors keep fields the specification doesn't define as JSON, such
29
+ // as GitHub's top-level `type` (`NOT_FOUND`, `FORBIDDEN`, `RATE_LIMITED`).
30
+ export const hasErrorType = (error: GraphQLClientError.GraphQLClientError, type: string) =>
31
+ error.reason._tag === "ResponseError" && error.reason.errors.every((entry) => entry.type === type)
32
+
33
+ // `isRetryable` is true for network failures, for 429 or 5xx responses, and
34
+ // for any error with a `Retry-After` header, whatever its status. That covers
35
+ // GitHub's 502 and 504 query timeouts, even with a GraphQL `errors` body, and
36
+ // its secondary rate limits (403 or 429 with `retry-after`). A primary rate
37
+ // limit can come without `retry-after`, with `x-ratelimit-remaining: 0`, so
38
+ // check that header too.
39
+ const rateLimited = (error: GraphQLClientError.GraphQLClientError) => error.headers?.["x-ratelimit-remaining"] === "0"
40
+
41
+ // Wait for `retryAfter` when it is set, and until `x-ratelimit-reset` (epoch
42
+ // seconds) on a primary rate limit. GitHub may ban an integration that keeps
43
+ // retrying while rate limited, so don't retry with a plain backoff.
44
+ const gitHubRetry = Schedule.exponential("1 second").pipe(
45
+ Schedule.setInputType<GraphQLClientError.GraphQLClientError>(),
46
+ Schedule.modifyDelay(({ duration, input, now }) => {
47
+ if (input.retryAfter !== undefined) return Effect.succeed(input.retryAfter)
48
+ if (!rateLimited(input)) return Effect.succeed(duration)
49
+ const reset = Number(input.headers?.["x-ratelimit-reset"]) * 1000
50
+ return Effect.succeed(Number.isFinite(reset) ? Duration.millis(Math.max(0, reset - now)) : Duration.minutes(1))
51
+ })
52
+ )
53
+
54
+ // The client never retries queries or mutations on its own. Retry only
55
+ // mutations that are safe to send twice, and with `GraphQLClient.pages`,
56
+ // retry inside a middleware, because `Stream.retry` starts again from the
57
+ // first page. Subscriptions reconnect on their own after a retryable failure,
58
+ // on `GraphQLClient.defaultSubscriptionRetry`, which waits for `retryAfter`.
59
+ // A primary rate limit without `retry-after` isn't retryable, so it ends the
60
+ // subscription; wait until `x-ratelimit-reset` before subscribing again.
61
+ export const retryGitHub = <A, R>(effect: Effect.Effect<A, GraphQLClientError.GraphQLClientError, R>) =>
62
+ Effect.retry(effect, {
63
+ schedule: gitHubRetry,
64
+ while: (error) => error.isRetryable || rateLimited(error),
65
+ times: 5
66
+ })
67
+
68
+ export const program = Effect.gen(function*() {
69
+ const github = yield* GitHub
70
+ const result = yield* retryGitHub(github.RepoIssues({ owner: "Effect-TS", name: "missing" })).pipe(
71
+ Effect.catchIf((error) => hasErrorType(error, "NOT_FOUND"), () => Effect.succeed(null))
72
+ )
73
+ yield* Effect.log(result === null ? "No such repository" : `${result.repository?.issues.nodes?.length} issues`)
74
+ }).pipe(Effect.provide(GitHub.layer))
@@ -0,0 +1,6 @@
1
+ ## Typed GraphQL clients with `effect/graphql`
2
+
3
+ Use the `effect/graphql` modules to call GraphQL APIs with typed
4
+ operations. Run `graphqlgen` from `@effect/graphql-generator` to generate
5
+ operations from `.graphql` documents, then build a client with
6
+ `GraphQLClient.make` and provide a transport from `GraphQLProtocol`.
@@ -1,9 +1,3 @@
1
- /**
2
- * Cloudflare Clef implementation of DecisionModel over Workers AI REST.
3
- *
4
- * @stability unstable
5
- * @since 4.0.0
6
- */
7
1
  import * as DecisionModel from "effect/ai/DecisionModel";
8
2
  import * as AiModel from "effect/ai/Model";
9
3
  import * as Effect from "effect/Effect";
@@ -29,6 +23,16 @@ export declare const model: (model: Model) => AiModel.Model<"cloudflare", Decisi
29
23
  /**
30
24
  * Builds a decision service with tolerance for four-decimal probability rounding.
31
25
  *
26
+ * **Details**
27
+ *
28
+ * Byte arrays and base64 strings are sent as base64 with their media type.
29
+ * `data:` URLs are sent unchanged. The API enforces image limits.
30
+ *
31
+ * **Gotchas**
32
+ *
33
+ * - Remote URLs fail with `AiError.InvalidUserInputError` because Clef does
34
+ * not fetch them.
35
+ *
32
36
  * @stability unstable
33
37
  * @category constructors
34
38
  * @since 4.0.0
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareDecisionModel.d.ts","sourceRoot":"","sources":["../src/CloudflareDecisionModel.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,aAAa,MAAM,yBAAyB,CAAA;AACxD,OAAO,KAAK,OAAO,MAAM,iBAAiB,CAAA;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,KAAK,gBAAgB,MAAM,uBAAuB,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,MAAM,KAAK,GAAG,OAAO,gBAAgB,CAAC,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;AAE7E;;;;;;GAMG;AACH,eAAO,MAAM,KAAK,UACT,KAAK,KACX,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,aAAa,CAAC,aAAa,EAAE,gBAAgB,CACvB,CAAA;AAErD;;;;;;GAMG;AACH,eAAO,MAAM,IAAI;oBAEc,KAAK;yEAuDnC,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,KAAK,YACP;IAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;CAAE,KACjC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,aAAa,EAAE,KAAK,EAAE,gBAAgB,CACT,CAAA"}
1
+ {"version":3,"file":"CloudflareDecisionModel.d.ts","sourceRoot":"","sources":["../src/CloudflareDecisionModel.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,aAAa,MAAM,yBAAyB,CAAA;AACxD,OAAO,KAAK,OAAO,MAAM,iBAAiB,CAAA;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,KAAK,gBAAgB,MAAM,uBAAuB,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,MAAM,KAAK,GAAG,OAAO,gBAAgB,CAAC,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;AAE7E;;;;;;GAMG;AACH,eAAO,MAAM,KAAK,UACT,KAAK,KACX,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,aAAa,CAAC,aAAa,EAAE,gBAAgB,CACvB,CAAA;AAErD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI;oBAEc,KAAK;yEA0EnC,CAAA;AAQD;;;;;;GAMG;AACH,eAAO,MAAM,KAAK,YACP;IAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;CAAE,KACjC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,aAAa,EAAE,KAAK,EAAE,gBAAgB,CACT,CAAA"}
@@ -4,9 +4,11 @@
4
4
  * @stability unstable
5
5
  * @since 4.0.0
6
6
  */
7
+ import * as AiError from "effect/ai/AiError";
7
8
  import * as DecisionModel from "effect/ai/DecisionModel";
8
9
  import * as AiModel from "effect/ai/Model";
9
10
  import * as Effect from "effect/Effect";
11
+ import * as Base64 from "effect/encoding/Base64";
10
12
  import * as Layer from "effect/Layer";
11
13
  import { CloudflareClient } from "./CloudflareClient.js";
12
14
  /**
@@ -22,6 +24,16 @@ export const model = model => AiModel.make("cloudflare", model, layer({
22
24
  /**
23
25
  * Builds a decision service with tolerance for four-decimal probability rounding.
24
26
  *
27
+ * **Details**
28
+ *
29
+ * Byte arrays and base64 strings are sent as base64 with their media type.
30
+ * `data:` URLs are sent unchanged. The API enforces image limits.
31
+ *
32
+ * **Gotchas**
33
+ *
34
+ * - Remote URLs fail with `AiError.InvalidUserInputError` because Clef does
35
+ * not fetch them.
36
+ *
25
37
  * @stability unstable
26
38
  * @category constructors
27
39
  * @since 4.0.0
@@ -30,9 +42,11 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
30
42
  const client = yield* CloudflareClient;
31
43
  return yield* DecisionModel.make({
32
44
  probabilityPrecision: 4,
45
+ supportsImages: true,
33
46
  decide: Effect.fnUntraced(function* ({
34
47
  state,
35
- decisions
48
+ decisions,
49
+ images
36
50
  }) {
37
51
  const questions = Object.create(null);
38
52
  for (const [key, decision] of Object.entries(decisions)) {
@@ -48,7 +62,7 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
48
62
  questions[key] = {
49
63
  type: "score",
50
64
  instructions: decision.instructions,
51
- criteria: decision.criteria
65
+ criteria: decision.criteria.map(level => level.description)
52
66
  };
53
67
  break;
54
68
  case "Probability":
@@ -60,10 +74,22 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
60
74
  break;
61
75
  }
62
76
  }
77
+ if (images?.some(image => image.data instanceof URL && image.data.protocol !== "data:")) {
78
+ return yield* Effect.fail(AiError.make({
79
+ module: "CloudflareDecisionModel",
80
+ method: "decide",
81
+ reason: new AiError.InvalidUserInputError({
82
+ description: "Cloudflare Clef accepts base64 or data URL images, not remote URLs"
83
+ })
84
+ }));
85
+ }
63
86
  const response = yield* client.createDecisions({
64
87
  model: options.model,
65
88
  state,
66
- questions
89
+ questions,
90
+ ...(images === undefined ? undefined : {
91
+ images: images.map(encodeImage)
92
+ })
67
93
  });
68
94
  const answers = Object.create(null);
69
95
  for (const [key, decision] of Object.entries(decisions)) {
@@ -83,7 +109,7 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
83
109
  const probabilities = Object.create(null);
84
110
  for (let index = 0; index < levels.length; index++) {
85
111
  const probability = answer.probabilities[String(index)];
86
- if (probability !== undefined) probabilities[levels[index]] = probability;
112
+ if (probability !== undefined) probabilities[levels[index].label] = probability;
87
113
  }
88
114
  answers[key] = {
89
115
  _tag: "Rate",
@@ -111,6 +137,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
111
137
  })
112
138
  });
113
139
  });
140
+ const encodeImage = image => image.data instanceof URL ? image.data.href : {
141
+ content_type: image.mediaType,
142
+ base64: typeof image.data === "string" ? image.data : Base64.encode(image.data)
143
+ };
114
144
  /**
115
145
  * Provides DecisionModel using an existing CloudflareClient.
116
146
  *
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareDecisionModel.js","names":[],"sources":["../src/CloudflareDecisionModel.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;AAMA,OAAO,KAAK,aAAa,MAAM,yBAAyB;AACxD,OAAO,KAAK,OAAO,MAAM,iBAAiB;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc;AACrC,SAAS,gBAAgB,QAAQ,uBAAuB;AAYxD;;;;;;;AAOA,OAAO,MAAM,KAAK,GAChB,KAAY,IAEZ,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,EAAE,KAAK,CAAC;EAAE;AAAK,CAAE,CAAC,CAAC;AAErD;;;;;;;AAOA,OAAO,MAAM,IAAI,gBAAG,MAAM,CAAC,UAAU,CACnC,WACE,OAAkC;EAElC,MAAM,MAAM,GAAG,OAAO,gBAAgB;EACtC,OAAO,OAAO,aAAa,CAAC,IAAI,CAAC;IAC/B,oBAAoB,EAAE,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC,UAAU,CAAC,WAAU;MAAE,KAAK;MAAE;IAAS,CAAE;MACtD,MAAM,SAAS,GAA6D,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;MAC/F,KAAK,MAAM,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QACvD,QAAQ,QAAQ,CAAC,IAAI;UACnB,KAAK,UAAU;YACb,SAAS,CAAC,GAAG,CAAC,GAAG;cAAE,IAAI,EAAE,QAAQ;cAAE,YAAY,EAAE,QAAQ,CAAC,YAAY;cAAE,QAAQ,EAAE,QAAQ,CAAC;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Aa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACvD,IAAI,WAAW,KAAK,SAAS,EAAE,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,WAAW;cACjF;cACA,OAAO,CAAC,GAAG,CAAC,GAAG;gBAAE,IAAI,EAAE,MAAM;gBAAE,MAAM,EAAE,MAAM,CAAC,KAAK;gBAAE,aAAa;gBAAE,UAAU,EAAE,MAAM,CAAC;cAAU,CAAE;cACnG;YACF;UACA,KAAK,MAAM;YACT,OAAO,CAAC,GAAG,CAAC,GAAG;cAAE,IAAI,EAAE,aAAa;cAAE,WAAW,EAAE,MAAM,CAAC;YAAI,CAAE;YAChE;QACJ;MACF;MACA,OAAO;QACL,OAAO;QACP,KAAK,EAAE;UAAE,WAAW,EAAE,QAAQ,CAAC,KAAK,CAAC,YAAY;UAAE,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC;QAAa;OAC9F;IACH,CAAC;GACF,CAAC;AACJ,CAAC,CACF;AAED,MAAM,WAAW,GAAI,KAA0B,IAC7C,KAAK,CAAC,IAAI,YAAY,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG;EAC5C,YAAY,EAAE,KAAK,CAAC,SAAS;EAC7B,MAAM,EAAE,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,GAAG,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI;CAC/E;AAEH;;;;;;;AAOA,OAAO,MAAM,KAAK,GAChB,OAAkC,IAElC,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC","ignoreList":[]}
@@ -14,8 +14,8 @@ import * as Schema from "effect/Schema";
14
14
  */
15
15
  export declare const ChoiceQuestion: Schema.Struct<{
16
16
  readonly type: Schema.Literal<"choice">;
17
- readonly instructions: Schema.String;
18
- readonly criteria: Schema.$Record<Schema.String, Schema.String>;
17
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
18
+ readonly criteria: Schema.$Record<Schema.String, Schema.NullOr<Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>>;
19
19
  }>;
20
20
  /**
21
21
  * An ordered rating question.
@@ -26,8 +26,8 @@ export declare const ChoiceQuestion: Schema.Struct<{
26
26
  */
27
27
  export declare const ScoreQuestion: Schema.Struct<{
28
28
  readonly type: Schema.Literal<"score">;
29
- readonly instructions: Schema.String;
30
- readonly criteria: Schema.$Array<Schema.String>;
29
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
30
+ readonly criteria: Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
31
31
  }>;
32
32
  /**
33
33
  * A probability question.
@@ -38,14 +38,15 @@ export declare const ScoreQuestion: Schema.Struct<{
38
38
  */
39
39
  export declare const NoulQuestion: Schema.Struct<{
40
40
  readonly type: Schema.Literal<"noul">;
41
- readonly instructions: Schema.String;
41
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
42
42
  readonly criteria: Schema.optional<Schema.Struct<{
43
- readonly false: Schema.String;
44
- readonly true: Schema.String;
43
+ readonly false: Schema.Codec<Schema.Json, Schema.Json, never, never>;
44
+ readonly true: Schema.Codec<Schema.Json, Schema.Json, never, never>;
45
45
  }>>;
46
46
  }>;
47
47
  /**
48
- * A Clef classification, rating, or probability question.
48
+ * A Clef question with string, JSON object, or JSON array instructions.
49
+ * Choice descriptions also accept `null`; Score and Noul descriptions accept any JSON value.
49
50
  *
50
51
  * @stability unstable
51
52
  * @category schemas
@@ -53,22 +54,40 @@ export declare const NoulQuestion: Schema.Struct<{
53
54
  */
54
55
  export declare const Question: Schema.Union<readonly [Schema.Struct<{
55
56
  readonly type: Schema.Literal<"choice">;
56
- readonly instructions: Schema.String;
57
- readonly criteria: Schema.$Record<Schema.String, Schema.String>;
57
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
58
+ readonly criteria: Schema.$Record<Schema.String, Schema.NullOr<Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>>;
58
59
  }>, Schema.Struct<{
59
60
  readonly type: Schema.Literal<"score">;
60
- readonly instructions: Schema.String;
61
- readonly criteria: Schema.$Array<Schema.String>;
61
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
62
+ readonly criteria: Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
62
63
  }>, Schema.Struct<{
63
64
  readonly type: Schema.Literal<"noul">;
64
- readonly instructions: Schema.String;
65
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
65
66
  readonly criteria: Schema.optional<Schema.Struct<{
66
- readonly false: Schema.String;
67
- readonly true: Schema.String;
67
+ readonly false: Schema.Codec<Schema.Json, Schema.Json, never, never>;
68
+ readonly true: Schema.Codec<Schema.Json, Schema.Json, never, never>;
68
69
  }>>;
69
70
  }>]>;
70
71
  /**
71
- * A batch of questions about text or JSON state.
72
+ * An image as a `data:` URL or as base64 data with its media type. Clef
73
+ * rejects remote URLs.
74
+ *
75
+ * @stability unstable
76
+ * @category schemas
77
+ * @since 4.0.5
78
+ */
79
+ export declare const Image: Schema.Union<readonly [Schema.String, Schema.Struct<{
80
+ readonly content_type: Schema.Union<readonly [Schema.Literals<readonly ["image/png", "image/jpeg", "image/webp"]>, Schema.StringForLiteralAutocomplete]>;
81
+ readonly base64: Schema.String;
82
+ }>]>;
83
+ /**
84
+ * A batch of questions about text or JSON state, with optional images shown
85
+ * to the model before the state.
86
+ *
87
+ * **Details**
88
+ *
89
+ * Clef accepts up to 4 images of at most 4 MiB and 16 megapixels each, 8 MiB
90
+ * of decoded images in total, and 13 MiB per request body.
72
91
  *
73
92
  * @stability unstable
74
93
  * @category schemas
@@ -79,20 +98,24 @@ export declare const DecisionsRequest: Schema.Struct<{
79
98
  readonly state: Schema.Codec<Schema.Json, Schema.Json, never, never>;
80
99
  readonly questions: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.Struct<{
81
100
  readonly type: Schema.Literal<"choice">;
82
- readonly instructions: Schema.String;
83
- readonly criteria: Schema.$Record<Schema.String, Schema.String>;
101
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
102
+ readonly criteria: Schema.$Record<Schema.String, Schema.NullOr<Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>>;
84
103
  }>, Schema.Struct<{
85
104
  readonly type: Schema.Literal<"score">;
86
- readonly instructions: Schema.String;
87
- readonly criteria: Schema.$Array<Schema.String>;
105
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
106
+ readonly criteria: Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
88
107
  }>, Schema.Struct<{
89
108
  readonly type: Schema.Literal<"noul">;
90
- readonly instructions: Schema.String;
109
+ readonly instructions: Schema.Union<readonly [Schema.String, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>, Schema.$Array<Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
91
110
  readonly criteria: Schema.optional<Schema.Struct<{
92
- readonly false: Schema.String;
93
- readonly true: Schema.String;
111
+ readonly false: Schema.Codec<Schema.Json, Schema.Json, never, never>;
112
+ readonly true: Schema.Codec<Schema.Json, Schema.Json, never, never>;
94
113
  }>>;
95
114
  }>]>>;
115
+ readonly images: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Struct<{
116
+ readonly content_type: Schema.Union<readonly [Schema.Literals<readonly ["image/png", "image/jpeg", "image/webp"]>, Schema.StringForLiteralAutocomplete]>;
117
+ readonly base64: Schema.String;
118
+ }>]>>>;
96
119
  }>;
97
120
  /**
98
121
  * A classification distribution.
@@ -108,7 +131,7 @@ export declare const ChoiceAnswer: Schema.Struct<{
108
131
  readonly confidence: Schema.Number;
109
132
  }>;
110
133
  /**
111
- * A zero-based rating and index-keyed distribution.
134
+ * A zero-based rating and index-keyed distribution. `legend` maps indices to descriptions.
112
135
  *
113
136
  * @stability unstable
114
137
  * @category schemas
@@ -119,7 +142,7 @@ export declare const ScoreAnswer: Schema.Struct<{
119
142
  readonly score: Schema.Number;
120
143
  readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
121
144
  readonly confidence: Schema.Number;
122
- readonly legend: Schema.$Record<Schema.String, Schema.String>;
145
+ readonly legend: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
123
146
  }>;
124
147
  /**
125
148
  * A Bernoulli probability.
@@ -149,7 +172,7 @@ export declare const Answer: Schema.Union<readonly [Schema.Struct<{
149
172
  readonly score: Schema.Number;
150
173
  readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
151
174
  readonly confidence: Schema.Number;
152
- readonly legend: Schema.$Record<Schema.String, Schema.String>;
175
+ readonly legend: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
153
176
  }>, Schema.Struct<{
154
177
  readonly type: Schema.Literal<"noul">;
155
178
  readonly noul: Schema.Number;
@@ -173,7 +196,7 @@ export declare const DecisionsResponse: Schema.Struct<{
173
196
  readonly score: Schema.Number;
174
197
  readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
175
198
  readonly confidence: Schema.Number;
176
- readonly legend: Schema.$Record<Schema.String, Schema.String>;
199
+ readonly legend: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
177
200
  }>, Schema.Struct<{
178
201
  readonly type: Schema.Literal<"noul">;
179
202
  readonly noul: Schema.Number;
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSchema.d.ts","sourceRoot":"","sources":["../src/CloudflareSchema.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc;;;;EAIzB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa;;;;EAIxB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;;;EAIvB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;IAA8D,CAAA;AAEnF;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;EAI3B,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;EAKvB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;;;;;;EAMtB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,UAAU;;;EAAuE,CAAA;AAE9F;;;;;;GAMG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;IAAwD,CAAA;AAE3E;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;EAO5B,CAAA"}
1
+ {"version":3,"file":"CloudflareSchema.d.ts","sourceRoot":"","sources":["../src/CloudflareSchema.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAIvC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc;;;;EAIzB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa;;;;EAIxB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;;;EAIvB,CAAA;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;IAA8D,CAAA;AAEnF;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK;;;IAShB,CAAA;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;EAK3B,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY;;;;;EAKvB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;;;;;;EAMtB,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,UAAU;;;EAAuE,CAAA;AAE9F;;;;;;GAMG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;IAAwD,CAAA;AAE3E;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;EAO5B,CAAA"}
@@ -5,6 +5,7 @@
5
5
  * @since 4.0.0
6
6
  */
7
7
  import * as Schema from "effect/Schema";
8
+ const Entry = /*#__PURE__*/Schema.Union([Schema.String, Schema.JsonObject, /*#__PURE__*/Schema.Array(Schema.Json)]);
8
9
  /**
9
10
  * A classification question.
10
11
  *
@@ -14,8 +15,8 @@ import * as Schema from "effect/Schema";
14
15
  */
15
16
  export const ChoiceQuestion = /*#__PURE__*/Schema.Struct({
16
17
  type: /*#__PURE__*/Schema.Literal("choice"),
17
- instructions: Schema.String,
18
- criteria: /*#__PURE__*/Schema.Record(Schema.String, Schema.String)
18
+ instructions: Entry,
19
+ criteria: /*#__PURE__*/Schema.Record(Schema.String, /*#__PURE__*/Schema.NullOr(Entry))
19
20
  });
20
21
  /**
21
22
  * An ordered rating question.
@@ -26,8 +27,8 @@ export const ChoiceQuestion = /*#__PURE__*/Schema.Struct({
26
27
  */
27
28
  export const ScoreQuestion = /*#__PURE__*/Schema.Struct({
28
29
  type: /*#__PURE__*/Schema.Literal("score"),
29
- instructions: Schema.String,
30
- criteria: /*#__PURE__*/Schema.Array(Schema.String)
30
+ instructions: Entry,
31
+ criteria: /*#__PURE__*/Schema.Array(Schema.Json)
31
32
  });
32
33
  /**
33
34
  * A probability question.
@@ -38,14 +39,15 @@ export const ScoreQuestion = /*#__PURE__*/Schema.Struct({
38
39
  */
39
40
  export const NoulQuestion = /*#__PURE__*/Schema.Struct({
40
41
  type: /*#__PURE__*/Schema.Literal("noul"),
41
- instructions: Schema.String,
42
+ instructions: Entry,
42
43
  criteria: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Struct({
43
- false: Schema.String,
44
- true: Schema.String
44
+ false: Schema.Json,
45
+ true: Schema.Json
45
46
  }))
46
47
  });
47
48
  /**
48
- * A Clef classification, rating, or probability question.
49
+ * A Clef question with string, JSON object, or JSON array instructions.
50
+ * Choice descriptions also accept `null`; Score and Noul descriptions accept any JSON value.
49
51
  *
50
52
  * @stability unstable
51
53
  * @category schemas
@@ -53,7 +55,25 @@ export const NoulQuestion = /*#__PURE__*/Schema.Struct({
53
55
  */
54
56
  export const Question = /*#__PURE__*/Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestion]);
55
57
  /**
56
- * A batch of questions about text or JSON state.
58
+ * An image as a `data:` URL or as base64 data with its media type. Clef
59
+ * rejects remote URLs.
60
+ *
61
+ * @stability unstable
62
+ * @category schemas
63
+ * @since 4.0.5
64
+ */
65
+ export const Image = /*#__PURE__*/Schema.Union([Schema.String, /*#__PURE__*/Schema.Struct({
66
+ content_type: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literals(["image/png", "image/jpeg", "image/webp"]), Schema.StringForLiteralAutocomplete]),
67
+ base64: Schema.String
68
+ })]);
69
+ /**
70
+ * A batch of questions about text or JSON state, with optional images shown
71
+ * to the model before the state.
72
+ *
73
+ * **Details**
74
+ *
75
+ * Clef accepts up to 4 images of at most 4 MiB and 16 megapixels each, 8 MiB
76
+ * of decoded images in total, and 13 MiB per request body.
57
77
  *
58
78
  * @stability unstable
59
79
  * @category schemas
@@ -62,7 +82,8 @@ export const Question = /*#__PURE__*/Schema.Union([ChoiceQuestion, ScoreQuestion
62
82
  export const DecisionsRequest = /*#__PURE__*/Schema.Struct({
63
83
  model: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literals(["clef", "clef-flash"]), Schema.StringForLiteralAutocomplete]),
64
84
  state: Schema.Json,
65
- questions: /*#__PURE__*/Schema.Record(Schema.String, Question)
85
+ questions: /*#__PURE__*/Schema.Record(Schema.String, Question),
86
+ images: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Image))
66
87
  });
67
88
  /**
68
89
  * A classification distribution.
@@ -78,7 +99,7 @@ export const ChoiceAnswer = /*#__PURE__*/Schema.Struct({
78
99
  confidence: Schema.Number
79
100
  });
80
101
  /**
81
- * A zero-based rating and index-keyed distribution.
102
+ * A zero-based rating and index-keyed distribution. `legend` maps indices to descriptions.
82
103
  *
83
104
  * @stability unstable
84
105
  * @category schemas
@@ -89,7 +110,7 @@ export const ScoreAnswer = /*#__PURE__*/Schema.Struct({
89
110
  score: Schema.Number,
90
111
  probabilities: /*#__PURE__*/Schema.Record(Schema.String, Schema.Number),
91
112
  confidence: Schema.Number,
92
- legend: /*#__PURE__*/Schema.Record(Schema.String, Schema.String)
113
+ legend: /*#__PURE__*/Schema.Record(Schema.String, Schema.Json)
93
114
  });
94
115
  /**
95
116
  * A Bernoulli probability.
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSchema.js","names":[],"sources":["../src/CloudflareSchema.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;AAMA,OAAO,KAAK,MAAM,MAAM,eAAe;AAEvC;;;;;;;AAOA,OAAO,MAAM,cAAc,gBAAG,MAAM,CAAC,MAAM,CAAC;EAC1C,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC;EAC9B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM;CACrD,CAAC;AAEF;;;;;;;AAOA,OAAO,MAAM,aAAa,gBAAG,MAAM,CAAC,MAAM,CAAC;EACzC,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;EAC7B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM;CACrC,CAAC;AAEF;;;;;;;AAOA,OAAO,MAAM,YAAY,gBAAG,MAAM,CAAC,MAAM,CAAC;EACxC,IAAI,eAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;EAC5B,YAAY,EAAE,MAAM,CAAC,MAAM;EAC3B,QAAQ,eAAE,MAAM,CAAC,QAAQ,cAAC,MAAM,CAAC,MAAM,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC,MAAM;IAAE,IAAI,EAAE,MAAM,CAAC;EAAM,CAAE,CAAC;CACvF,CAAC;AAEF;;;;;;;AAOA,OAAO,MAAM,QAAQ,gBAAG,MAAM,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC;AAEnF;;;;;;;AAOA,OAAO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
  {
2
2
  "name": "@effect/ai-cloudflare",
3
- "version": "4.0.3",
3
+ "version": "4.0.5",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "A Cloudflare Workers AI decision provider for Effect",
@@ -47,10 +47,10 @@
47
47
  "provenance": true
48
48
  },
49
49
  "devDependencies": {
50
- "effect": "^4.0.3"
50
+ "effect": "^4.0.5"
51
51
  },
52
52
  "peerDependencies": {
53
- "effect": "^4.0.3"
53
+ "effect": "^4.0.5"
54
54
  },
55
55
  "scripts": {
56
56
  "codegen": "effect-utils codegen",
@@ -4,9 +4,11 @@
4
4
  * @stability unstable
5
5
  * @since 4.0.0
6
6
  */
7
+ import * as AiError from "effect/ai/AiError"
7
8
  import * as DecisionModel from "effect/ai/DecisionModel"
8
9
  import * as AiModel from "effect/ai/Model"
9
10
  import * as Effect from "effect/Effect"
11
+ import * as Base64 from "effect/encoding/Base64"
10
12
  import * as Layer from "effect/Layer"
11
13
  import { CloudflareClient } from "./CloudflareClient.ts"
12
14
  import type * as CloudflareSchema from "./CloudflareSchema.ts"
@@ -35,6 +37,16 @@ export const model = (
35
37
  /**
36
38
  * Builds a decision service with tolerance for four-decimal probability rounding.
37
39
  *
40
+ * **Details**
41
+ *
42
+ * Byte arrays and base64 strings are sent as base64 with their media type.
43
+ * `data:` URLs are sent unchanged. The API enforces image limits.
44
+ *
45
+ * **Gotchas**
46
+ *
47
+ * - Remote URLs fail with `AiError.InvalidUserInputError` because Clef does
48
+ * not fetch them.
49
+ *
38
50
  * @stability unstable
39
51
  * @category constructors
40
52
  * @since 4.0.0
@@ -46,7 +58,8 @@ export const make = Effect.fnUntraced(
46
58
  const client = yield* CloudflareClient
47
59
  return yield* DecisionModel.make({
48
60
  probabilityPrecision: 4,
49
- decide: Effect.fnUntraced(function*({ state, decisions }) {
61
+ supportsImages: true,
62
+ decide: Effect.fnUntraced(function*({ state, decisions, images }) {
50
63
  const questions: Record<string, typeof CloudflareSchema.Question.Encoded> = Object.create(null)
51
64
  for (const [key, decision] of Object.entries(decisions)) {
52
65
  switch (decision._tag) {
@@ -54,14 +67,32 @@ export const make = Effect.fnUntraced(
54
67
  questions[key] = { type: "choice", instructions: decision.instructions, criteria: decision.criteria }
55
68
  break
56
69
  case "Rate":
57
- questions[key] = { type: "score", instructions: decision.instructions, criteria: decision.criteria }
70
+ questions[key] = {
71
+ type: "score",
72
+ instructions: decision.instructions,
73
+ criteria: decision.criteria.map((level) => level.description)
74
+ }
58
75
  break
59
76
  case "Probability":
60
77
  questions[key] = { type: "noul", instructions: decision.instructions, criteria: decision.criteria }
61
78
  break
62
79
  }
63
80
  }
64
- const response = yield* client.createDecisions({ model: options.model, state, questions })
81
+ if (images?.some((image) => image.data instanceof URL && image.data.protocol !== "data:")) {
82
+ return yield* Effect.fail(AiError.make({
83
+ module: "CloudflareDecisionModel",
84
+ method: "decide",
85
+ reason: new AiError.InvalidUserInputError({
86
+ description: "Cloudflare Clef accepts base64 or data URL images, not remote URLs"
87
+ })
88
+ }))
89
+ }
90
+ const response = yield* client.createDecisions({
91
+ model: options.model,
92
+ state,
93
+ questions,
94
+ ...(images === undefined ? undefined : { images: images.map(encodeImage) })
95
+ })
65
96
  const answers: Record<string, DecisionModel.ProviderAnswer> = Object.create(null)
66
97
  for (const [key, decision] of Object.entries(decisions)) {
67
98
  const answer = response.answers[key]
@@ -79,7 +110,7 @@ export const make = Effect.fnUntraced(
79
110
  const probabilities: Record<string, number> = Object.create(null)
80
111
  for (let index = 0; index < levels.length; index++) {
81
112
  const probability = answer.probabilities[String(index)]
82
- if (probability !== undefined) probabilities[levels[index]] = probability
113
+ if (probability !== undefined) probabilities[levels[index].label] = probability
83
114
  }
84
115
  answers[key] = { _tag: "Rate", rating: answer.score, probabilities, confidence: answer.confidence }
85
116
  break
@@ -98,6 +129,12 @@ export const make = Effect.fnUntraced(
98
129
  }
99
130
  )
100
131
 
132
+ const encodeImage = (image: DecisionModel.Image): typeof CloudflareSchema.Image.Encoded =>
133
+ image.data instanceof URL ? image.data.href : {
134
+ content_type: image.mediaType,
135
+ base64: typeof image.data === "string" ? image.data : Base64.encode(image.data)
136
+ }
137
+
101
138
  /**
102
139
  * Provides DecisionModel using an existing CloudflareClient.
103
140
  *
@@ -6,6 +6,8 @@
6
6
  */
7
7
  import * as Schema from "effect/Schema"
8
8
 
9
+ const Entry = Schema.Union([Schema.String, Schema.JsonObject, Schema.Array(Schema.Json)])
10
+
9
11
  /**
10
12
  * A classification question.
11
13
  *
@@ -15,8 +17,8 @@ import * as Schema from "effect/Schema"
15
17
  */
16
18
  export const ChoiceQuestion = Schema.Struct({
17
19
  type: Schema.Literal("choice"),
18
- instructions: Schema.String,
19
- criteria: Schema.Record(Schema.String, Schema.String)
20
+ instructions: Entry,
21
+ criteria: Schema.Record(Schema.String, Schema.NullOr(Entry))
20
22
  })
21
23
 
22
24
  /**
@@ -28,8 +30,8 @@ export const ChoiceQuestion = Schema.Struct({
28
30
  */
29
31
  export const ScoreQuestion = Schema.Struct({
30
32
  type: Schema.Literal("score"),
31
- instructions: Schema.String,
32
- criteria: Schema.Array(Schema.String)
33
+ instructions: Entry,
34
+ criteria: Schema.Array(Schema.Json)
33
35
  })
34
36
 
35
37
  /**
@@ -41,12 +43,13 @@ export const ScoreQuestion = Schema.Struct({
41
43
  */
42
44
  export const NoulQuestion = Schema.Struct({
43
45
  type: Schema.Literal("noul"),
44
- instructions: Schema.String,
45
- criteria: Schema.optional(Schema.Struct({ false: Schema.String, true: Schema.String }))
46
+ instructions: Entry,
47
+ criteria: Schema.optional(Schema.Struct({ false: Schema.Json, true: Schema.Json }))
46
48
  })
47
49
 
48
50
  /**
49
- * A Clef classification, rating, or probability question.
51
+ * A Clef question with string, JSON object, or JSON array instructions.
52
+ * Choice descriptions also accept `null`; Score and Noul descriptions accept any JSON value.
50
53
  *
51
54
  * @stability unstable
52
55
  * @category schemas
@@ -55,7 +58,32 @@ export const NoulQuestion = Schema.Struct({
55
58
  export const Question = Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestion])
56
59
 
57
60
  /**
58
- * A batch of questions about text or JSON state.
61
+ * An image as a `data:` URL or as base64 data with its media type. Clef
62
+ * rejects remote URLs.
63
+ *
64
+ * @stability unstable
65
+ * @category schemas
66
+ * @since 4.0.5
67
+ */
68
+ export const Image = Schema.Union([
69
+ Schema.String,
70
+ Schema.Struct({
71
+ content_type: Schema.Union([
72
+ Schema.Literals(["image/png", "image/jpeg", "image/webp"]),
73
+ Schema.StringForLiteralAutocomplete
74
+ ]),
75
+ base64: Schema.String
76
+ })
77
+ ])
78
+
79
+ /**
80
+ * A batch of questions about text or JSON state, with optional images shown
81
+ * to the model before the state.
82
+ *
83
+ * **Details**
84
+ *
85
+ * Clef accepts up to 4 images of at most 4 MiB and 16 megapixels each, 8 MiB
86
+ * of decoded images in total, and 13 MiB per request body.
59
87
  *
60
88
  * @stability unstable
61
89
  * @category schemas
@@ -64,7 +92,8 @@ export const Question = Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestio
64
92
  export const DecisionsRequest = Schema.Struct({
65
93
  model: Schema.Union([Schema.Literals(["clef", "clef-flash"]), Schema.StringForLiteralAutocomplete]),
66
94
  state: Schema.Json,
67
- questions: Schema.Record(Schema.String, Question)
95
+ questions: Schema.Record(Schema.String, Question),
96
+ images: Schema.optional(Schema.Array(Image))
68
97
  })
69
98
 
70
99
  /**
@@ -82,7 +111,7 @@ export const ChoiceAnswer = Schema.Struct({
82
111
  })
83
112
 
84
113
  /**
85
- * A zero-based rating and index-keyed distribution.
114
+ * A zero-based rating and index-keyed distribution. `legend` maps indices to descriptions.
86
115
  *
87
116
  * @stability unstable
88
117
  * @category schemas
@@ -93,7 +122,7 @@ export const ScoreAnswer = Schema.Struct({
93
122
  score: Schema.Number,
94
123
  probabilities: Schema.Record(Schema.String, Schema.Number),
95
124
  confidence: Schema.Number,
96
- legend: Schema.Record(Schema.String, Schema.String)
125
+ legend: Schema.Record(Schema.String, Schema.Json)
97
126
  })
98
127
 
99
128
  /**