tutorial.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { Config, Effect, Formatter, Layer, Schema, Stream } from "effect"
  2. import { LLM, LLMClient, Provider, ProviderID, Tool, type ProviderModelOptions } from "@opencode-ai/llm"
  3. import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor } from "@opencode-ai/llm/route"
  4. import { OpenAI } from "@opencode-ai/llm/providers"
  5. /**
  6. * A runnable walkthrough of the LLM package use-site API.
  7. *
  8. * Run from `packages/llm` 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.model("gpt-4o-mini", {
  19. apiKey,
  20. generation: { maxTokens: 160 },
  21. providerOptions: {
  22. openai: { store: false },
  23. },
  24. })
  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 model 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. // Model 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 === "request-finish") process.stdout.write(`\nfinish: ${event.reason}\n`)
  74. }),
  75. ),
  76. Stream.runDrain,
  77. )
  78. // 5. Tools are typed with Effect Schema. Passing tools to `LLMClient.stream`
  79. // adds their definitions to the request and dispatches matching tool calls.
  80. // Add `stopWhen` to opt into follow-up model rounds after tool results.
  81. const tools = {
  82. get_weather: Tool.make({
  83. description: "Get current weather for a city.",
  84. parameters: Schema.Struct({ city: Schema.String }),
  85. success: Schema.Struct({ forecast: Schema.String }),
  86. execute: (input) => Effect.succeed({ forecast: `${input.city}: sunny, 72F` }),
  87. }),
  88. }
  89. const streamWithTools = LLM.stream({
  90. request: LLM.request({
  91. model,
  92. prompt: "Use get_weather for San Francisco, then answer in one sentence.",
  93. generation: { maxTokens: 80, temperature: 0 },
  94. }),
  95. tools,
  96. stopWhen: LLM.stepCountIs(3),
  97. }).pipe(
  98. Stream.tap((event) =>
  99. Effect.sync(() => {
  100. if (event.type === "tool-call") console.log("tool call", event.name, event.input)
  101. if (event.type === "tool-result") console.log("tool result", event.name, event.result)
  102. if (event.type === "text-delta") process.stdout.write(event.text)
  103. }),
  104. ),
  105. Stream.runDrain,
  106. )
  107. // 6. `generateObject` is the structured-output helper. It forces a synthetic
  108. // tool call internally, so the same call site works across providers instead of
  109. // depending on provider-specific JSON mode flags.
  110. const WeatherReport = Schema.Struct({
  111. city: Schema.String,
  112. forecast: Schema.String,
  113. highFahrenheit: Schema.Number,
  114. })
  115. const generateStructuredObject = Effect.gen(function* () {
  116. const response = yield* LLM.generateObject({
  117. model,
  118. system: "Return only structured weather data.",
  119. prompt: "Give me today's weather for San Francisco.",
  120. schema: WeatherReport,
  121. generation: { maxTokens: 120, temperature: 0 },
  122. })
  123. console.log("\n== generateObject ==")
  124. console.log(Formatter.formatJson(response.object, { space: 2 }))
  125. })
  126. // If the shape is only known at runtime, pass raw JSON Schema instead. The
  127. // `.object` type is `unknown`; callers that need static types should validate it.
  128. const generateDynamicObject = LLM.generateObject({
  129. model,
  130. prompt: "Extract the city and forecast from: San Francisco is sunny.",
  131. jsonSchema: {
  132. type: "object",
  133. properties: {
  134. city: { type: "string" },
  135. forecast: { type: "string" },
  136. },
  137. required: ["city", "forecast"],
  138. },
  139. })
  140. // -----------------------------------------------------------------------------
  141. // Part 2: provider composition with a fake provider
  142. // -----------------------------------------------------------------------------
  143. // A protocol is the provider-native API shape: common request -> body, response
  144. // frames -> common events. This fake one turns text prompts into a JSON body
  145. // and treats every SSE frame as output text.
  146. const FakeBody = Schema.Struct({
  147. model: Schema.String,
  148. input: Schema.String,
  149. })
  150. type FakeBody = Schema.Schema.Type<typeof FakeBody>
  151. const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
  152. // Protocol ids are open strings, so external packages can define their own
  153. // protocols without changing this package.
  154. id: "fake-echo",
  155. body: {
  156. schema: FakeBody,
  157. from: (request) =>
  158. Effect.succeed({
  159. model: request.model.id,
  160. input: request.messages
  161. .flatMap((message) => message.content)
  162. .filter((part) => part.type === "text")
  163. .map((part) => part.text)
  164. .join("\n"),
  165. }),
  166. },
  167. stream: {
  168. event: Schema.String,
  169. initial: () => undefined,
  170. step: (_, frame) => Effect.succeed([undefined, [{ type: "text-delta", text: frame }]] as const),
  171. onHalt: () => [{ type: "request-finish", reason: "stop" }],
  172. },
  173. })
  174. // An route is the runnable binding for that protocol. It adds the deployment
  175. // axes that the protocol deliberately does not know: URL, auth, and framing.
  176. const FakeAdapter = Route.make({
  177. id: "fake-echo",
  178. protocol: FakeProtocol,
  179. endpoint: Endpoint.path("/v1/echo"),
  180. auth: Auth.passthrough,
  181. framing: Framing.sse,
  182. })
  183. // A provider module exports a Provider definition. The default `model` helper
  184. // sets provider identity, protocol id, and the route id resolved by the registry.
  185. const fakeEchoModel = Route.model(FakeAdapter, { provider: "fake-echo", baseURL: "https://fake.local" })
  186. const FakeEcho = Provider.make({
  187. id: ProviderID.make("fake-echo"),
  188. model: (id: string, options: ProviderModelOptions = {}) => fakeEchoModel({ id, ...options }),
  189. })
  190. // `LLMClient.prepare` is the lower-level inspection hook: it compiles through
  191. // body conversion, validation, endpoint, auth, and HTTP construction without
  192. // sending anything over the network.
  193. const inspectFakeProvider = Effect.gen(function* () {
  194. const prepared = yield* LLMClient.prepare(
  195. LLM.request({
  196. model: FakeEcho.model("tiny-echo"),
  197. prompt: "Show me the provider pipeline.",
  198. }),
  199. )
  200. console.log("\n== fake provider prepare ==")
  201. console.log("route:", prepared.route)
  202. console.log("body:", Formatter.formatJson(prepared.body, { space: 2 }))
  203. })
  204. // Provide the LLM runtime and the HTTP request executor once. Keep one path
  205. // enabled at a time so the tutorial can demonstrate generate, prepare, stream,
  206. // or tool-loop behavior without spending tokens on every example.
  207. const requestExecutorLayer = RequestExecutor.defaultLayer
  208. const llmClientLayer = LLMClient.layer.pipe(Layer.provide(requestExecutorLayer))
  209. const program = Effect.gen(function* () {
  210. // yield* generateOnce
  211. // yield* inspectFakeProvider
  212. // yield* LLMClient.prepare(rawOverlayExample).pipe(Effect.andThen((prepared) => Effect.sync(() => console.log(prepared.body))))
  213. // yield* streamText
  214. // yield* generateStructuredObject
  215. // yield* generateDynamicObject.pipe(Effect.andThen((response) => Effect.sync(() => console.log(response.object))))
  216. yield* streamWithTools
  217. }).pipe(Effect.provide(Layer.mergeAll(requestExecutorLayer, llmClientLayer)))
  218. Effect.runPromise(program)