Repository navigation
Expand file tree
/
Copy pathtutorial.ts
More file actions
284 lines (258 loc) · 10.6 KB
/
Copy pathtutorial.ts
File metadata and controls
284 lines (258 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { Config, Effect, Formatter, Schema, Stream } from "effect"
import { HttpClientResponse } from "effect/http"
import { NodeFileSystem } from "@effect/platform-node"
import { ai, AIClient, Media, Message, ProviderID, ToolRuntime } from "@opencode/ai/effect"
import { tool } from "@opencode/ai/effect"
import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor } from "@opencode/ai/route"
import { OpenAI } from "@opencode/ai/providers"
/**
* A runnable walkthrough of the LLM package use-site API.
*
* Run from `packages/ai` with an OpenAI key in the environment:
*
* OPENAI_API_KEY=... bun example/tutorial.ts [example]
*
* where `example` is one of the keys of `examples` at the bottom (default
* `tools`). The `fake` example runs offline and needs no key.
*
* The file is intentionally written as a normal TypeScript program. You can
* hover imports and local values to see how the public API is typed.
*/
const apiKey = Config.Redacted("OPENAI_API_KEY")
// 1. Configure a provider. The configured facade records provider identity,
// deployment options, authentication, and defaults. Per-modality selectors pick
// the API: `.responses(...)` / `.chat(...)` for LLM calls and `.image(...)` for
// image generation.
const openai = OpenAI.configure({
apiKey,
maxTokens: 160,
providerOptions: {
store: false,
},
})
const model = openai.responses("gpt-4o-mini")
// 2. Build a provider-neutral request. This is useful when reusing one request
// across generate and stream examples.
//
// Options can live on both the configured route/provider facade and the request:
//
// - `maxTokens`, `temperature`, `topP`, `topK`, penalties, `seed` and `stop`:
// common controls set at the top level.
// - `promptCacheKey`: stable cache affinity for protocols that support it.
// - `providerOptions`: model-typed provider-native behavior. For example,
// OpenAI store behavior, Anthropic thinking, Gemini thinking config, or
// OpenRouter routing/reasoning.
// - `http`: last-resort serializable overlays for final request body, headers,
// and query params. Prefer typed `providerOptions` when a field is stable.
//
// Route/provider options are defaults. Request options override them for this call.
const request = ai.request({
model,
system: "You are concise and practical.",
prompt: "Tell me a joke",
maxTokens: 80,
temperature: 0.7,
promptCacheKey: "tutorial-joke",
})
// 3. `generate` sends the request and collects the event stream into one
// response object. `response.text` is the collected text output.
const generateOnce = Effect.gen(function* () {
const response = yield* ai.generate(request)
console.log("\n== generate ==")
console.log("generated text:", response.text)
console.log("usage", Formatter.formatJson(response.usage, { space: 2 }))
})
// 4. `stream` exposes provider output as common `LLMEvent`s for UIs that want
// incremental text, reasoning, tool input, usage, or finish events.
const streamText = ai.stream(request).pipe(
Stream.tap((event) =>
Effect.sync(() => {
if (event.type === "text-delta") process.stdout.write(`\ntext: ${event.text}`)
if (event.type === "finish")
process.stdout.write(
`\nfinish: ${event.reason.normalized}${event.reason.raw ? ` (${event.reason.raw})` : ""}\n`,
)
}),
),
Stream.runDrain,
)
// 5. Tools are typed with Effect Schema. Provider turns remain explicit:
// advertise definitions on the request, stream one turn, dispatch local calls,
// then persist/build follow-up history in the enclosing product flow.
const tools = [
tool({
name: "get_weather",
description: "Get current weather for a city.",
input: Schema.Struct({ city: Schema.String }),
success: Schema.Struct({ forecast: Schema.String }),
execute: (input) => Effect.succeed({ forecast: `${input.city}: sunny, 72F` }),
}),
]
const streamWithTools = Effect.gen(function* () {
const request = ai.request({
model,
prompt: "Use get_weather for San Francisco, then answer in one sentence.",
maxTokens: 80,
temperature: 0,
tools,
})
const events = Array.from(yield* ai.stream(request).pipe(Stream.runCollect))
for (const event of events) {
if (event.type === "tool-call") console.log("tool call", event.name, event.input)
if (event.type === "text-delta") process.stdout.write(event.text)
if (event.type !== "tool-call" || event.providerExecuted) continue
const dispatched = yield* ToolRuntime.dispatch(tools, event)
console.log("tool result", event.name, dispatched.result)
// A durable agent would persist these messages before starting another
// raw model turn. This tutorial keeps the boundary visible instead.
const followUp = {
...request,
messages: [
...request.messages,
Message.assistant([event]),
Message.tool({ ...event, result: dispatched.result }),
],
}
console.log("follow-up history messages:", followUp.messages.length)
}
})
// 6. `schema` asks for structured output. It forces a hidden tool call, so the
// same call site works across providers, and decodes its input into `object`.
const WeatherReport = Schema.Struct({
city: Schema.String,
forecast: Schema.String,
highFahrenheit: Schema.Number,
})
const generateStructuredObject = Effect.gen(function* () {
const response = yield* ai.generate({
model,
system: "Return only structured weather data.",
prompt: "Give me today's weather for San Francisco.",
schema: WeatherReport,
maxTokens: 120,
temperature: 0,
})
console.log("\n== structured output ==")
console.log(Formatter.formatJson(response.object, { space: 2 }))
})
// If the shape is only known at runtime, pass raw JSON Schema instead. The
// `.object` type is `unknown`; callers that need static types should validate it.
const generateDynamicObject = ai.generate({
model,
prompt: "Extract the city and forecast from: San Francisco is sunny.",
schema: {
type: "object",
properties: {
city: { type: "string" },
forecast: { type: "string" },
},
required: ["city", "forecast"],
},
})
// -----------------------------------------------------------------------------
// Part 2: provider composition with a fake provider
// -----------------------------------------------------------------------------
// A protocol is the provider-native API shape: common request -> body, response
// frames -> common events. This fake one turns text prompts into a JSON body
// and treats every SSE frame as output text.
const FakeBody = Schema.Struct({
model: Schema.String,
input: Schema.String,
})
type FakeBody = Schema.Schema.Type<typeof FakeBody>
const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
// Protocol ids are open strings, so external packages can define their own
// protocols without changing this package.
id: "fake-echo",
body: {
schema: FakeBody,
from: (request) =>
Effect.succeed({
model: request.model.id,
input: request.messages
.flatMap((message) => [...message.content])
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n"),
}),
},
stream: {
event: Schema.String,
initial: () => undefined,
step: (_, frame) => Effect.succeed([undefined, [{ type: "text-delta", id: "text-0", text: frame }]] as const),
onHalt: () => Effect.succeed([{ type: "finish", reason: { normalized: "stop" } }]),
},
})
// A route is the runnable binding for that protocol. It adds the deployment
// axes that the protocol deliberately does not know: URL, auth, and framing.
const FakeAdapter = Route.make({
id: "fake-echo",
provider: "fake-echo",
protocol: FakeProtocol,
endpoint: Endpoint.path("/v1/echo", { baseURL: "https://fake.local" }),
auth: Auth.passthrough,
framing: Framing.sse,
})
// A provider module exports a configured facade. Configuration happens before
// model selection; model selectors accept ids only.
const FakeEcho = {
id: ProviderID.make("fake-echo"),
configure: () => ({
id: ProviderID.make("fake-echo"),
model: (id: string) => FakeAdapter.model({ id }),
}),
}
// 7. Run the fake provider offline. `RequestExecutor.middleware` sees every HTTP
// request before it is sent; here it answers with two SSE frames instead of
// calling the network.
const fakeExecutor = RequestExecutor.middleware((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
new Response("data: hello\n\ndata: from fake-echo\n\n", { headers: { "content-type": "text/event-stream" } }),
),
),
)
const generateFake = Effect.gen(function* () {
const response = yield* ai.generate({ model: FakeEcho.configure().model("echo-1"), prompt: "Say hello." })
console.log("\n== fake provider ==")
console.log("generated text:", response.text)
})
// 8. Image generation uses the same facade and the same request/generate shape.
// `response.images[0]` is a `Media.Asset`: bytes decode lazily and are cached, and
// `Media.write` persists them through the Effect `FileSystem`.
const generateImage = Effect.gen(function* () {
const response = yield* ai.image.generate({
model: openai.image("gpt-image-1-mini"),
prompt: "A flat black circle centered on a plain white background.",
aspect: "1:1",
// Exact pixel sizes and output formats are provider options.
providerOptions: { quality: "low", outputFormat: "jpeg" },
})
console.log("\n== image ==")
console.log("media type:", response.images[0].mediaType)
console.log("bytes:", (yield* response.images[0].bytes()).byteLength)
console.log("usage", Formatter.formatJson(response.usage, { space: 2 }))
yield* Media.write(response.images[0], "tutorial-image.jpg").pipe(Effect.provide(NodeFileSystem.layer))
})
// Provide every modality client and the HTTP request executor once with
// `AIClient.layer`; `AIClient.layerWith(executor)` swaps the executor, as the
// fake example does. One example runs at a time so the tutorial does not spend
// tokens on every path.
const examples: Record<string, Effect.Effect<void, unknown, AIClient.Services>> = {
generate: generateOnce,
stream: streamText,
tools: streamWithTools,
object: generateStructuredObject,
"dynamic-object": generateDynamicObject.pipe(
Effect.andThen((response) => Effect.sync(() => console.log(response.object))),
),
image: generateImage,
fake: generateFake,
}
const name = process.argv[2] ?? "tools"
if (!Object.hasOwn(examples, name))
throw new Error(`Unknown example ${name}; pick one of ${Object.keys(examples).join(", ")}`)
Effect.runPromise(
examples[name].pipe(Effect.provide(name === "fake" ? AIClient.layerWith(fakeExecutor) : AIClient.layer)),
)