@codilore/llm 1.15.13

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 (145) hide show
  1. package/AGENTS.md +321 -0
  2. package/README.md +131 -0
  3. package/example/call-sites.md +591 -0
  4. package/example/tutorial.ts +255 -0
  5. package/package.json +50 -0
  6. package/script/recording-cost-report.ts +250 -0
  7. package/script/setup-recording-env.ts +542 -0
  8. package/src/cache-policy.ts +111 -0
  9. package/src/index.ts +32 -0
  10. package/src/llm.ts +186 -0
  11. package/src/protocols/anthropic-messages.ts +841 -0
  12. package/src/protocols/bedrock-converse.ts +649 -0
  13. package/src/protocols/bedrock-event-stream.ts +87 -0
  14. package/src/protocols/gemini.ts +465 -0
  15. package/src/protocols/index.ts +6 -0
  16. package/src/protocols/openai-chat.ts +431 -0
  17. package/src/protocols/openai-compatible-chat.ts +24 -0
  18. package/src/protocols/openai-responses.ts +987 -0
  19. package/src/protocols/shared.ts +283 -0
  20. package/src/protocols/utils/bedrock-auth.ts +70 -0
  21. package/src/protocols/utils/bedrock-cache.ts +37 -0
  22. package/src/protocols/utils/bedrock-media.ts +80 -0
  23. package/src/protocols/utils/cache.ts +16 -0
  24. package/src/protocols/utils/gemini-tool-schema.ts +101 -0
  25. package/src/protocols/utils/lifecycle.ts +102 -0
  26. package/src/protocols/utils/openai-options.ts +84 -0
  27. package/src/protocols/utils/tool-stream.ts +218 -0
  28. package/src/provider.ts +37 -0
  29. package/src/providers/amazon-bedrock.ts +43 -0
  30. package/src/providers/anthropic.ts +35 -0
  31. package/src/providers/azure.ts +110 -0
  32. package/src/providers/cloudflare.ts +127 -0
  33. package/src/providers/github-copilot.ts +66 -0
  34. package/src/providers/google.ts +35 -0
  35. package/src/providers/index.ts +11 -0
  36. package/src/providers/openai-compatible-profile.ts +20 -0
  37. package/src/providers/openai-compatible.ts +65 -0
  38. package/src/providers/openai-options.ts +81 -0
  39. package/src/providers/openai.ts +63 -0
  40. package/src/providers/openrouter.ts +98 -0
  41. package/src/providers/xai.ts +56 -0
  42. package/src/route/auth-options.ts +57 -0
  43. package/src/route/auth.ts +156 -0
  44. package/src/route/client.ts +434 -0
  45. package/src/route/endpoint.ts +53 -0
  46. package/src/route/executor.ts +374 -0
  47. package/src/route/framing.ts +27 -0
  48. package/src/route/index.ts +25 -0
  49. package/src/route/protocol.ts +84 -0
  50. package/src/route/transport/http.ts +108 -0
  51. package/src/route/transport/index.ts +33 -0
  52. package/src/route/transport/websocket.ts +280 -0
  53. package/src/schema/errors.ts +203 -0
  54. package/src/schema/events.ts +370 -0
  55. package/src/schema/ids.ts +43 -0
  56. package/src/schema/index.ts +5 -0
  57. package/src/schema/messages.ts +404 -0
  58. package/src/schema/options.ts +221 -0
  59. package/src/tool-runtime.ts +78 -0
  60. package/src/tool.ts +241 -0
  61. package/src/utils/record.ts +3 -0
  62. package/sst-env.d.ts +10 -0
  63. package/test/adapter.test.ts +164 -0
  64. package/test/auth-options.types.ts +168 -0
  65. package/test/auth.test.ts +103 -0
  66. package/test/cache-policy.test.ts +262 -0
  67. package/test/continuation-scenarios.ts +104 -0
  68. package/test/endpoint.test.ts +58 -0
  69. package/test/executor.test.ts +418 -0
  70. package/test/exports.test.ts +62 -0
  71. package/test/fixtures/media/restroom.png +0 -0
  72. package/test/fixtures/recordings/anthropic-messages/accepts-malformed-assistant-tool-order-with-default-patch.json +29 -0
  73. package/test/fixtures/recordings/anthropic-messages/anthropic-opus-4-7-image-tool-result.json +43 -0
  74. package/test/fixtures/recordings/anthropic-messages/claude-opus-4-7-drives-a-tool-loop.json +56 -0
  75. package/test/fixtures/recordings/anthropic-messages/rejects-malformed-assistant-tool-order-without-patch.json +29 -0
  76. package/test/fixtures/recordings/anthropic-messages/streams-text.json +29 -0
  77. package/test/fixtures/recordings/anthropic-messages/streams-tool-call.json +29 -0
  78. package/test/fixtures/recordings/anthropic-messages-cache/writes-then-reads-cache-control-on-identical-second-call.json +48 -0
  79. package/test/fixtures/recordings/bedrock-converse/drives-a-tool-loop.json +55 -0
  80. package/test/fixtures/recordings/bedrock-converse/streams-a-tool-call.json +29 -0
  81. package/test/fixtures/recordings/bedrock-converse/streams-text.json +29 -0
  82. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  83. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-llama-3-1-8b-text.json +32 -0
  84. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  85. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-llama-3-1-8b-text.json +32 -0
  86. package/test/fixtures/recordings/gemini/gemini-2-5-flash-image.json +32 -0
  87. package/test/fixtures/recordings/gemini/streams-text.json +28 -0
  88. package/test/fixtures/recordings/gemini/streams-tool-call.json +28 -0
  89. package/test/fixtures/recordings/gemini-cache/reports-cachedcontenttokencount-on-identical-second-call.json +46 -0
  90. package/test/fixtures/recordings/openai-chat/continues-after-tool-result.json +28 -0
  91. package/test/fixtures/recordings/openai-chat/drives-a-tool-loop-end-to-end.json +46 -0
  92. package/test/fixtures/recordings/openai-chat/streams-text.json +28 -0
  93. package/test/fixtures/recordings/openai-chat/streams-tool-call.json +28 -0
  94. package/test/fixtures/recordings/openai-compatible-chat/deepseek-streams-text.json +28 -0
  95. package/test/fixtures/recordings/openai-compatible-chat/groq-llama-3-3-70b-drives-a-tool-loop.json +53 -0
  96. package/test/fixtures/recordings/openai-compatible-chat/groq-streams-text.json +28 -0
  97. package/test/fixtures/recordings/openai-compatible-chat/groq-streams-tool-call.json +28 -0
  98. package/test/fixtures/recordings/openai-compatible-chat/openrouter-claude-opus-4-7-drives-a-tool-loop.json +54 -0
  99. package/test/fixtures/recordings/openai-compatible-chat/openrouter-gpt-4o-mini-drives-a-tool-loop.json +53 -0
  100. package/test/fixtures/recordings/openai-compatible-chat/openrouter-gpt-5-5-drives-a-tool-loop.json +54 -0
  101. package/test/fixtures/recordings/openai-compatible-chat/openrouter-streams-text.json +28 -0
  102. package/test/fixtures/recordings/openai-compatible-chat/openrouter-streams-tool-call.json +28 -0
  103. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-text.json +28 -0
  104. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-tool-call.json +28 -0
  105. package/test/fixtures/recordings/openai-responses/gpt-5-5-drives-a-tool-loop.json +54 -0
  106. package/test/fixtures/recordings/openai-responses/gpt-5-5-streams-text.json +28 -0
  107. package/test/fixtures/recordings/openai-responses/gpt-5-5-streams-tool-call.json +28 -0
  108. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-image-tool-result.json +42 -0
  109. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning-continuation.json +58 -0
  110. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning.json +32 -0
  111. package/test/fixtures/recordings/openai-responses-cache/reports-cached-tokens-on-identical-second-call.json +46 -0
  112. package/test/generate-object.test.ts +184 -0
  113. package/test/lib/effect.ts +50 -0
  114. package/test/lib/http.ts +98 -0
  115. package/test/lib/openai-chunks.ts +27 -0
  116. package/test/lib/sse.ts +17 -0
  117. package/test/lib/tool-runtime.ts +146 -0
  118. package/test/llm.test.ts +167 -0
  119. package/test/provider/anthropic-messages-cache.recorded.test.ts +54 -0
  120. package/test/provider/anthropic-messages.recorded.test.ts +46 -0
  121. package/test/provider/anthropic-messages.test.ts +829 -0
  122. package/test/provider/bedrock-converse-cache.recorded.test.ts +54 -0
  123. package/test/provider/bedrock-converse.test.ts +707 -0
  124. package/test/provider/cloudflare.test.ts +230 -0
  125. package/test/provider/gemini-cache.recorded.test.ts +48 -0
  126. package/test/provider/gemini.test.ts +476 -0
  127. package/test/provider/golden.recorded.test.ts +219 -0
  128. package/test/provider/openai-chat.test.ts +446 -0
  129. package/test/provider/openai-compatible-chat.test.ts +238 -0
  130. package/test/provider/openai-responses-cache.recorded.test.ts +46 -0
  131. package/test/provider/openai-responses.test.ts +1322 -0
  132. package/test/provider/openrouter.test.ts +56 -0
  133. package/test/provider.types.ts +41 -0
  134. package/test/recorded-golden.ts +97 -0
  135. package/test/recorded-runner.ts +100 -0
  136. package/test/recorded-scenarios.ts +531 -0
  137. package/test/recorded-test.ts +74 -0
  138. package/test/recorded-utils.ts +56 -0
  139. package/test/recorded-websocket.ts +26 -0
  140. package/test/route.test.ts +43 -0
  141. package/test/schema.test.ts +97 -0
  142. package/test/tool-runtime.test.ts +802 -0
  143. package/test/tool-stream.test.ts +99 -0
  144. package/test/tool.types.ts +40 -0
  145. package/tsconfig.json +15 -0
