@tinyweb_dev/agent-framework-llm 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/cache-policy.d.ts +3 -0
  2. package/dist/cache-policy.d.ts.map +1 -0
  3. package/dist/index.cjs +2956 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +23 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2831 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llm.cjs +1718 -0
  10. package/dist/llm.cjs.map +1 -0
  11. package/dist/llm.d.ts +284 -0
  12. package/dist/llm.d.ts.map +1 -0
  13. package/dist/llm.js +1692 -0
  14. package/dist/llm.js.map +1 -0
  15. package/dist/protocols/openai-chat.cjs +2443 -0
  16. package/dist/protocols/openai-chat.cjs.map +1 -0
  17. package/dist/protocols/openai-chat.d.ts +357 -0
  18. package/dist/protocols/openai-chat.d.ts.map +1 -0
  19. package/dist/protocols/openai-chat.js +2414 -0
  20. package/dist/protocols/openai-chat.js.map +1 -0
  21. package/dist/protocols/openai-compatible-chat.cjs +2443 -0
  22. package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
  23. package/dist/protocols/openai-compatible-chat.d.ts +77 -0
  24. package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
  25. package/dist/protocols/openai-compatible-chat.js +2419 -0
  26. package/dist/protocols/openai-compatible-chat.js.map +1 -0
  27. package/dist/protocols/shared.cjs +904 -0
  28. package/dist/protocols/shared.cjs.map +1 -0
  29. package/dist/protocols/shared.d.ts +51 -0
  30. package/dist/protocols/shared.d.ts.map +1 -0
  31. package/dist/protocols/shared.js +857 -0
  32. package/dist/protocols/shared.js.map +1 -0
  33. package/dist/protocols/utils/openai-options.d.ts +15 -0
  34. package/dist/protocols/utils/openai-options.d.ts.map +1 -0
  35. package/dist/protocols/utils/tool-stream.d.ts +78 -0
  36. package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
  37. package/dist/provider.cjs +20 -0
  38. package/dist/provider.cjs.map +1 -0
  39. package/dist/provider.d.ts +19 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +17 -0
  42. package/dist/provider.js.map +1 -0
  43. package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
  44. package/dist/providers/openai-compatible-profile.cjs.map +1 -0
  45. package/dist/providers/openai-compatible-profile.d.ts +52 -0
  46. package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
  47. package/dist/providers/openai-compatible-profile.js +21 -0
  48. package/dist/providers/openai-compatible-profile.js.map +1 -0
  49. package/dist/providers/openai-compatible.cjs +2533 -0
  50. package/dist/providers/openai-compatible.cjs.map +1 -0
  51. package/dist/providers/openai-compatible.d.ts +128 -0
  52. package/dist/providers/openai-compatible.d.ts.map +1 -0
  53. package/dist/providers/openai-compatible.js +2495 -0
  54. package/dist/providers/openai-compatible.js.map +1 -0
  55. package/dist/providers/openai-options.cjs +797 -0
  56. package/dist/providers/openai-options.cjs.map +1 -0
  57. package/dist/providers/openai-options.d.ts +29 -0
  58. package/dist/providers/openai-options.d.ts.map +1 -0
  59. package/dist/providers/openai-options.js +792 -0
  60. package/dist/providers/openai-options.js.map +1 -0
  61. package/dist/providers/openai.cjs +2517 -0
  62. package/dist/providers/openai.cjs.map +1 -0
  63. package/dist/providers/openai.d.ts +87 -0
  64. package/dist/providers/openai.d.ts.map +1 -0
  65. package/dist/providers/openai.js +2489 -0
  66. package/dist/providers/openai.js.map +1 -0
  67. package/dist/route/auth-options.cjs +855 -0
  68. package/dist/route/auth-options.cjs.map +1 -0
  69. package/dist/route/auth-options.d.ts +25 -0
  70. package/dist/route/auth-options.d.ts.map +1 -0
  71. package/dist/route/auth-options.js +852 -0
  72. package/dist/route/auth-options.js.map +1 -0
  73. package/dist/route/auth.cjs +855 -0
  74. package/dist/route/auth.cjs.map +1 -0
  75. package/dist/route/auth.d.ts +51 -0
  76. package/dist/route/auth.d.ts.map +1 -0
  77. package/dist/route/auth.js +836 -0
  78. package/dist/route/auth.js.map +1 -0
  79. package/dist/route/client.cjs +1844 -0
  80. package/dist/route/client.cjs.map +1 -0
  81. package/dist/route/client.d.ts +268 -0
  82. package/dist/route/client.d.ts.map +1 -0
  83. package/dist/route/client.js +1830 -0
  84. package/dist/route/client.js.map +1 -0
  85. package/dist/route/endpoint.cjs +756 -0
  86. package/dist/route/endpoint.cjs.map +1 -0
  87. package/dist/route/endpoint.d.ts +13 -0
  88. package/dist/route/endpoint.d.ts.map +1 -0
  89. package/dist/route/endpoint.js +752 -0
  90. package/dist/route/endpoint.js.map +1 -0
  91. package/dist/route/executor.cjs +1077 -0
  92. package/dist/route/executor.cjs.map +1 -0
  93. package/dist/route/executor.d.ts +13 -0
  94. package/dist/route/executor.d.ts.map +1 -0
  95. package/dist/route/executor.js +1072 -0
  96. package/dist/route/executor.js.map +1 -0
  97. package/dist/route/framing.cjs +773 -0
  98. package/dist/route/framing.cjs.map +1 -0
  99. package/dist/route/framing.d.ts +9 -0
  100. package/dist/route/framing.d.ts.map +1 -0
  101. package/dist/route/framing.js +750 -0
  102. package/dist/route/framing.js.map +1 -0
  103. package/dist/route/overflow-detect.d.ts +18 -0
  104. package/dist/route/overflow-detect.d.ts.map +1 -0
  105. package/dist/route/protocol.cjs +25 -0
  106. package/dist/route/protocol.cjs.map +1 -0
  107. package/dist/route/protocol.d.ts +40 -0
  108. package/dist/route/protocol.d.ts.map +1 -0
  109. package/dist/route/protocol.js +21 -0
  110. package/dist/route/protocol.js.map +1 -0
  111. package/dist/route/transport/http.d.ts +48 -0
  112. package/dist/route/transport/http.d.ts.map +1 -0
  113. package/dist/route/transport/index.cjs +969 -0
  114. package/dist/route/transport/index.cjs.map +1 -0
  115. package/dist/route/transport/index.d.ts +13 -0
  116. package/dist/route/transport/index.d.ts.map +1 -0
  117. package/dist/route/transport/index.js +967 -0
  118. package/dist/route/transport/index.js.map +1 -0
  119. package/dist/schema/errors.d.ts +181 -0
  120. package/dist/schema/errors.d.ts.map +1 -0
  121. package/dist/schema/events.d.ts +3224 -0
  122. package/dist/schema/events.d.ts.map +1 -0
  123. package/dist/schema/ids.d.ts +31 -0
  124. package/dist/schema/ids.d.ts.map +1 -0
  125. package/dist/schema/index.cjs +847 -0
  126. package/dist/schema/index.cjs.map +1 -0
  127. package/dist/schema/index.d.ts +6 -0
  128. package/dist/schema/index.d.ts.map +1 -0
  129. package/dist/schema/index.js +777 -0
  130. package/dist/schema/index.js.map +1 -0
  131. package/dist/schema/messages.d.ts +292 -0
  132. package/dist/schema/messages.d.ts.map +1 -0
  133. package/dist/schema/options.d.ts +123 -0
  134. package/dist/schema/options.d.ts.map +1 -0
  135. package/dist/tool-runtime.cjs +907 -0
  136. package/dist/tool-runtime.cjs.map +1 -0
  137. package/dist/tool-runtime.d.ts +50 -0
  138. package/dist/tool-runtime.d.ts.map +1 -0
  139. package/dist/tool-runtime.js +901 -0
  140. package/dist/tool-runtime.js.map +1 -0
  141. package/dist/tool.cjs +802 -0
  142. package/dist/tool.cjs.map +1 -0
  143. package/dist/tool.d.ts +111 -0
  144. package/dist/tool.d.ts.map +1 -0
  145. package/dist/tool.js +796 -0
  146. package/dist/tool.js.map +1 -0
  147. package/package.json +112 -29
  148. package/src/cache-policy.ts +0 -92
  149. package/src/index.ts +0 -62
  150. package/src/llm.ts +0 -210
  151. package/src/protocols/openai-chat.ts +0 -464
  152. package/src/protocols/openai-compatible-chat.ts +0 -29
  153. package/src/protocols/shared.ts +0 -204
  154. package/src/protocols/utils/openai-options.ts +0 -56
  155. package/src/protocols/utils/tool-stream.ts +0 -135
  156. package/src/provider.ts +0 -32
  157. package/src/providers/openai-compatible.ts +0 -69
  158. package/src/providers/openai-options.ts +0 -71
  159. package/src/providers/openai.ts +0 -39
  160. package/src/route/auth-options.ts +0 -48
  161. package/src/route/auth.ts +0 -198
  162. package/src/route/client.ts +0 -459
  163. package/src/route/endpoint.ts +0 -28
  164. package/src/route/executor.ts +0 -396
  165. package/src/route/framing.ts +0 -13
  166. package/src/route/overflow-detect.ts +0 -74
  167. package/src/route/protocol.ts +0 -48
  168. package/src/route/transport/http.ts +0 -123
  169. package/src/route/transport/index.ts +0 -21
  170. package/src/schema/errors.ts +0 -225
  171. package/src/schema/events.ts +0 -335
  172. package/src/schema/ids.ts +0 -44
  173. package/src/schema/index.ts +0 -6
  174. package/src/schema/messages.ts +0 -250
  175. package/src/schema/options.ts +0 -231
  176. package/src/tool-runtime.ts +0 -301
  177. package/src/tool.ts +0 -212
