@effect/ai-cloudflare 0.0.0-stage → 4.0.1

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.
Files changed (106) hide show
  1. package/AGENTS.md +410 -0
  2. package/CLAUDE.md +410 -0
  3. package/LICENSE +21 -0
  4. package/README.md +43 -2
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  69. package/ai-docs/src/60_child-process/index.md +3 -0
  70. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  71. package/ai-docs/src/70_cli/index.md +5 -0
  72. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  73. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  74. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  75. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  76. package/ai-docs/src/71_ai/index.md +5 -0
  77. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  78. package/ai-docs/src/80_cluster/index.md +4 -0
  79. package/ai-docs/src/index.md +10 -0
  80. package/ai-docs/tsconfig.json +24 -0
  81. package/dist/CloudflareClient.d.ts +79 -0
  82. package/dist/CloudflareClient.d.ts.map +1 -0
  83. package/dist/CloudflareClient.js +86 -0
  84. package/dist/CloudflareClient.js.map +1 -0
  85. package/dist/CloudflareDecisionModel.d.ts +49 -0
  86. package/dist/CloudflareDecisionModel.d.ts.map +1 -0
  87. package/dist/CloudflareDecisionModel.js +122 -0
  88. package/dist/CloudflareDecisionModel.js.map +1 -0
  89. package/dist/CloudflareSchema.d.ts +186 -0
  90. package/dist/CloudflareSchema.d.ts.map +1 -0
  91. package/dist/CloudflareSchema.js +128 -0
  92. package/dist/CloudflareSchema.js.map +1 -0
  93. package/dist/index.d.ts +19 -0
  94. package/dist/index.d.ts.map +1 -0
  95. package/dist/index.js +20 -0
  96. package/dist/index.js.map +1 -0
  97. package/dist/internal/errors.d.ts +7 -0
  98. package/dist/internal/errors.d.ts.map +1 -0
  99. package/dist/internal/errors.js +109 -0
  100. package/dist/internal/errors.js.map +1 -0
  101. package/package.json +58 -3
  102. package/src/CloudflareClient.ts +149 -0
  103. package/src/CloudflareDecisionModel.ts +111 -0
  104. package/src/CloudflareSchema.ts +131 -0
  105. package/src/index.ts +23 -0
  106. package/src/internal/errors.ts +101 -0