@@ -0,0 +1,230 @@
1
+ import { describe, expect } from "bun:test"
2
+ import { ConfigProvider, Effect, Schema } from "effect"
3
+ import { HttpClientRequest } from "effect/unstable/http"
4
+ import { LLM } from "../../src"
5
+ import { CloudflareAIGateway, CloudflareWorkersAI } from "../../src/providers/cloudflare"
6
+ import { LLMClient } from "../../src/route"
7
+ import { it } from "../lib/effect"
8
+ import { dynamicResponse } from "../lib/http"
9
+ import { sseEvents } from "../lib/sse"
10
+
11
+ const Json = Schema.fromJsonString(Schema.Unknown)
12
+ const decodeJson = Schema.decodeUnknownSync(Json)
13
+ const withEnv = (env: Record<string, string>) => Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))
14
+
15
+ const deltaChunk = (delta: object, finishReason: string | null = null) => ({
16
+ id: "chatcmpl_fixture",
17
+ choices: [{ delta, finish_reason: finishReason }],
18
+ usage: null,
19
+ })
20
+
21
+ describe("Cloudflare", () => {
22
+ it.effect("prepares AI Gateway models through the OpenAI-compatible Chat protocol", () =>
23
+ Effect.gen(function* () {
24
+ const model = CloudflareAIGateway.configure({
25
+ accountId: "test-account",
26
+ gatewayId: "test-gateway",
27
+ apiKey: "test-token",
28
+ }).model("workers-ai/@cf/meta/llama-3.3-70b-instruct")
29
+
30
+ expect(model).toMatchObject({
31
+ id: "workers-ai/@cf/meta/llama-3.3-70b-instruct",
32
+ provider: "cloudflare-ai-gateway",
33
+ route: { id: "cloudflare-ai-gateway" },
34
+ })
35
+ expect(model.route.endpoint.baseURL).toBe("https://gateway.ai.cloudflare.com/v1/test-account/test-gateway/compat")
36
+
37
+ const prepared = yield* LLMClient.prepare(LLM.request({ model, prompt: "Say hello." }))
38
+
39
+ expect(prepared.route).toBe("cloudflare-ai-gateway")
40
+ expect(prepared.body).toMatchObject({
41
+ model: "workers-ai/@cf/meta/llama-3.3-70b-instruct",
42
+ messages: [{ role: "user", content: "Say hello." }],
43
+ stream: true,
44
+ })
45
+ }),
46
+ )
47
+
48
+ it.effect("posts to the derived gateway endpoint with bearer auth", () =>
49
+ Effect.gen(function* () {
50
+ const response = yield* LLM.generate(
51
+ LLM.request({
52
+ model: CloudflareAIGateway.configure({
53
+ accountId: "test-account",
54
+ gatewayId: "test-gateway",
55
+ apiKey: "test-token",
56
+ }).model("openai/gpt-4o-mini"),
57
+ prompt: "Say hello.",
58
+ }),
59
+ ).pipe(
60
+ Effect.provide(
61
+ dynamicResponse((input) =>
62
+ Effect.gen(function* () {
63
+ const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
64
+ expect(web.url).toBe(
65
+ "https://gateway.ai.cloudflare.com/v1/test-account/test-gateway/compat/chat/completions",
66
+ )
67
+ expect(web.headers.get("authorization")).toBe("Bearer test-token")
68
+ expect(decodeJson(input.text)).toMatchObject({
69
+ model: "openai/gpt-4o-mini",
70
+ stream: true,
71
+ messages: [{ role: "user", content: "Say hello." }],
72
+ })
73
+ return input.respond(
74
+ sseEvents(deltaChunk({ role: "assistant", content: "Hello" }), deltaChunk({}, "stop")),
75
+ { headers: { "content-type": "text/event-stream" } },
76
+ )
77
+ }),
78
+ ),
79
+ ),
80
+ )
81
+
82
+ expect(response.text).toBe("Hello")
83
+ }),
84
+ )
85
+
86
+ it.effect("defaults AI Gateway id to default when omitted or blank", () =>
87
+ Effect.gen(function* () {
88
+ expect(
89
+ CloudflareAIGateway.configure({
90
+ accountId: "test-account",
91
+ gatewayId: "",
92
+ gatewayApiKey: "test-token",
93
+ }).model("workers-ai/@cf/meta/llama-3.3-70b-instruct").route.endpoint.baseURL,
94
+ ).toBe("https://gateway.ai.cloudflare.com/v1/test-account/default/compat")
95
+ }),
96
+ )
97
+
98
+ it.effect("supports authenticated AI Gateway plus upstream provider auth", () =>
99
+ Effect.gen(function* () {
100
+ yield* LLM.generate(
101
+ LLM.request({
102
+ model: CloudflareAIGateway.configure({
103
+ accountId: "test-account",
104
+ gatewayApiKey: "gateway-token",
105
+ apiKey: "provider-token",
106
+ }).model("openai/gpt-4o-mini"),
107
+ prompt: "Say hello.",
108
+ }),
109
+ ).pipe(
110
+ Effect.provide(
111
+ dynamicResponse((input) =>
112
+ Effect.gen(function* () {
113
+ const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
114
+ expect(web.url).toBe("https://gateway.ai.cloudflare.com/v1/test-account/default/compat/chat/completions")
115
+ expect(web.headers.get("cf-aig-authorization")).toBe("Bearer gateway-token")
116
+ expect(web.headers.get("authorization")).toBe("Bearer provider-token")
117
+ return input.respond(
118
+ sseEvents(deltaChunk({ role: "assistant", content: "Hello" }), deltaChunk({}, "stop")),
119
+ { headers: { "content-type": "text/event-stream" } },
120
+ )
121
+ }),
122
+ ),
123
+ ),
124
+ )
125
+ }),
126
+ )
127
+
128
+ it.effect("allows a fully configured baseURL override", () =>
129
+ Effect.gen(function* () {
130
+ const prepared = yield* LLMClient.prepare(
131
+ LLM.request({
132
+ model: CloudflareAIGateway.configure({
133
+ baseURL: "https://gateway.proxy.test/v1/custom/compat",
134
+ apiKey: "test-token",
135
+ }).model("openai/gpt-4o-mini"),
136
+ prompt: "Say hello.",
137
+ }),
138
+ )
139
+
140
+ expect(prepared.model.route.endpoint.baseURL).toBe("https://gateway.proxy.test/v1/custom/compat")
141
+ }),
142
+ )
143
+
144
+ it.effect("prepares direct Workers AI models through the OpenAI-compatible Chat protocol", () =>
145
+ Effect.gen(function* () {
146
+ const model = CloudflareWorkersAI.configure({
147
+ accountId: "test-account",
148
+ apiKey: "test-token",
149
+ }).model("@cf/meta/llama-3.1-8b-instruct")
150
+
151
+ expect(model).toMatchObject({
152
+ id: "@cf/meta/llama-3.1-8b-instruct",
153
+ provider: "cloudflare-workers-ai",
154
+ route: { id: "cloudflare-workers-ai" },
155
+ })
156
+ expect(model.route.endpoint.baseURL).toBe("https://api.cloudflare.com/client/v4/accounts/test-account/ai/v1")
157
+
158
+ const prepared = yield* LLMClient.prepare(LLM.request({ model, prompt: "Say hello." }))
159
+
160
+ expect(prepared.route).toBe("cloudflare-workers-ai")
161
+ expect(prepared.body).toMatchObject({
162
+ model: "@cf/meta/llama-3.1-8b-instruct",
163
+ messages: [{ role: "user", content: "Say hello." }],
164
+ stream: true,
165
+ })
166
+ }),
167
+ )
168
+
169
+ it.effect("posts direct Workers AI requests to the account endpoint with bearer auth", () =>
170
+ Effect.gen(function* () {
171
+ const response = yield* LLM.generate(
172
+ LLM.request({
173
+ model: CloudflareWorkersAI.configure({
174
+ accountId: "test-account",
175
+ apiKey: "test-token",
176
+ }).model("@cf/meta/llama-3.1-8b-instruct"),
177
+ prompt: "Say hello.",
178
+ }),
179
+ ).pipe(
180
+ Effect.provide(
181
+ dynamicResponse((input) =>
182
+ Effect.gen(function* () {
183
+ const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
184
+ expect(web.url).toBe("https://api.cloudflare.com/client/v4/accounts/test-account/ai/v1/chat/completions")
185
+ expect(web.headers.get("authorization")).toBe("Bearer test-token")
186
+ expect(decodeJson(input.text)).toMatchObject({
187
+ model: "@cf/meta/llama-3.1-8b-instruct",
188
+ stream: true,
189
+ messages: [{ role: "user", content: "Say hello." }],
190
+ })
191
+ return input.respond(
192
+ sseEvents(deltaChunk({ role: "assistant", content: "Hello" }), deltaChunk({}, "stop")),
193
+ { headers: { "content-type": "text/event-stream" } },
194
+ )
195
+ }),
196
+ ),
197
+ ),
198
+ )
199
+
200
+ expect(response.text).toBe("Hello")
201
+ }),
202
+ )
203
+
204
+ it.effect("supports direct Workers AI token aliases through auth config", () =>
205
+ Effect.gen(function* () {
206
+ yield* LLM.generate(
207
+ LLM.request({
208
+ model: CloudflareWorkersAI.configure({
209
+ accountId: "test-account",
210
+ }).model("@cf/meta/llama-3.1-8b-instruct"),
211
+ prompt: "Say hello.",
212
+ }),
213
+ ).pipe(
214
+ withEnv({ CLOUDFLARE_WORKERS_AI_TOKEN: "test-token" }),
215
+ Effect.provide(
216
+ dynamicResponse((input) =>
217
+ Effect.gen(function* () {
218
+ const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
219
+ expect(web.headers.get("authorization")).toBe("Bearer test-token")
220
+ return input.respond(
221
+ sseEvents(deltaChunk({ role: "assistant", content: "Hello" }), deltaChunk({}, "stop")),
222
+ { headers: { "content-type": "text/event-stream" } },
223
+ )
224
+ }),
225
+ ),
226
+ ),
227
+ )
228
+ }),
229
+ )
230
+ })
@@ -0,0 +1,48 @@
1
+ import { describe, expect } from "bun:test"
2
+ import { Effect } from "effect"
3
+ import { LLM } from "../../src"
4
+ import { LLMClient } from "../../src/route"
5
+ import * as Google from "../../src/providers/google"
6
+ import { LARGE_CACHEABLE_SYSTEM } from "../recorded-scenarios"
7
+ import { recordedTests } from "../recorded-test"
8
+
9
+ const model = Google.configure({
10
+ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GEMINI_API_KEY ?? "fixture",
11
+ }).model("gemini-2.5-flash")
12
+
13
+ // Gemini does implicit prefix caching on 2.5+ models above ~1024 tokens. The
14
+ // `CacheHint` is currently a no-op for Gemini (the explicit `CachedContent`
15
+ // API is out-of-band and intentionally not wired up). This test exists to
16
+ // pin the usage-parsing path: `cachedContentTokenCount` should surface as
17
+ // `cacheReadInputTokens` on the second identical call.
18
+ const cacheRequest = LLM.request({
19
+ id: "recorded_gemini_cache",
20
+ model,
21
+ system: LARGE_CACHEABLE_SYSTEM,
22
+ prompt: "Say hi.",
23
+ generation: { maxTokens: 16, temperature: 0 },
24
+ })
25
+
26
+ const recorded = recordedTests({
27
+ prefix: "gemini-cache",
28
+ provider: "google",
29
+ protocol: "gemini",
30
+ requires: ["GOOGLE_GENERATIVE_AI_API_KEY"],
31
+ // Two identical requests in one cassette — replay walks the cassette in
32
+ // recording order so the second call replays the cached-hit interaction.
33
+ })
34
+
35
+ describe("Gemini cache recorded", () => {
36
+ recorded.effect.with("reports cachedContentTokenCount on identical second call", { tags: ["cache"] }, () =>
37
+ Effect.gen(function* () {
38
+ const first = yield* LLMClient.generate(cacheRequest)
39
+ expect(first.usage?.cacheReadInputTokens ?? 0).toBeGreaterThanOrEqual(0)
40
+
41
+ const second = yield* LLMClient.generate(cacheRequest)
42
+ // Implicit caching is best-effort on Gemini's side; we assert the field
43
+ // is at least populated and non-negative. When re-recording, verify the
44
+ // cassette shows > 0 in the second response's usage.
45
+ expect(second.usage?.cacheReadInputTokens ?? 0).toBeGreaterThanOrEqual(0)
46
+ }),
47
+ )
48
+ })