package/src/llm.ts DELETED
@@ -1,210 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/llm.ts
2
- import { Effect, JsonSchema, Schema } from "effect"
3
- import { LLMClient, modelLimits, modelRef, type ModelRefInput } from "./route/client"
4
- import {
5
- GenerationOptions,
6
- HttpOptions,
7
- InvalidProviderOutputReason,
8
- LLMError,
9
- LLMEvent,
10
- LLMRequest,
11
- LLMResponse,
12
- Message,
13
- SystemPart,
14
- ToolChoice,
15
- ToolDefinition,
16
- type ContentPart,
17
- ToolCallPart,
18
- ToolResultPart,
19
- } from "./schema"
20
- import { make as makeTool, type ToolSchema } from "./tool"
21
-
22
- export type ModelInput = ModelRefInput
23
-
24
- export type MessageInput = Message.Input
25
-
26
- export type ToolChoiceInput = ToolChoice.Input
27
- export type ToolChoiceMode = ToolChoice.Mode
28
-
29
- export type ToolResultInput = Parameters<typeof ToolResultPart.make>[0]
30
-
31
- export type RequestInput = Omit<
32
- ConstructorParameters<typeof LLMRequest>[0],
33
- "system" | "messages" | "tools" | "toolChoice" | "generation" | "http" | "providerOptions"
34
- > & {
35
- readonly system?: string | SystemPart | ReadonlyArray<SystemPart>
36
- readonly prompt?: string | ContentPart | ReadonlyArray<ContentPart>
37
- readonly messages?: ReadonlyArray<Message | MessageInput>
38
- readonly tools?: ReadonlyArray<ToolDefinition.Input>
39
- readonly toolChoice?: ToolChoiceInput
40
- readonly generation?: GenerationOptions.Input
41
- readonly providerOptions?: ConstructorParameters<typeof LLMRequest>[0]["providerOptions"]
42
- readonly http?: HttpOptions.Input
43
- }
44
-
45
- export const limits = modelLimits
46
-
47
- export const text = Message.text
48
-
49
- export const system = SystemPart.make
50
-
51
- export const message = Message.make
52
-
53
- export const user = Message.user
54
-
55
- export const assistant = Message.assistant
56
-
57
- export const model = modelRef
58
-
59
- export const toolDefinition = ToolDefinition.make
60
-
61
- export const toolCall = ToolCallPart.make
62
-
63
- export const toolResult = ToolResultPart.make
64
-
65
- export const toolMessage = Message.tool
66
-
67
- export const toolChoiceName = ToolChoice.named
68
-
69
- export const toolChoice = ToolChoice.make
70
-
71
- export const generation = GenerationOptions.make
72
-
73
- export const generate = LLMClient.generate
74
-
75
- export const stream = LLMClient.stream
76
-
77
- export const stepCountIs = LLMClient.stepCountIs
78
-
79
- export { hasToolCall, stopWhenAny } from "./tool-runtime"
80
-
81
- export const requestInput = (input: LLMRequest): RequestInput => ({
82
- ...LLMRequest.input(input),
83
- })
84
-
85
- export const request = (input: RequestInput) => {
86
- const {
87
- system: requestSystem,
88
- prompt,
89
- messages,
90
- tools,
91
- toolChoice: requestToolChoice,
92
- generation: requestGeneration,
93
- providerOptions: requestProviderOptions,
94
- http: requestHttp,
95
- ...rest
96
- } = input
97
- return new LLMRequest({
98
- ...rest,
99
- system: SystemPart.content(requestSystem),
100
- messages: [...(messages?.map(message) ?? []), ...(prompt === undefined ? [] : [user(prompt)])],
101
- tools: tools?.map(toolDefinition) ?? [],
102
- toolChoice: requestToolChoice ? toolChoice(requestToolChoice) : undefined,
103
- generation: requestGeneration === undefined ? undefined : generation(requestGeneration),
104
- providerOptions: requestProviderOptions,
105
- http: requestHttp === undefined ? undefined : HttpOptions.make(requestHttp),
106
- })
107
- }
108
-
109
- export const updateRequest = (input: LLMRequest, patch: Partial<RequestInput>) =>
110
- request({ ...requestInput(input), ...patch })
111
-
112
- const GENERATE_OBJECT_TOOL_NAME = "generate_object"
113
-
114
- const GENERATE_OBJECT_TOOL_DESCRIPTION = "Return the structured result by calling this tool."
115
-
116
- type GenerateObjectBase = Omit<RequestInput, "tools" | "toolChoice" | "responseFormat">
117
-
118
- export class GenerateObjectResponse<T> {
119
- constructor(
120
- readonly object: T,
121
- readonly response: LLMResponse,
122
- ) {}
123
-
124
- get events() {
125
- return this.response.events
126
- }
127
-
128
- get usage() {
129
- return this.response.usage
130
- }
131
- }
132
-
133
- export interface GenerateObjectOptions<S extends ToolSchema<any>> extends GenerateObjectBase {
134
- readonly schema: S
135
- }
136
-
137
- export interface GenerateObjectDynamicOptions extends GenerateObjectBase {
138
- readonly jsonSchema: JsonSchema.JsonSchema
139
- }
140
-
141
- const runGenerateObject = Effect.fn("LLM.generateObject")(function* (
142
- options: GenerateObjectBase,
143
- tool: ReturnType<typeof makeTool>,
144
- ) {
145
- const baseRequest = request(options)
146
- const generateRequest = LLMRequest.update(baseRequest, {
147
- toolChoice: ToolChoice.named(GENERATE_OBJECT_TOOL_NAME),
148
- })
149
- const response = yield* LLMClient.generate({
150
- request: generateRequest,
151
- tools: { [GENERATE_OBJECT_TOOL_NAME]: tool },
152
- toolExecution: "none",
153
- })
154
- const call = response.toolCalls.find(
155
- (event) => LLMEvent.is.toolCall(event) && event.name === GENERATE_OBJECT_TOOL_NAME,
156
- )
157
- if (!call || !LLMEvent.is.toolCall(call))
158
- return yield* new LLMError({
159
- module: "LLM",
160
- method: "generateObject",
161
- reason: new InvalidProviderOutputReason({
162
- message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`,
163
- }),
164
- })
165
- const object = yield* tool._decode(call.input).pipe(
166
- Effect.mapError(
167
- (error) =>
168
- new LLMError({
169
- module: "LLM",
170
- method: "generateObject",
171
- reason: new InvalidProviderOutputReason({
172
- message: `generateObject: tool input failed schema decode: ${error.message}`,
173
- }),
174
- }),
175
- ),
176
- )
177
- return new GenerateObjectResponse(object, response)
178
- })
179
-
180
- export function generateObject<S extends ToolSchema<any>>(
181
- options: GenerateObjectOptions<S>,
182
- ): Effect.Effect<GenerateObjectResponse<Schema.Schema.Type<S>>, LLMError>
183
- export function generateObject(
184
- options: GenerateObjectDynamicOptions,
185
- ): Effect.Effect<GenerateObjectResponse<unknown>, LLMError>
186
- export function generateObject(options: GenerateObjectOptions<ToolSchema<any>> | GenerateObjectDynamicOptions) {
187
- if ("schema" in options) {
188
- const { schema, ...rest } = options
189
- return runGenerateObject(
190
- rest,
191
- makeTool({
192
- description: GENERATE_OBJECT_TOOL_DESCRIPTION,
193
- parameters: schema,
194
- success: Schema.Unknown as ToolSchema<unknown>,
195
- execute: () => Effect.void,
196
- }),
197
- )
198
- }
199
- const { jsonSchema, ...rest } = options
200
- return runGenerateObject(
201
- rest,
202
- makeTool({
203
- description: GENERATE_OBJECT_TOOL_DESCRIPTION,
204
- jsonSchema,
205
- execute: () => Effect.void,
206
- }),
207
- )
208
- }
209
-
210
- export * as LLM from "./llm"
@@ -1,464 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/protocols/openai-chat.ts
2
- import { Array as Arr, Effect, Schema } from "effect"
3
- import { Route } from "../route/client"
4
- import { Auth } from "../route/auth"
5
- import { Endpoint } from "../route/endpoint"
6
- import { Framing } from "../route/framing"
7
- import { HttpTransport } from "../route/transport"
8
- import { Protocol } from "../route/protocol"
9
- import {
10
- LLMEvent,
11
- Usage,
12
- type FinishReason,
13
- type LLMRequest,
14
- type MediaPart,
15
- type TextPart,
16
- type ToolCallPart,
17
- type ToolDefinition,
18
- } from "../schema"
19
- import { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared"
20
- import { OpenAIOptions } from "./utils/openai-options"
21
- import { ToolStream } from "./utils/tool-stream"
22
-
23
- const ADAPTER = "openai-chat"
24
- export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
25
- export const PATH = "/chat/completions"
26
-
27
- // =============================================================================
28
- // Request Body Schema
29
- // =============================================================================
30
- const OpenAIChatFunction = Schema.Struct({
31
- name: Schema.String,
32
- description: Schema.String,
33
- parameters: JsonObject,
34
- })
35
-
36
- const OpenAIChatTool = Schema.Struct({
37
- type: Schema.tag("function"),
38
- function: OpenAIChatFunction,
39
- })
40
- type OpenAIChatTool = Schema.Schema.Type<typeof OpenAIChatTool>
41
-
42
- const OpenAIChatAssistantToolCall = Schema.Struct({
43
- id: Schema.String,
44
- type: Schema.tag("function"),
45
- function: Schema.Struct({
46
- name: Schema.String,
47
- arguments: Schema.String,
48
- }),
49
- })
50
- type OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>
51
-
52
- const OpenAIChatUserContentText = Schema.Struct({
53
- type: Schema.Literal("text"),
54
- text: Schema.String,
55
- })
56
- const OpenAIChatUserContentImageUrl = Schema.Struct({
57
- type: Schema.Literal("image_url"),
58
- image_url: Schema.Struct({ url: Schema.String }),
59
- })
60
- const OpenAIChatUserContentPart = Schema.Union([OpenAIChatUserContentText, OpenAIChatUserContentImageUrl]).pipe(
61
- Schema.toTaggedUnion("type"),
62
- )
63
- type OpenAIChatUserContentPart = Schema.Schema.Type<typeof OpenAIChatUserContentPart>
64
- const OpenAIChatUserContent = Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContentPart)])
65
-
66
- const OpenAIChatMessage = Schema.Union([
67
- Schema.Struct({ role: Schema.Literal("system"), content: Schema.String }),
68
- Schema.Struct({ role: Schema.Literal("user"), content: OpenAIChatUserContent }),
69
- Schema.Struct({
70
- role: Schema.Literal("assistant"),
71
- content: Schema.NullOr(Schema.String),
72
- tool_calls: optionalArray(OpenAIChatAssistantToolCall),
73
- reasoning_content: Schema.optional(Schema.String),
74
- }),
75
- Schema.Struct({ role: Schema.Literal("tool"), tool_call_id: Schema.String, content: Schema.String }),
76
- ]).pipe(Schema.toTaggedUnion("role"))
77
- type OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>
78
-
79
- const OpenAIChatToolChoice = Schema.Union([
80
- Schema.Literals(["auto", "none", "required"]),
81
- Schema.Struct({
82
- type: Schema.tag("function"),
83
- function: Schema.Struct({ name: Schema.String }),
84
- }),
85
- ])
86
-
87
- export const bodyFields = {
88
- model: Schema.String,
89
- messages: Schema.Array(OpenAIChatMessage),
90
- tools: optionalArray(OpenAIChatTool),
91
- tool_choice: Schema.optional(OpenAIChatToolChoice),
92
- stream: Schema.Literal(true),
93
- stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
94
- store: Schema.optional(Schema.Boolean),
95
- reasoning_effort: Schema.optional(OpenAIOptions.OpenAIReasoningEffort),
96
- max_tokens: Schema.optional(Schema.Number),
97
- temperature: Schema.optional(Schema.Number),
98
- top_p: Schema.optional(Schema.Number),
99
- frequency_penalty: Schema.optional(Schema.Number),
100
- presence_penalty: Schema.optional(Schema.Number),
101
- seed: Schema.optional(Schema.Number),
102
- stop: optionalArray(Schema.String),
103
- }
104
- const OpenAIChatBody = Schema.Struct(bodyFields)
105
- export type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>
106
-
107
- // =============================================================================
108
- // Streaming Event Schema
109
- // =============================================================================
110
- const OpenAIChatUsage = Schema.Struct({
111
- prompt_tokens: Schema.optional(Schema.Number),
112
- completion_tokens: Schema.optional(Schema.Number),
113
- total_tokens: Schema.optional(Schema.Number),
114
- prompt_tokens_details: optionalNull(
115
- Schema.Struct({
116
- cached_tokens: Schema.optional(Schema.Number),
117
- }),
118
- ),
119
- completion_tokens_details: optionalNull(
120
- Schema.Struct({
121
- reasoning_tokens: Schema.optional(Schema.Number),
122
- }),
123
- ),
124
- })
125
-
126
- const OpenAIChatToolCallDeltaFunction = Schema.Struct({
127
- name: optionalNull(Schema.String),
128
- arguments: optionalNull(Schema.String),
129
- })
130
-
131
- const OpenAIChatToolCallDelta = Schema.Struct({
132
- index: Schema.Number,
133
- id: optionalNull(Schema.String),
134
- function: optionalNull(OpenAIChatToolCallDeltaFunction),
135
- })
136
- type OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>
137
-
138
- const OpenAIChatDelta = Schema.Struct({
139
- content: optionalNull(Schema.String),
140
- tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
141
- })
142
-
143
- const OpenAIChatChoice = Schema.Struct({
144
- delta: optionalNull(OpenAIChatDelta),
145
- finish_reason: optionalNull(Schema.String),
146
- })
147
-
148
- const OpenAIChatEvent = Schema.Struct({
149
- choices: Schema.Array(OpenAIChatChoice),
150
- usage: optionalNull(OpenAIChatUsage),
151
- })
152
- type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
153
- type OpenAIChatRequestMessage = LLMRequest["messages"][number]
154
-
155
- interface ParserState {
156
- readonly tools: ToolStream.State<number>
157
- readonly toolCallEvents: ReadonlyArray<LLMEvent>
158
- readonly usage?: Usage
159
- readonly finishReason?: FinishReason
160
- /** Running assistant text used to normalise cumulative `delta.content` providers. */
161
- readonly textAcc: string
162
- }
163
-
164
- const invalid = ProviderShared.invalidRequest
165
-
166
- // =============================================================================
167
- // Request Lowering
168
- // =============================================================================
169
- const lowerTool = (tool: ToolDefinition): OpenAIChatTool => ({
170
- type: "function",
171
- function: {
172
- name: tool.name,
173
- description: tool.description,
174
- parameters: tool.inputSchema,
175
- },
176
- })
177
-
178
- const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>) =>
179
- ProviderShared.matchToolChoice("OpenAI Chat", toolChoice, {
180
- auto: () => "auto" as const,
181
- none: () => "none" as const,
182
- required: () => "required" as const,
183
- tool: (name) => ({ type: "function" as const, function: { name } }),
184
- })
185
-
186
- const lowerToolCall = (part: ToolCallPart): OpenAIChatAssistantToolCall => ({
187
- id: part.id,
188
- type: "function",
189
- function: {
190
- name: part.name,
191
- arguments: ProviderShared.encodeJson(part.input),
192
- },
193
- })
194
-
195
- const openAICompatibleReasoningContent = (native: unknown) =>
196
- isRecord(native) && typeof native.reasoning_content === "string" ? native.reasoning_content : undefined
197
-
198
- const mediaToImageUrl = (part: MediaPart): string => {
199
- const data = part.data
200
- if (typeof data === "string") {
201
- if (data.startsWith("http://") || data.startsWith("https://") || data.startsWith("data:") || data.startsWith("file://"))
202
- return data
203
- return `data:${part.mediaType};base64,${data}`
204
- }
205
- return `data:${part.mediaType};base64,${ProviderShared.mediaBytes(part)}`
206
- }
207
-
208
- const lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (message: OpenAIChatRequestMessage) {
209
- const parts: OpenAIChatUserContentPart[] = []
210
- let hasMedia = false
211
- const textParts: TextPart[] = []
212
- for (const part of message.content) {
213
- if (!ProviderShared.supportsContent(part, ["text", "media"]))
214
- return yield* ProviderShared.unsupportedContent("OpenAI Chat", "user", ["text", "media"])
215
- if (part.type === "text") {
216
- textParts.push(part)
217
- parts.push({ type: "text", text: part.text })
218
- continue
219
- }
220
- if (!part.mediaType.startsWith("image/"))
221
- return yield* ProviderShared.invalidRequest(
222
- `OpenAI Chat user messages only support image/* media (received ${part.mediaType})`,
223
- )
224
- hasMedia = true
225
- parts.push({ type: "image_url", image_url: { url: mediaToImageUrl(part) } })
226
- }
227
- if (!hasMedia) return { role: "user" as const, content: ProviderShared.joinText(textParts) }
228
- return { role: "user" as const, content: parts }
229
- })
230
-
231
- const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(function* (
232
- message: OpenAIChatRequestMessage,
233
- ) {
234
- const content: TextPart[] = []
235
- const toolCalls: OpenAIChatAssistantToolCall[] = []
236
- for (const part of message.content) {
237
- if (!ProviderShared.supportsContent(part, ["text", "tool-call"]))
238
- return yield* ProviderShared.unsupportedContent("OpenAI Chat", "assistant", ["text", "tool-call"])
239
- if (part.type === "text") {
240
- content.push(part)
241
- continue
242
- }
243
- if (part.type === "tool-call") {
244
- toolCalls.push(lowerToolCall(part))
245
- continue
246
- }
247
- }
248
- return {
249
- role: "assistant" as const,
250
- content: content.length === 0 ? null : ProviderShared.joinText(content),
251
- tool_calls: toolCalls.length === 0 ? undefined : toolCalls,
252
- reasoning_content: openAICompatibleReasoningContent(message.native?.openaiCompatible),
253
- }
254
- })
255
-
256
- const lowerToolMessages = Effect.fn("OpenAIChat.lowerToolMessages")(function* (message: OpenAIChatRequestMessage) {
257
- const messages: OpenAIChatMessage[] = []
258
- for (const part of message.content) {
259
- if (!ProviderShared.supportsContent(part, ["tool-result"]))
260
- return yield* ProviderShared.unsupportedContent("OpenAI Chat", "tool", ["tool-result"])
261
- messages.push({ role: "tool", tool_call_id: part.id, content: ProviderShared.toolResultText(part) })
262
- }
263
- return messages
264
- })
265
-
266
- const lowerMessage = Effect.fn("OpenAIChat.lowerMessage")(function* (message: OpenAIChatRequestMessage) {
267
- if (message.role === "user") return [yield* lowerUserMessage(message)]
268
- if (message.role === "assistant") return [yield* lowerAssistantMessage(message)]
269
- return yield* lowerToolMessages(message)
270
- })
271
-
272
- const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request: LLMRequest) {
273
- const system: OpenAIChatMessage[] =
274
- request.system.length === 0 ? [] : [{ role: "system", content: ProviderShared.joinText(request.system) }]
275
- return [...system, ...Arr.flatten(yield* Effect.forEach(request.messages, lowerMessage))]
276
- })
277
-
278
- const lowerOptions = Effect.fn("OpenAIChat.lowerOptions")(function* (request: LLMRequest) {
279
- const store = OpenAIOptions.store(request)
280
- const reasoningEffort = OpenAIOptions.reasoningEffort(request)
281
- if (reasoningEffort && !OpenAIOptions.isReasoningEffort(reasoningEffort))
282
- return yield* invalid(`OpenAI Chat does not support reasoning effort ${reasoningEffort}`)
283
- return {
284
- ...(store !== undefined ? { store } : {}),
285
- ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
286
- }
287
- })
288
-
289
- const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request: LLMRequest) {
290
- const generation = request.generation
291
- return {
292
- model: request.model.id,
293
- messages: yield* lowerMessages(request),
294
- tools: request.tools.length === 0 ? undefined : request.tools.map(lowerTool),
295
- tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
296
- stream: true as const,
297
- stream_options: { include_usage: true },
298
- max_tokens: generation?.maxTokens,
299
- temperature: generation?.temperature,
300
- top_p: generation?.topP,
301
- frequency_penalty: generation?.frequencyPenalty,
302
- presence_penalty: generation?.presencePenalty,
303
- seed: generation?.seed,
304
- stop: generation?.stop,
305
- ...(yield* lowerOptions(request)),
306
- }
307
- })
308
-
309
- // =============================================================================
310
- // Stream Parsing
311
- // =============================================================================
312
- const mapFinishReason = (reason: string | null | undefined): FinishReason => {
313
- if (reason === "stop") return "stop"
314
- if (reason === "length") return "length"
315
- if (reason === "content_filter") return "content-filter"
316
- if (reason === "function_call" || reason === "tool_calls") return "tool-calls"
317
- return "unknown"
318
- }
319
-
320
- const mapUsage = (usage: OpenAIChatEvent["usage"]): Usage | undefined => {
321
- if (!usage) return undefined
322
- const cached = usage.prompt_tokens_details?.cached_tokens
323
- const reasoning = usage.completion_tokens_details?.reasoning_tokens
324
- const nonCached = ProviderShared.subtractTokens(usage.prompt_tokens, cached)
325
- return new Usage({
326
- inputTokens: usage.prompt_tokens,
327
- outputTokens: usage.completion_tokens,
328
- nonCachedInputTokens: nonCached,
329
- cacheReadInputTokens: cached,
330
- reasoningTokens: reasoning,
331
- totalTokens: ProviderShared.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),
332
- providerMetadata: { openai: usage },
333
- })
334
- }
335
-
336
- /**
337
- * OpenAI Chat streams are *incremental* (`delta.content` is the next fragment).
338
- * Some OpenAI-compatible proxies instead re-send the full text so far on every
339
- * chunk (cumulative snapshots). Blindly forwarding those as text-delta makes
340
- * UIs that concatenate deltas render duplicated prose.
341
- *
342
- * Returns the incremental fragment to emit (empty = skip) and the new
343
- * accumulated text for parser state.
344
- */
345
- const normaliseTextDelta = (
346
- prev: string,
347
- incoming: string,
348
- ): { readonly emit: string; readonly textAcc: string } => {
349
- if (!incoming) return { emit: "", textAcc: prev }
350
- // Exact replay of what we already have — drop.
351
- if (incoming === prev) return { emit: "", textAcc: prev }
352
- // Cumulative snapshot: full text so far (or a longer prefix continuation).
353
- if (prev.length > 0 && incoming.startsWith(prev)) {
354
- return { emit: incoming.slice(prev.length), textAcc: incoming }
355
- }
356
- // Stale / shorter snapshot after we already advanced — drop.
357
- if (prev.length > 0 && prev.startsWith(incoming)) {
358
- return { emit: "", textAcc: prev }
359
- }
360
- // True incremental fragment.
361
- return { emit: incoming, textAcc: prev + incoming }
362
- }
363
-
364
- const step = (state: ParserState, event: OpenAIChatEvent) =>
365
- Effect.gen(function* () {
366
- const events: LLMEvent[] = []
367
- const usage = mapUsage(event.usage) ?? state.usage
368
- const choice = event.choices[0]
369
- const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason
370
- const delta = choice?.delta
371
- const toolDeltas = delta?.tool_calls ?? []
372
- let tools = state.tools
373
- let textAcc = state.textAcc
374
-
375
- if (delta?.content) {
376
- const normalised = normaliseTextDelta(textAcc, delta.content)
377
- textAcc = normalised.textAcc
378
- if (normalised.emit) {
379
- events.push(LLMEvent.textDelta({ id: "text-0", text: normalised.emit }))
380
- }
381
- }
382
-
383
- for (const tool of toolDeltas) {
384
- const result = ToolStream.appendOrStart(
385
- ADAPTER,
386
- tools,
387
- tool.index,
388
- { id: tool.id ?? undefined, name: tool.function?.name ?? undefined, text: tool.function?.arguments ?? "" },
389
- "OpenAI Chat tool call delta is missing id or name",
390
- )
391
- if (ToolStream.isError(result)) return yield* result
392
- tools = result.tools
393
- if (result.event) events.push(result.event)
394
- }
395
-
396
- const finished =
397
- finishReason !== undefined && state.finishReason === undefined && Object.keys(tools).length > 0
398
- ? yield* ToolStream.finishAll(ADAPTER, tools)
399
- : undefined
400
-
401
- return [
402
- {
403
- tools: finished?.tools ?? tools,
404
- toolCallEvents: finished?.events ?? state.toolCallEvents,
405
- usage,
406
- finishReason,
407
- textAcc,
408
- },
409
- events,
410
- ] as const
411
- })
412
-
413
- const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
414
- const hasToolCalls = state.toolCallEvents.length > 0
415
- const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason
416
- return [...state.toolCallEvents, ...(reason ? [LLMEvent.requestFinish({ reason, usage: state.usage })] : [])]
417
- }
418
-
419
- // =============================================================================
420
- // Protocol And OpenAI Route
421
- // =============================================================================
422
- export const protocol = Protocol.make({
423
- id: ADAPTER,
424
- body: {
425
- schema: OpenAIChatBody,
426
- from: fromRequest,
427
- },
428
- stream: {
429
- event: Protocol.jsonEvent(OpenAIChatEvent),
430
- initial: (): ParserState => ({
431
- tools: ToolStream.empty<number>(),
432
- toolCallEvents: [],
433
- textAcc: "",
434
- }),
435
- step,
436
- onHalt: finishEvents,
437
- },
438
- })
439
-
440
- const encodeBody = Schema.encodeSync(Schema.fromJsonString(OpenAIChatBody))
441
-
442
- export const httpTransport = HttpTransport.httpJson({
443
- endpoint: Endpoint.path(PATH),
444
- auth: Auth.bearer(),
445
- framing: Framing.sse,
446
- encodeBody,
447
- })
448
-
449
- export const route = Route.make({
450
- id: ADAPTER,
451
- provider: "openai",
452
- protocol,
453
- transport: httpTransport,
454
- defaults: {
455
- baseURL: DEFAULT_BASE_URL,
456
- },
457
- })
458
-
459
- // =============================================================================
460
- // Model Helper
461
- // =============================================================================
462
- export const model = route.model
463
-
464
- export * as OpenAIChat from "./openai-chat"
@@ -1,29 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/protocols/openai-compatible-chat.ts
2
- import { Route, type RouteRoutedModelInput } from "../route/client"
3
- import { Endpoint } from "../route/endpoint"
4
- import { Framing } from "../route/framing"
5
- import * as OpenAIChat from "./openai-chat"
6
-
7
- const ADAPTER = "openai-compatible-chat"
8
-
9
- export type OpenAICompatibleChatModelInput = Omit<RouteRoutedModelInput, "baseURL"> & {
10
- readonly baseURL: string
11
- }
12
-
13
- /**
14
- * Route for non-OpenAI providers that expose an OpenAI Chat-compatible
15
- * `/chat/completions` endpoint. Reuses `OpenAIChat.protocol` end-to-end and
16
- * overrides only the route id so providers can be resolved per-family without
17
- * colliding with native OpenAI. The model carries the host on `baseURL`,
18
- * supplied by whichever profile/provider helper builds it.
19
- */
20
- export const route = Route.make({
21
- id: ADAPTER,
22
- protocol: OpenAIChat.protocol,
23
- endpoint: Endpoint.path("/chat/completions"),
24
- framing: Framing.sse,
25
- })
26
-
27
- export const model = Route.model<OpenAICompatibleChatModelInput>(route)
28
-
29
- export * as OpenAICompatibleChat from "./openai-compatible-chat"