tutorial.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { Config, Effect, Formatter, Layer, Schema, Stream } from "effect"
  2. import { LLM, LLMClient, LLMRequest, Message, ProviderID, Tool, ToolRuntime } from "@opencode-ai/ai"
  3. import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor, WebSocketExecutor } from "@opencode-ai/ai/route"
  4. import { OpenAI } from "@opencode-ai/ai/providers"
  5. /**
  6. * A runnable walkthrough of the LLM package use-site API.
  7. *
  8. * Run from `packages/ai` with an OpenAI key in the environment:
  9. *
  10. * OPENAI_API_KEY=... bun example/tutorial.ts
  11. *
  12. * The file is intentionally written as a normal TypeScript program. You can
  13. * hover imports and local values to see how the public API is typed.
  14. */
  15. const apiKey = Config.redacted("OPENAI_API_KEY")
  16. // 1. Pick a model. The provider helper records provider identity, protocol
  17. // choice, capabilities, deployment options, authentication, and defaults.
  18. const model = OpenAI.configure({
  19. apiKey,
  20. generation: { maxTokens: 160 },
  21. providerOptions: {
  22. openai: { store: false },
  23. },
  24. }).model("gpt-4o-mini")
  25. // 2. Build a provider-neutral request. This is useful when reusing one request
  26. // across generate and stream examples.
  27. //
  28. // Options can live on both the configured route/provider facade and the request:
  29. //
  30. // - `generation`: common controls such as max tokens, temperature, topP/topK,
  31. // penalties, seed, and stop sequences.
  32. // - `providerOptions`: namespaced provider-native behavior. For example,
  33. // OpenAI cache keys and store behavior, Anthropic thinking, Gemini thinking
  34. // config, or OpenRouter routing/reasoning.
  35. // - `http`: last-resort serializable overlays for final request body, headers,
  36. // and query params. Prefer typed `providerOptions` when a field is stable.
  37. //
  38. // Route/provider options are defaults. Request options override them for this call.
  39. const request = LLM.request({
  40. model,
  41. system: "You are concise and practical.",
  42. prompt: "Tell me a joke",
  43. generation: { maxTokens: 80, temperature: 0.7 },
  44. providerOptions: {
  45. openai: { promptCacheKey: "tutorial-joke" },
  46. },
  47. })
  48. // `http` is intentionally not needed for normal calls. This shows the shape for
  49. // newly released provider fields before they deserve a typed provider option.
  50. const rawOverlayExample = LLM.request({
  51. model,
  52. prompt: "Show the final HTTP overlay shape.",
  53. http: {
  54. body: { metadata: { example: "tutorial" } },
  55. headers: { "x-opencode-tutorial": "1" },
  56. query: { debug: "1" },
  57. },
  58. })
  59. // 3. `generate` sends the request and collects the event stream into one
  60. // response object. `response.text` is the collected text output.
  61. const generateOnce = Effect.gen(function* () {
  62. const response = yield* LLM.generate(request)
  63. console.log("\n== generate ==")
  64. console.log("generated text:", response.text)
  65. console.log("usage", Formatter.formatJson(response.usage, { space: 2 }))
  66. })
  67. // 4. `stream` exposes provider output as common `LLMEvent`s for UIs that want
  68. // incremental text, reasoning, tool input, usage, or finish events.
  69. const streamText = LLM.stream(request).pipe(
  70. Stream.tap((event) =>
  71. Effect.sync(() => {
  72. if (event.type === "text-delta") process.stdout.write(`\ntext: ${event.text}`)
  73. if (event.type === "finish")
  74. process.stdout.write(
  75. `\nfinish: ${event.reason.normalized}${event.reason.raw ? ` (${event.reason.raw})` : ""}\n`,
  76. )
  77. }),
  78. ),
  79. Stream.runDrain,
  80. )
  81. // 5. Tools are typed with Effect Schema. Provider turns remain explicit:
  82. // advertise definitions on the request, stream one turn, dispatch local calls,
  83. // then persist/build follow-up history in the enclosing product flow.
  84. const tools = {
  85. get_weather: Tool.make({
  86. description: "Get current weather for a city.",
  87. parameters: Schema.Struct({ city: Schema.String }),
  88. success: Schema.Struct({ forecast: Schema.String }),
  89. execute: (input) => Effect.succeed({ forecast: `${input.city}: sunny, 72F` }),
  90. }),
  91. }
  92. const streamWithTools = Effect.gen(function* () {
  93. const request = LLM.request({
  94. model,
  95. prompt: "Use get_weather for San Francisco, then answer in one sentence.",
  96. generation: { maxTokens: 80, temperature: 0 },
  97. tools: Tool.toDefinitions(tools),
  98. })
  99. const events = Array.from(yield* LLM.stream(request).pipe(Stream.runCollect))
  100. for (const event of events) {
  101. if (event.type === "tool-call") console.log("tool call", event.name, event.input)
  102. if (event.type === "text-delta") process.stdout.write(event.text)
  103. if (event.type !== "tool-call" || event.providerExecuted) continue
  104. const dispatched = yield* ToolRuntime.dispatch(tools, event)
  105. console.log("tool result", event.name, dispatched.result)
  106. // A durable agent would persist these messages before starting another
  107. // raw model turn. This tutorial keeps the boundary visible instead.
  108. const followUp = LLMRequest.update(request, {
  109. messages: [
  110. ...request.messages,
  111. Message.assistant([event]),
  112. Message.tool({ ...event, result: dispatched.result }),
  113. ],
  114. })
  115. console.log("follow-up history messages:", followUp.messages.length)
  116. }
  117. })
  118. // 6. `generateObject` is the structured-output helper. It forces a synthetic
  119. // tool call internally, so the same call site works across providers instead of
  120. // depending on provider-specific JSON mode flags.
  121. const WeatherReport = Schema.Struct({
  122. city: Schema.String,
  123. forecast: Schema.String,
  124. highFahrenheit: Schema.Number,
  125. })
  126. const generateStructuredObject = Effect.gen(function* () {
  127. const response = yield* LLM.generateObject({
  128. model,
  129. system: "Return only structured weather data.",
  130. prompt: "Give me today's weather for San Francisco.",
  131. schema: WeatherReport,
  132. generation: { maxTokens: 120, temperature: 0 },
  133. })
  134. console.log("\n== generateObject ==")
  135. console.log(Formatter.formatJson(response.object, { space: 2 }))
  136. })
  137. // If the shape is only known at runtime, pass raw JSON Schema instead. The
  138. // `.object` type is `unknown`; callers that need static types should validate it.
  139. const generateDynamicObject = LLM.generateObject({
  140. model,
  141. prompt: "Extract the city and forecast from: San Francisco is sunny.",
  142. jsonSchema: {
  143. type: "object",
  144. properties: {
  145. city: { type: "string" },
  146. forecast: { type: "string" },
  147. },
  148. required: ["city", "forecast"],
  149. },
  150. })
  151. // -----------------------------------------------------------------------------
  152. // Part 2: provider composition with a fake provider
  153. // -----------------------------------------------------------------------------
  154. // A protocol is the provider-native API shape: common request -> body, response
  155. // frames -> common events. This fake one turns text prompts into a JSON body
  156. // and treats every SSE frame as output text.
  157. const FakeBody = Schema.Struct({
  158. model: Schema.String,
  159. input: Schema.String,
  160. })
  161. type FakeBody = Schema.Schema.Type<typeof FakeBody>
  162. const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
  163. // Protocol ids are open strings, so external packages can define their own
  164. // protocols without changing this package.
  165. id: "fake-echo",
  166. body: {
  167. schema: FakeBody,
  168. from: (request) =>
  169. Effect.succeed({
  170. model: request.model.id,
  171. input: request.messages
  172. .flatMap((message) => message.content)
  173. .filter((part) => part.type === "text")
  174. .map((part) => part.text)
  175. .join("\n"),
  176. }),
  177. },
  178. stream: {
  179. event: Schema.String,
  180. initial: () => undefined,
  181. step: (_, frame) => Effect.succeed([undefined, [{ type: "text-delta", id: "text-0", text: frame }]] as const),
  182. onHalt: () => [{ type: "finish", reason: { normalized: "stop" } }],
  183. },
  184. })
  185. // An route is the runnable binding for that protocol. It adds the deployment
  186. // axes that the protocol deliberately does not know: URL, auth, and framing.
  187. const FakeAdapter = Route.make({
  188. id: "fake-echo",
  189. provider: "fake-echo",
  190. protocol: FakeProtocol,
  191. endpoint: Endpoint.path("/v1/echo", { baseURL: "https://fake.local" }),
  192. auth: Auth.passthrough,
  193. framing: Framing.sse,
  194. })
  195. // A provider module exports a configured facade. Configuration happens before
  196. // model selection; model selectors accept ids only.
  197. const FakeEcho = {
  198. id: ProviderID.make("fake-echo"),
  199. configure: () => ({
  200. id: ProviderID.make("fake-echo"),
  201. model: (id: string) => FakeAdapter.model({ id }),
  202. }),
  203. }
  204. // `LLMClient.prepare` is the lower-level inspection hook: it compiles through
  205. // body conversion, validation, endpoint, auth, and HTTP construction without
  206. // sending anything over the network.
  207. const inspectFakeProvider = Effect.gen(function* () {
  208. const prepared = yield* LLMClient.prepare(
  209. LLM.request({
  210. model: FakeEcho.configure().model("tiny-echo"),
  211. prompt: "Show me the provider pipeline.",
  212. }),
  213. )
  214. console.log("\n== fake provider prepare ==")
  215. console.log("route:", prepared.route)
  216. console.log("body:", Formatter.formatJson(prepared.body, { space: 2 }))
  217. })
  218. // Provide the LLM runtime and the HTTP request executor once. Keep one path
  219. // enabled at a time so the tutorial can demonstrate generate, prepare, stream,
  220. // or tool-loop behavior without spending tokens on every example.
  221. const requestExecutorLayer = RequestExecutor.fetchLayer
  222. const llmDeps = Layer.mergeAll(requestExecutorLayer, WebSocketExecutor.layer)
  223. const llmClientLayer = LLMClient.layer.pipe(Layer.provide(llmDeps))
  224. const program = Effect.gen(function* () {
  225. // yield* generateOnce
  226. // yield* inspectFakeProvider
  227. // yield* LLMClient.prepare(rawOverlayExample).pipe(Effect.andThen((prepared) => Effect.sync(() => console.log(prepared.body))))
  228. // yield* streamText
  229. // yield* generateStructuredObject
  230. // yield* generateDynamicObject.pipe(Effect.andThen((response) => Effect.sync(() => console.log(response.object))))
  231. yield* streamWithTools
  232. }).pipe(Effect.provide(Layer.mergeAll(llmDeps, llmClientLayer)))
  233. Effect.runPromise(program)