tutorial.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import { Config, Effect, Formatter, Layer, Schema, Stream } from "effect"
  2. import { LLM, LLMClient, Message, ProviderID, Tool, ToolRuntime } from "@opencode-ai/llm"
  3. import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor, WebSocketExecutor } 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.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") process.stdout.write(`\nfinish: ${event.reason}\n`)
  74. }),
  75. ),
  76. Stream.runDrain,
  77. )
  78. // 5. Tools are typed with Effect Schema. Provider turns remain explicit:
  79. // advertise definitions on the request, stream one turn, dispatch local calls,
  80. // then persist/build follow-up history in the enclosing product flow.
  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 = Effect.gen(function* () {
  90. const 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. tools: Tool.toDefinitions(tools),
  95. })
  96. const events = Array.from(yield* LLM.stream(request).pipe(Stream.runCollect))
  97. for (const event of events) {
  98. if (event.type === "tool-call") console.log("tool call", event.name, event.input)
  99. if (event.type === "text-delta") process.stdout.write(event.text)
  100. if (event.type !== "tool-call" || event.providerExecuted) continue
  101. const dispatched = yield* ToolRuntime.dispatch(tools, event)
  102. console.log("tool result", event.name, dispatched.result)
  103. // A durable agent would persist these messages before starting another
  104. // raw model turn. This tutorial keeps the boundary visible instead.
  105. const followUp = LLM.updateRequest(request, {
  106. messages: [
  107. ...request.messages,
  108. Message.assistant([event]),
  109. Message.tool({ ...event, result: dispatched.result }),
  110. ],
  111. })
  112. console.log("follow-up history messages:", followUp.messages.length)
  113. }
  114. })
  115. // 6. `generateObject` is the structured-output helper. It forces a synthetic
  116. // tool call internally, so the same call site works across providers instead of
  117. // depending on provider-specific JSON mode flags.
  118. const WeatherReport = Schema.Struct({
  119. city: Schema.String,
  120. forecast: Schema.String,
  121. highFahrenheit: Schema.Number,
  122. })
  123. const generateStructuredObject = Effect.gen(function* () {
  124. const response = yield* LLM.generateObject({
  125. model,
  126. system: "Return only structured weather data.",
  127. prompt: "Give me today's weather for San Francisco.",
  128. schema: WeatherReport,
  129. generation: { maxTokens: 120, temperature: 0 },
  130. })
  131. console.log("\n== generateObject ==")
  132. console.log(Formatter.formatJson(response.object, { space: 2 }))
  133. })
  134. // If the shape is only known at runtime, pass raw JSON Schema instead. The
  135. // `.object` type is `unknown`; callers that need static types should validate it.
  136. const generateDynamicObject = LLM.generateObject({
  137. model,
  138. prompt: "Extract the city and forecast from: San Francisco is sunny.",
  139. jsonSchema: {
  140. type: "object",
  141. properties: {
  142. city: { type: "string" },
  143. forecast: { type: "string" },
  144. },
  145. required: ["city", "forecast"],
  146. },
  147. })
  148. // -----------------------------------------------------------------------------
  149. // Part 2: provider composition with a fake provider
  150. // -----------------------------------------------------------------------------
  151. // A protocol is the provider-native API shape: common request -> body, response
  152. // frames -> common events. This fake one turns text prompts into a JSON body
  153. // and treats every SSE frame as output text.
  154. const FakeBody = Schema.Struct({
  155. model: Schema.String,
  156. input: Schema.String,
  157. })
  158. type FakeBody = Schema.Schema.Type<typeof FakeBody>
  159. const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
  160. // Protocol ids are open strings, so external packages can define their own
  161. // protocols without changing this package.
  162. id: "fake-echo",
  163. body: {
  164. schema: FakeBody,
  165. from: (request) =>
  166. Effect.succeed({
  167. model: request.model.id,
  168. input: request.messages
  169. .flatMap((message) => message.content)
  170. .filter((part) => part.type === "text")
  171. .map((part) => part.text)
  172. .join("\n"),
  173. }),
  174. },
  175. stream: {
  176. event: Schema.String,
  177. initial: () => undefined,
  178. step: (_, frame) => Effect.succeed([undefined, [{ type: "text-delta", id: "text-0", text: frame }]] as const),
  179. onHalt: () => [{ type: "finish", reason: "stop" }],
  180. },
  181. })
  182. // An route is the runnable binding for that protocol. It adds the deployment
  183. // axes that the protocol deliberately does not know: URL, auth, and framing.
  184. const FakeAdapter = Route.make({
  185. id: "fake-echo",
  186. provider: "fake-echo",
  187. protocol: FakeProtocol,
  188. endpoint: Endpoint.path("/v1/echo", { baseURL: "https://fake.local" }),
  189. auth: Auth.passthrough,
  190. framing: Framing.sse,
  191. })
  192. // A provider module exports a configured facade. Configuration happens before
  193. // model selection; model selectors accept ids only.
  194. const FakeEcho = {
  195. id: ProviderID.make("fake-echo"),
  196. configure: () => ({
  197. id: ProviderID.make("fake-echo"),
  198. model: (id: string) => FakeAdapter.model({ id }),
  199. }),
  200. }
  201. // `LLMClient.prepare` is the lower-level inspection hook: it compiles through
  202. // body conversion, validation, endpoint, auth, and HTTP construction without
  203. // sending anything over the network.
  204. const inspectFakeProvider = Effect.gen(function* () {
  205. const prepared = yield* LLMClient.prepare(
  206. LLM.request({
  207. model: FakeEcho.configure().model("tiny-echo"),
  208. prompt: "Show me the provider pipeline.",
  209. }),
  210. )
  211. console.log("\n== fake provider prepare ==")
  212. console.log("route:", prepared.route)
  213. console.log("body:", Formatter.formatJson(prepared.body, { space: 2 }))
  214. })
  215. // Provide the LLM runtime and the HTTP request executor once. Keep one path
  216. // enabled at a time so the tutorial can demonstrate generate, prepare, stream,
  217. // or tool-loop behavior without spending tokens on every example.
  218. const requestExecutorLayer = RequestExecutor.fetchLayer
  219. const llmDeps = Layer.mergeAll(requestExecutorLayer, WebSocketExecutor.layer)
  220. const llmClientLayer = LLMClient.layer.pipe(Layer.provide(llmDeps))
  221. const program = Effect.gen(function* () {
  222. // yield* generateOnce
  223. // yield* inspectFakeProvider
  224. // yield* LLMClient.prepare(rawOverlayExample).pipe(Effect.andThen((prepared) => Effect.sync(() => console.log(prepared.body))))
  225. // yield* streamText
  226. // yield* generateStructuredObject
  227. // yield* generateDynamicObject.pipe(Effect.andThen((response) => Effect.sync(() => console.log(response.object))))
  228. yield* streamWithTools
  229. }).pipe(Effect.provide(Layer.mergeAll(llmDeps, llmClientLayer)))
  230. Effect.runPromise(program)