@@ -0,0 +1,158 @@
1
+ /**
2
+ * @title Stateful chat sessions
3
+ *
4
+ * The AI `Chat` module maintains conversation history automatically. Build
5
+ * AI agents or chat assistants.
6
+ */
7
+ import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai"
8
+ import { Config, Context, DateTime, Effect, Layer, Ref, Schema } from "effect"
9
+ import { AiError, Chat, Prompt, Tool, Toolkit } from "effect/ai"
10
+ import { FetchHttpClient } from "effect/http"
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Provider setup
14
+ // ---------------------------------------------------------------------------
15
+
16
+ const OpenAiClientLayer = OpenAiClient.layerConfig({
17
+ apiKey: Config.Redacted("OPENAI_API_KEY")
18
+ }).pipe(Layer.provide(FetchHttpClient.layer))
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Tools for the agentic loop
22
+ // ---------------------------------------------------------------------------
23
+
24
+ const Tools = Toolkit.make(Tool.make("getCurrentTime", {
25
+ description: "Get the current time in ISO format",
26
+ parameters: Schema.Struct({
27
+ id: Schema.String
28
+ }),
29
+ success: Schema.String
30
+ }))
31
+
32
+ const ToolsLayer = Tools.toLayer(Effect.gen(function*() {
33
+ yield* Effect.logDebug("Initializing tools...")
34
+ return Tools.of({
35
+ getCurrentTime: Effect.fn("Tools.getCurrentTime")(function*(_) {
36
+ const now = yield* DateTime.now
37
+ return DateTime.formatIso(now)
38
+ })
39
+ })
40
+ }))
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Service that wraps Chat for a domain use-case
44
+ // ---------------------------------------------------------------------------
45
+
46
+ export class AiAssistantError extends Schema.TaggedError<AiAssistantError>()("AiAssistantError", {
47
+ reason: AiError.AiErrorReason
48
+ }) {
49
+ static fromAiError(error: AiError.AiError) {
50
+ return new AiAssistantError({ reason: error.reason })
51
+ }
52
+ }
53
+
54
+ export class AiAssistant extends Context.Service<AiAssistant, {
55
+ // Send a message while maintaining conversation history across turns.
56
+ chat(message: string): Effect.Effect<string, AiAssistantError>
57
+ // Ask a question and use an agentic loop with tool calls to answer it.
58
+ agent(question: string): Effect.Effect<string, AiAssistantError>
59
+ }>()("acme/AiAssistant") {
60
+ static readonly layer = Layer.effect(
61
+ AiAssistant,
62
+ Effect.gen(function*() {
63
+ // Choose the model you want to use for the chat sessions.
64
+ const modelLayer = yield* OpenAiLanguageModel.model("gpt-5.2").captureRequirements
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // 1. Chat.empty — basic multi-turn conversation
68
+ // ---------------------------------------------------------------------------
69
+
70
+ // Create a new chat session with `Chat.empty` or `Chat.fromPrompt`. The
71
+ // session maintains conversation history automatically, so you can focus on
72
+ // the current turn without having to manage context.
73
+ const newSession = yield* Chat.fromPrompt(Prompt.empty.pipe(
74
+ Prompt.setSystem("You are a helpful assistant that answers questions.")
75
+ ))
76
+
77
+ // You can also create a chat using a json export.
78
+ const json = yield* newSession.exportJson
79
+ const session = yield* Chat.fromJson(json)
80
+
81
+ const chat = Effect.fn("AiAssistant.chat")(
82
+ function*(message: string) {
83
+ // Create a new turn in the conversation by passing the user's message
84
+ // to `session.generateText`.
85
+ const response = yield* session.generateText({ prompt: message }).pipe(
86
+ // Provide the model layer to use.
87
+ // You could potentially use different models for different turns,
88
+ // or even switch models in the middle of a conversation.
89
+ Effect.provide(modelLayer)
90
+ )
91
+
92
+ // You can inspect the accumulated history at any point through the
93
+ // `history` ref on the chat instance.
94
+ const history = yield* Ref.get(session.history)
95
+ yield* Effect.logInfo(
96
+ `Conversation has ${history.content.length} messages`
97
+ )
98
+
99
+ return response.text
100
+ },
101
+ Effect.mapError((error) => AiAssistantError.fromAiError(error))
102
+ )
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // 2. Create agentic loops with tools
106
+ // ---------------------------------------------------------------------------
107
+
108
+ const tools = yield* Tools
109
+ const agent = Effect.fn("AiAssistant.agent")(
110
+ function*(question: string) {
111
+ // We start the agent with a system prompt and the user question. The
112
+ // agent can then call tools in a loop until it decides to return a
113
+ // final answer.
114
+ const session = yield* Chat.fromPrompt([
115
+ { role: "system", content: "You are an assistant that can use tools to answer questions." },
116
+ { role: "user", content: question }
117
+ ])
118
+
119
+ while (true) {
120
+ const response = yield* session.generateText({
121
+ prompt: [], // No additional prompt — the model has full access to the conversation history
122
+ toolkit: tools // Provide the tools to the model
123
+ }).pipe(
124
+ // Provide the model layer to use.
125
+ // You could potentially use different models for different turns,
126
+ // or even switch models in the middle of a conversation.
127
+ Effect.provide(modelLayer)
128
+ )
129
+ if (response.toolCalls.length > 0) {
130
+ // If the model called any tools, execute them and the Chat module
131
+ // will automatically add the tool results to the conversation
132
+ // history before the next turn.
133
+ continue
134
+ }
135
+ // If there are no tool calls, the model has returned a final answer
136
+ // and we can exit the loop.
137
+ return response.text
138
+ }
139
+ },
140
+ // Remap AI errors to our domain-specific error type, but die on
141
+ // unexpected errors.
142
+ Effect.catchTag(
143
+ "AiError",
144
+ (error) => Effect.fail(AiAssistantError.fromAiError(error)),
145
+ (e) => Effect.die(e)
146
+ )
147
+ )
148
+
149
+ return AiAssistant.of({
150
+ chat,
151
+ agent
152
+ })
153
+ })
154
+ ).pipe(
155
+ // Provide the OpenAI client and tools layers to the AiAssistant service.
156
+ Layer.provide([OpenAiClientLayer, ToolsLayer])
157
+ )
158
+ }
@@ -0,0 +1,9 @@
1
+ import { Schema } from "effect"
2
+
3
+ export class LaunchPlan extends Schema.Class<LaunchPlan>("LaunchPlan")({
4
+ audience: Schema.Literals(["developers", "operators", "platform teams"]),
5
+ channels: Schema.Array(Schema.String),
6
+ launchDate: Schema.String,
7
+ summary: Schema.String,
8
+ keyRisks: Schema.Array(Schema.String)
9
+ }) {}
@@ -0,0 +1,5 @@
1
+ ## Working with AI modules
2
+
3
+ Effect's AI modules provide a provider-agnostic interface for language models.
4
+ You can generate text, decode structured objects with `Schema` and stream partial
5
+ responses.
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @title Defining cluster entities
3
+ *
4
+ * Define distributed entity RPCs and run them in a cluster.
5
+ */
6
+ import { NodeClusterSocket, NodeRuntime } from "@effect/platform-node"
7
+ import { Effect, Layer, Ref, Schema } from "effect"
8
+ import { ClusterSchema, Entity, TestRunner } from "effect/cluster"
9
+ import { Rpc } from "effect/rpc"
10
+ import type { SqlClient } from "effect/sql"
11
+
12
+ export const Increment = Rpc.make("Increment", {
13
+ payload: { amount: Schema.Int },
14
+ success: Schema.Int
15
+ })
16
+
17
+ export const GetCount = Rpc.make("GetCount", {
18
+ success: Schema.Int
19
+ })
20
+ // If you want GetCount messages to be persisted, you can annotate the RPC
21
+ // schema with `ClusterSchema.Persisted`.
22
+ //
23
+ // By default, messages are volatile and only sent over a network.
24
+ .annotate(ClusterSchema.Persisted, true)
25
+
26
+ // `Entity.make` takes an array of Rpc definitions
27
+ export const Counter = Entity.make("Counter", [Increment, GetCount])
28
+
29
+ // Entity handlers can keep in-memory state while the entity is active.
30
+ // `maxIdleTime` controls passivation: if the entity is idle long enough, it is
31
+ // stopped and later recreated on demand.
32
+ export const CounterEntityLayer = Counter.toLayer(
33
+ Effect.gen(function*() {
34
+ const count = yield* Ref.make(0)
35
+
36
+ return Counter.of({
37
+ Increment: ({ payload }) => Ref.updateAndGet(count, (current) => current + payload.amount),
38
+ GetCount: () =>
39
+ Ref.get(count).pipe(
40
+ // Add Rpc.fork to allow the GetCount handler to run concurrently with
41
+ // Increment handlers.
42
+ //
43
+ // This opts-out of the default behavior where all handlers for a
44
+ // given entity run sequentially.
45
+ Rpc.fork
46
+ )
47
+ })
48
+ }),
49
+ { maxIdleTime: "5 minutes" }
50
+ )
51
+
52
+ // If you ever need to access an entity client, you can use the `client`
53
+ // property on the entity definition.
54
+ export const useCounter = Effect.gen(function*() {
55
+ const clientFor = yield* Counter.client
56
+ const counter = clientFor("counter-123")
57
+
58
+ const afterIncrement = yield* counter.Increment({ amount: 1 })
59
+ const currentCount = yield* counter.GetCount()
60
+
61
+ console.log(`Count after increment: ${afterIncrement}, current count: ${currentCount}`)
62
+ })
63
+
64
+ // `SingleRunner.layer` is useful for local development / tests where you still
65
+ // want the cluster entity runtime model.
66
+ declare const SqlClientLayer: Layer.Layer<SqlClient.SqlClient>
67
+
68
+ // Create the cluster layer using `NodeClusterSocket.layer`
69
+ const ClusterLayer = NodeClusterSocket.layer().pipe(
70
+ Layer.provide(SqlClientLayer)
71
+ )
72
+
73
+ // You can also use `TestRunner.layer` to run your entities in a single process,
74
+ // without any network communication and in-memory storage. This is useful for testing and
75
+ // development.
76
+ const ClusterLayerTest = TestRunner.layer
77
+
78
+ // Merge all your entity layers together and provide the cluster layer to run
79
+ // them in a cluster.
80
+ const EntitiesLayer = Layer.mergeAll(
81
+ CounterEntityLayer
82
+ )
83
+
84
+ const ProductionLayer = EntitiesLayer.pipe(
85
+ Layer.provide(ClusterLayer)
86
+ )
87
+
88
+ export const TestLayer = EntitiesLayer.pipe(
89
+ // For testing, we can use `Layer.provideMerge` to tests can access storage
90
+ // and other cluster services directly.
91
+ Layer.provideMerge(ClusterLayerTest)
92
+ )
93
+
94
+ // Finally, run your app with the entities layer.
95
+ Layer.launch(ProductionLayer).pipe(
96
+ NodeRuntime.runMain
97
+ )
@@ -0,0 +1,4 @@
1
+ ## Building distributed applications with cluster
2
+
3
+ The cluster modules let you model stateful services as entities and distribute
4
+ them across multiple machines.
@@ -0,0 +1,10 @@
1
+ # Effect library documentation
2
+
3
+ This documentation covers the Effect library and its related packages.
4
+
5
+ When you need to find information about Effect, use this documentation and the
6
+ Effect source code available in your environment. Avoid unrelated copies of
7
+ Effect or external documentation, as they may be outdated or incorrect.
8
+
9
+ **Note**: The examples in this documentation contain comments for illustration
10
+ purposes. In practice, you would not include these comments in your code.
@@ -0,0 +1,24 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "../tsconfig.base.json",
4
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
5
+ "compilerOptions": {
6
+ "rootDir": ".",
7
+ "noEmit": true,
8
+ "declaration": false,
9
+ "declarationMap": false,
10
+ "composite": false,
11
+ "incremental": false,
12
+ "types": ["node"],
13
+ "plugins": [
14
+ {
15
+ "name": "@effect/language-service",
16
+ "namespaceImportPackages": [],
17
+ "diagnosticSeverity": {
18
+ "floatingEffect": "off",
19
+ "preferSchemaOverJson": "off"
20
+ }
21
+ }
22
+ ]
23
+ }
24
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * HTTP client for Cloudflare Clef decisions through Workers AI REST.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as AiError from "effect/ai/AiError";
8
+ import * as Config from "effect/Config";
9
+ import * as Context from "effect/Context";
10
+ import * as Effect from "effect/Effect";
11
+ import * as HttpClient from "effect/http/HttpClient";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Redacted from "effect/Redacted";
14
+ import * as CloudflareSchema from "./CloudflareSchema.ts";
15
+ /**
16
+ * Low-level Cloudflare decision operations.
17
+ *
18
+ * @stability unstable
19
+ * @category services
20
+ * @since 4.0.0
21
+ */
22
+ export interface Service {
23
+ readonly client: HttpClient.HttpClient;
24
+ readonly createDecisions: (request: typeof CloudflareSchema.DecisionsRequest.Encoded) => Effect.Effect<typeof CloudflareSchema.DecisionsResponse.Type, AiError.AiError>;
25
+ }
26
+ declare const CloudflareClient_base: Context.ServiceClass<CloudflareClient, "@effect/ai-cloudflare/CloudflareClient", Service>;
27
+ /**
28
+ * Cloudflare Workers AI client service.
29
+ *
30
+ * @stability unstable
31
+ * @category services
32
+ * @since 4.0.0
33
+ */
34
+ export declare class CloudflareClient extends CloudflareClient_base {
35
+ }
36
+ /**
37
+ * Account, authentication, API base URL, and HTTP customization options.
38
+ *
39
+ * @stability unstable
40
+ * @category options
41
+ * @since 4.0.0
42
+ */
43
+ export interface Options {
44
+ readonly accountId: string;
45
+ readonly apiKey: Redacted.Redacted<string>;
46
+ readonly apiUrl?: string | undefined;
47
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined;
48
+ }
49
+ /**
50
+ * Builds a Cloudflare client without automatic retries.
51
+ *
52
+ * @stability unstable
53
+ * @category constructors
54
+ * @since 4.0.0
55
+ */
56
+ export declare const make: (options: Options) => Effect.Effect<Service, never, HttpClient.HttpClient>;
57
+ /**
58
+ * Provides a Cloudflare client from explicit options.
59
+ *
60
+ * @stability unstable
61
+ * @category layers
62
+ * @since 4.0.0
63
+ */
64
+ export declare const layer: (options: Options) => Layer.Layer<CloudflareClient, never, HttpClient.HttpClient>;
65
+ /**
66
+ * Provides a client from configuration, defaulting to CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN.
67
+ *
68
+ * @stability unstable
69
+ * @category layers
70
+ * @since 4.0.0
71
+ */
72
+ export declare const layerConfig: (options?: {
73
+ readonly accountId?: Config.Config<string> | undefined;
74
+ readonly apiKey?: Config.Config<Redacted.Redacted<string>> | undefined;
75
+ readonly apiUrl?: Config.Config<string> | undefined;
76
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined;
77
+ }) => Layer.Layer<CloudflareClient, Config.ConfigError, HttpClient.HttpClient>;
78
+ export {};
79
+ //# sourceMappingURL=CloudflareClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareClient.d.ts","sourceRoot":"","sources":["../src/CloudflareClient.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,OAAO,MAAM,mBAAmB,CAAA;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,OAAO,MAAM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EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,SAAS,CAAA;IACtD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,CAAA;IACtE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,SAAS,CAAA;IACnD,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC,UAAU,KAAK,UAAU,CAAC,UAAU,CAAC,GAAG,SAAS,CAAA;CAClG,KAAG,KAAK,CAAC,KAAK,CAAC,gBAAgB,EAAE,MAAM,CAAC,WAAW,EAAE,UAAU,CAAC,UAAU,CAWxE,CAAA"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * HTTP client for Cloudflare Clef decisions through Workers AI REST.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as AiError from "effect/ai/AiError";
8
+ import * as Config from "effect/Config";
9
+ import * as Context from "effect/Context";
10
+ import * as Effect from "effect/Effect";
11
+ import { flow, identity } from "effect/Function";
12
+ import * as HttpClient from "effect/http/HttpClient";
13
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
14
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
15
+ import * as Layer from "effect/Layer";
16
+ import * as Redacted from "effect/Redacted";
17
+ import * as Schema from "effect/Schema";
18
+ import * as CloudflareSchema from "./CloudflareSchema.js";
19
+ import * as Errors from "./internal/errors.js";
20
+ /**
21
+ * Cloudflare Workers AI client service.
22
+ *
23
+ * @stability unstable
24
+ * @category services
25
+ * @since 4.0.0
26
+ */
27
+ export class CloudflareClient extends /*#__PURE__*/Context.Service()("@effect/ai-cloudflare/CloudflareClient") {}
28
+ const decodeResponse = /*#__PURE__*/HttpClientResponse.schemaBodyJson(/*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Struct({
29
+ success: /*#__PURE__*/Schema.Literal(true),
30
+ result: CloudflareSchema.DecisionsResponse
31
+ }), /*#__PURE__*/Schema.Struct({
32
+ success: /*#__PURE__*/Schema.Literal(false)
33
+ })]));
34
+ /**
35
+ * Builds a Cloudflare client without automatic retries.
36
+ *
37
+ * @stability unstable
38
+ * @category constructors
39
+ * @since 4.0.0
40
+ */
41
+ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
42
+ const base = yield* HttpClient.HttpClient;
43
+ const client = base.pipe(HttpClient.mapRequest(flow(HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.cloudflare.com/client/v4"), HttpClientRequest.bearerToken(Redacted.value(options.apiKey)), HttpClientRequest.acceptJson)), HttpClient.filterStatusOk, options.transformClient ?? identity);
44
+ const path = `/accounts/${encodeURIComponent(options.accountId)}/ai/run/@cf/cloudflare/`;
45
+ return CloudflareClient.of({
46
+ client,
47
+ createDecisions: payload => HttpClientRequest.bodyJson(HttpClientRequest.post(path + payload.model), payload).pipe(Effect.mapError(error => AiError.make({
48
+ module: "CloudflareClient",
49
+ method: "createDecisions",
50
+ reason: new AiError.InvalidRequestError({
51
+ description: String(error)
52
+ })
53
+ })), Effect.flatMap(client.execute), Effect.flatMap(response => decodeResponse(response).pipe(Effect.flatMap(body => body.success ? Effect.succeed(body.result) : Errors.mapResponseError(response)))), Effect.catchTags({
54
+ HttpClientError: Errors.mapHttpClientError,
55
+ SchemaError: error => Effect.fail(AiError.make({
56
+ module: "CloudflareClient",
57
+ method: "createDecisions",
58
+ reason: AiError.InvalidOutputError.fromSchemaError(error)
59
+ }))
60
+ }))
61
+ });
62
+ });
63
+ /**
64
+ * Provides a Cloudflare client from explicit options.
65
+ *
66
+ * @stability unstable
67
+ * @category layers
68
+ * @since 4.0.0
69
+ */
70
+ export const layer = options => Layer.effect(CloudflareClient, make(options));
71
+ /**
72
+ * Provides a client from configuration, defaulting to CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN.
73
+ *
74
+ * @stability unstable
75
+ * @category layers
76
+ * @since 4.0.0
77
+ */
78
+ export const layerConfig = options => Layer.effect(CloudflareClient, Effect.gen(function* () {
79
+ return yield* make({
80
+ accountId: yield* options?.accountId ?? Config.String("CLOUDFLARE_ACCOUNT_ID"),
81
+ apiKey: yield* options?.apiKey ?? Config.Redacted("CLOUDFLARE_API_TOKEN"),
82
+ apiUrl: options?.apiUrl ? yield* options.apiUrl : undefined,
83
+ transformClient: options?.transformClient
84
+ });
85
+ }));
86
+ //# sourceMappingURL=CloudflareClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareClient.js","names":[],"sources":["../src/CloudflareClient.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;AAMA,OAAO,KAAK,OAAO,MAAM,mBAAmB;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,OAAO,MAAM,gBAAgB;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,SAAS,IAAI,EAAE,QAAQ,QAAQ,iBAAiB;AAChD,OAAO,KAAK,UAAU,MAAM,wBAAwB;AACpD,OAAO,KAAK,iBAAiB,MAAM,+BAA+B;AAClE,OAAO,KAAK,kBAAkB,MAAM,gCAAgC;AACpE,OAAO,KAAK,KAAK,MAAM,cAAc;AACrC,OAAO,KAAK,QAAQ,MAAM,iBAAiB;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,gBAAgB,MAAM,uBAAuB;AACzD,OAAO,KAAK,MAAM,MAAM,sBAAsB;AAgB9C;;;;;;;AAOA,OAAM,MAAO,gBACX,sBAAQ,OAAO,CAAC,OAAO,EAA6B,CAAC,wCAAwC,CAAC;AAiBhG,MAAM,cAAc,gBAAG,kBAAkB,CAAC,cAAc,cAAC,MAAM,CAAC,KAAK,CAAC,cACpE,MAAM,CAAC,MAAM,CAAC;EAAE,OAAO,eAAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;EAAE,MAA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* @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as DecisionModel from "effect/ai/DecisionModel";
8
+ import * as AiModel from "effect/ai/Model";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ import { CloudflareClient } from "./CloudflareClient.ts";
12
+ import type * as CloudflareSchema from "./CloudflareSchema.ts";
13
+ /**
14
+ * Cloudflare Clef model identifiers.
15
+ *
16
+ * @stability unstable
17
+ * @category models
18
+ * @since 4.0.0
19
+ */
20
+ export type Model = typeof CloudflareSchema.DecisionsRequest.Encoded["model"];
21
+ /**
22
+ * Creates a decision model with Cloudflare provider metadata.
23
+ *
24
+ * @stability unstable
25
+ * @category constructors
26
+ * @since 4.0.0
27
+ */
28
+ export declare const model: (model: Model) => AiModel.Model<"cloudflare", DecisionModel.DecisionModel, CloudflareClient>;
29
+ /**
30
+ * Builds a decision service with tolerance for four-decimal probability rounding.
31
+ *
32
+ * @stability unstable
33
+ * @category constructors
34
+ * @since 4.0.0
35
+ */
36
+ export declare const make: (options: {
37
+ readonly model: Model;
38
+ }) => Effect.Effect<DecisionModel.DecisionModel, never, CloudflareClient>;
39
+ /**
40
+ * Provides DecisionModel using an existing CloudflareClient.
41
+ *
42
+ * @stability unstable
43
+ * @category layers
44
+ * @since 4.0.0
45
+ */
46
+ export declare const layer: (options: {
47
+ readonly model: Model;
48
+ }) => Layer.Layer<DecisionModel.DecisionModel, never, CloudflareClient>;
49
+ //# sourceMappingURL=CloudflareDecisionModel.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Cloudflare Clef implementation of DecisionModel over Workers AI REST.
3
+ *
4
+ * @stability unstable
5
+ * @since 4.0.0
6
+ */
7
+ import * as DecisionModel from "effect/ai/DecisionModel";
8
+ import * as AiModel from "effect/ai/Model";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ import { CloudflareClient } from "./CloudflareClient.js";
12
+ /**
13
+ * Creates a decision model with Cloudflare provider metadata.
14
+ *
15
+ * @stability unstable
16
+ * @category constructors
17
+ * @since 4.0.0
18
+ */
19
+ export const model = model => AiModel.make("cloudflare", model, layer({
20
+ model
21
+ }));
22
+ /**
23
+ * Builds a decision service with tolerance for four-decimal probability rounding.
24
+ *
25
+ * @stability unstable
26
+ * @category constructors
27
+ * @since 4.0.0
28
+ */
29
+ export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
30
+ const client = yield* CloudflareClient;
31
+ return yield* DecisionModel.make({
32
+ probabilityPrecision: 4,
33
+ decide: Effect.fnUntraced(function* ({
34
+ state,
35
+ decisions
36
+ }) {
37
+ const questions = Object.create(null);
38
+ for (const [key, decision] of Object.entries(decisions)) {
39
+ switch (decision._tag) {
40
+ case "Classify":
41
+ questions[key] = {
42
+ type: "choice",
43
+ instructions: decision.instructions,
44
+ criteria: decision.criteria
45
+ };
46
+ break;
47
+ case "Rate":
48
+ questions[key] = {
49
+ type: "score",
50
+ instructions: decision.instructions,
51
+ criteria: decision.criteria
52
+ };
53
+ break;
54
+ case "Probability":
55
+ questions[key] = {
56
+ type: "noul",
57
+ instructions: decision.instructions,
58
+ criteria: decision.criteria
59
+ };
60
+ break;
61
+ }
62
+ }
63
+ const response = yield* client.createDecisions({
64
+ model: options.model,
65
+ state,
66
+ questions
67
+ });
68
+ const answers = Object.create(null);
69
+ for (const [key, decision] of Object.entries(decisions)) {
70
+ const answer = response.answers[key];
71
+ switch (answer?.type) {
72
+ case "choice":
73
+ answers[key] = {
74
+ _tag: "Classify",
75
+ label: answer.choice,
76
+ probabilities: answer.probabilities,
77
+ confidence: answer.confidence
78
+ };
79
+ break;
80
+ case "score":
81
+ {
82
+ const levels = decision._tag === "Rate" ? decision.criteria : [];
83
+ const probabilities = Object.create(null);
84
+ for (let index = 0; index < levels.length; index++) {
85
+ const probability = answer.probabilities[String(index)];
86
+ if (probability !== undefined) probabilities[levels[index]] = probability;
87
+ }
88
+ answers[key] = {
89
+ _tag: "Rate",
90
+ rating: answer.score,
91
+ probabilities,
92
+ confidence: answer.confidence
93
+ };
94
+ break;
95
+ }
96
+ case "noul":
97
+ answers[key] = {
98
+ _tag: "Probability",
99
+ probability: answer.noul
100
+ };
101
+ break;
102
+ }
103
+ }
104
+ return {
105
+ answers,
106
+ usage: {
107
+ inputTokens: response.usage.input_tokens,
108
+ outputTokens: response.usage.output_tokens
109
+ }
110
+ };
111
+ })
112
+ });
113
+ });
114
+ /**
115
+ * Provides DecisionModel using an existing CloudflareClient.
116
+ *
117
+ * @stability unstable
118
+ * @category layers
119
+ * @since 4.0.0
120
+ */
121
+ export const layer = options => Layer.effect(DecisionModel.DecisionModel, make(options));
122
+ //# sourceMappingURL=CloudflareDecisionModel.js.map