tutorial.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 } 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. // 3. `generate` sends the request and collects the event stream into one
  49. // response object. `response.text` is the collected text output.
  50. const generateOnce = Effect.gen(function* () {
  51. const response = yield* LLM.generate(request)
  52. console.log("\n== generate ==")
  53. console.log("generated text:", response.text)
  54. console.log("usage", Formatter.formatJson(response.usage, { space: 2 }))
  55. })
  56. // 4. `stream` exposes provider output as common `LLMEvent`s for UIs that want
  57. // incremental text, reasoning, tool input, usage, or finish events.
  58. const streamText = LLM.stream(request).pipe(
  59. Stream.tap((event) =>
  60. Effect.sync(() => {
  61. if (event.type === "text-delta") process.stdout.write(`\ntext: ${event.text}`)
  62. if (event.type === "finish")
  63. process.stdout.write(
  64. `\nfinish: ${event.reason.normalized}${event.reason.raw ? ` (${event.reason.raw})` : ""}\n`,
  65. )
  66. }),
  67. ),
  68. Stream.runDrain,
  69. )
  70. // 5. Tools are typed with Effect Schema. Provider turns remain explicit:
  71. // advertise definitions on the request, stream one turn, dispatch local calls,
  72. // then persist/build follow-up history in the enclosing product flow.
  73. const tools = {
  74. get_weather: Tool.make({
  75. description: "Get current weather for a city.",
  76. parameters: Schema.Struct({ city: Schema.String }),
  77. success: Schema.Struct({ forecast: Schema.String }),
  78. execute: (input) => Effect.succeed({ forecast: `${input.city}: sunny, 72F` }),
  79. }),
  80. }
  81. const streamWithTools = Effect.gen(function* () {
  82. const request = LLM.request({
  83. model,
  84. prompt: "Use get_weather for San Francisco, then answer in one sentence.",
  85. generation: { maxTokens: 80, temperature: 0 },
  86. tools: Tool.toDefinitions(tools),
  87. })
  88. const events = Array.from(yield* LLM.stream(request).pipe(Stream.runCollect))
  89. for (const event of events) {
  90. if (event.type === "tool-call") console.log("tool call", event.name, event.input)
  91. if (event.type === "text-delta") process.stdout.write(event.text)
  92. if (event.type !== "tool-call" || event.providerExecuted) continue
  93. const dispatched = yield* ToolRuntime.dispatch(tools, event)
  94. console.log("tool result", event.name, dispatched.result)
  95. // A durable agent would persist these messages before starting another
  96. // raw model turn. This tutorial keeps the boundary visible instead.
  97. const followUp = LLMRequest.update(request, {
  98. messages: [
  99. ...request.messages,
  100. Message.assistant([event]),
  101. Message.tool({ ...event, result: dispatched.result }),
  102. ],
  103. })
  104. console.log("follow-up history messages:", followUp.messages.length)
  105. }
  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", id: "text-0", text: frame }]] as const),
  171. onHalt: () => [{ type: "finish", reason: { normalized: "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. provider: "fake-echo",
  179. protocol: FakeProtocol,
  180. endpoint: Endpoint.path("/v1/echo", { baseURL: "https://fake.local" }),
  181. auth: Auth.passthrough,
  182. framing: Framing.sse,
  183. })
  184. // A provider module exports a configured facade. Configuration happens before
  185. // model selection; model selectors accept ids only.
  186. const FakeEcho = {
  187. id: ProviderID.make("fake-echo"),
  188. configure: () => ({
  189. id: ProviderID.make("fake-echo"),
  190. model: (id: string) => FakeAdapter.model({ id }),
  191. }),
  192. }
  193. // Provide the LLM runtime and the HTTP request executor once. Keep one path
  194. // enabled at a time so the tutorial can demonstrate generate, stream, or
  195. // tool-loop behavior without spending tokens on every example.
  196. const requestExecutorLayer = RequestExecutor.fetchLayer
  197. const llmClientLayer = LLMClient.layer.pipe(Layer.provide(requestExecutorLayer))
  198. const program = Effect.gen(function* () {
  199. // yield* generateOnce
  200. // yield* streamText
  201. // yield* generateStructuredObject
  202. // yield* generateDynamicObject.pipe(Effect.andThen((response) => Effect.sync(() => console.log(response.object))))
  203. yield* streamWithTools
  204. }).pipe(Effect.provide(Layer.mergeAll(requestExecutorLayer, llmClientLayer)))
  205. Effect.runPromise(program)