@tinyweb_dev/agent-framework-llm 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tinyweb-agent-framework contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @tinyweb-agent-framework/llm
2
+
3
+ LLM core: schemas, **OpenAI Chat protocol**, route architecture, tool runtime, and provider profiles.
4
+
5
+ Adapted from [opencode](https://github.com/sst/opencode)'s `@opencode-ai/llm` package, slimmed to OpenAI Chat only.
6
+
7
+ ## Surface
8
+
9
+ ```ts
10
+ import {
11
+ LLM, // request/generate/stream/helpers facade
12
+ LLMClient, // Service + layer + prepare/stream/generate
13
+ Tool, // Tool.make typed-tool builder
14
+ Route, // Route.make / Route.model
15
+ OpenAI, // canonical OpenAI provider
16
+ OpenAICompatible, // deepseek/together/groq/cerebras/fireworks/deepinfra/openrouter/xai/ollama/lmstudio
17
+ Auth, AuthOptions, // bearer / header / config / fromModelApiKey
18
+ ProviderShared, // joinText, parseToolInput, validateWith, …
19
+ } from "@tinyweb-agent-framework/llm"
20
+ ```
21
+
22
+ ## Models
23
+
24
+ ```ts
25
+ import { OpenAI, OpenAICompatible } from "@tinyweb-agent-framework/llm"
26
+
27
+ // OpenAI
28
+ const m1 = OpenAI.chat("gpt-4o-mini", { apiKey: process.env.OPENAI_API_KEY })
29
+
30
+ // Any OpenAI-compatible profile (DeepSeek, Together, Groq, Ollama, …)
31
+ const m2 = OpenAICompatible.deepseek("deepseek-chat", { apiKey: process.env.DEEPSEEK_API_KEY })
32
+ const m3 = OpenAICompatible.ollama("llama3", { apiKey: "ollama" })
33
+ ```
34
+
35
+ ## Tools
36
+
37
+ ```ts
38
+ import { Tool, ToolFailure } from "@tinyweb-agent-framework/llm"
39
+ import { Effect, Schema } from "effect"
40
+
41
+ const search = Tool.make({
42
+ description: "Search the web",
43
+ parameters: Schema.Struct({ query: Schema.String, limit: Schema.optional(Schema.Number) }),
44
+ success: Schema.Struct({ results: Schema.Array(Schema.String) }),
45
+ execute: ({ query }) =>
46
+ Effect.tryPromise({
47
+ try: () => fetch(`https://example.com/api?q=${query}`).then((r) => r.json()),
48
+ catch: (e) => new ToolFailure({ message: String(e) }),
49
+ }),
50
+ })
51
+ ```
52
+
53
+ ## Architecture
54
+
55
+ Four-axis decomposition: **Protocol** (body & stream schema), **Endpoint**, **Auth**, **Framing** — composed via `Route.make({ id, protocol, transport, defaults })`. See `src/route/` and `src/protocols/openai-chat.ts`.
56
+
57
+ ## License
58
+
59
+ MIT
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/package.json",
3
+ "name": "@tinyweb_dev/agent-framework-llm",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "typecheck": "tsc --noEmit",
9
+ "test": "bun test --timeout 30000"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./schema": "./src/schema/index.ts",
19
+ "./tool": "./src/tool.ts",
20
+ "./tool-runtime": "./src/tool-runtime.ts",
21
+ "./route": "./src/route/client.ts",
22
+ "./route/auth": "./src/route/auth.ts",
23
+ "./route/auth-options": "./src/route/auth-options.ts",
24
+ "./route/endpoint": "./src/route/endpoint.ts",
25
+ "./route/framing": "./src/route/framing.ts",
26
+ "./route/protocol": "./src/route/protocol.ts",
27
+ "./route/executor": "./src/route/executor.ts",
28
+ "./route/transport": "./src/route/transport/index.ts",
29
+ "./protocols/shared": "./src/protocols/shared.ts",
30
+ "./protocols/openai-chat": "./src/protocols/openai-chat.ts",
31
+ "./protocols/openai-compatible-chat": "./src/protocols/openai-compatible-chat.ts",
32
+ "./provider": "./src/provider.ts",
33
+ "./providers/openai": "./src/providers/openai.ts",
34
+ "./providers/openai-compatible": "./src/providers/openai-compatible.ts",
35
+ "./providers/openai-compatible-profile": "./src/providers/openai-compatible-profile.ts",
36
+ "./providers/openai-options": "./src/providers/openai-options.ts",
37
+ "./llm": "./src/llm.ts"
38
+ },
39
+ "devDependencies": {
40
+ "@tsconfig/bun": "1.0.9",
41
+ "@types/bun": "1.3.12",
42
+ "typescript": "5.8.2"
43
+ },
44
+ "dependencies": {
45
+ "effect": "4.0.0-beta.59",
46
+ "@tinyweb_dev/agent-framework-core": "0.1.0"
47
+ }
48
+ }
@@ -0,0 +1,92 @@
1
+ // Adapted from opencode@v1.14.48 packages/llm/src/cache-policy.ts
2
+ // Apply an `LLMRequest.cache` policy by injecting `CacheHint`s onto the parts
3
+ // the policy designates. Runs once at compile time, before the per-protocol
4
+ // body builder, so the existing inline-hint lowering path handles the rest.
5
+ //
6
+ // At v1 only the OpenAI Chat protocol is supported, and OpenAI uses implicit
7
+ // prefix caching (no inline cache markers). `RESPECTS_INLINE_HINTS` is empty,
8
+ // so this function is effectively a passthrough today. The full policy
9
+ // engine is kept in place so adding Anthropic/Bedrock protocols later is a
10
+ // route-registration change only.
11
+ import { CacheHint, type CachePolicy, type CachePolicyObject } from "./schema/options"
12
+ import { LLMRequest, Message, ToolDefinition, type ContentPart } from "./schema/messages"
13
+
14
+ const AUTO: CachePolicyObject = {
15
+ tools: true,
16
+ system: true,
17
+ messages: "latest-user-message",
18
+ }
19
+
20
+ const NONE: CachePolicyObject = {}
21
+
22
+ const resolve = (policy: CachePolicy | undefined): CachePolicyObject => {
23
+ if (policy === undefined || policy === "auto") return AUTO
24
+ if (policy === "none") return NONE
25
+ return policy
26
+ }
27
+
28
+ // Protocols whose wire format honors inline cache markers. None at v1.
29
+ const RESPECTS_INLINE_HINTS = new Set<string>([])
30
+
31
+ const makeHint = (ttlSeconds: number | undefined): CacheHint =>
32
+ ttlSeconds !== undefined ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" })
33
+
34
+ const markLastTool = (tools: ReadonlyArray<ToolDefinition>, hint: CacheHint): ReadonlyArray<ToolDefinition> => {
35
+ if (tools.length === 0) return tools
36
+ const last = tools.length - 1
37
+ if (tools[last]!.cache) return tools
38
+ return tools.map((tool, i) => (i === last ? new ToolDefinition({ ...tool, cache: hint }) : tool))
39
+ }
40
+
41
+ const markLastSystem = (system: LLMRequest["system"], hint: CacheHint): LLMRequest["system"] => {
42
+ if (system.length === 0) return system
43
+ const last = system.length - 1
44
+ if (system[last]!.cache) return system
45
+ return system.map((part, i) => (i === last ? { ...part, cache: hint } : part))
46
+ }
47
+
48
+ const lastIndexOfRole = (messages: ReadonlyArray<Message>, role: Message["role"]): number =>
49
+ messages.findLastIndex((m) => m.role === role)
50
+
51
+ const markMessageAt = (messages: ReadonlyArray<Message>, index: number, hint: CacheHint): ReadonlyArray<Message> => {
52
+ if (index < 0 || index >= messages.length) return messages
53
+ const target = messages[index]!
54
+ if (target.content.length === 0) return messages
55
+ const lastTextIndex = target.content.findLastIndex((part) => part.type === "text")
56
+ const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.length - 1
57
+ const existing = target.content[markAt]!
58
+ if ("cache" in existing && existing.cache) return messages
59
+ const nextContent = target.content.map((part, i) => (i === markAt ? ({ ...part, cache: hint } as ContentPart) : part))
60
+ const next = new Message({ ...target, content: nextContent })
61
+ const result = messages.slice()
62
+ result[index] = next
63
+ return result
64
+ }
65
+
66
+ const markMessages = (
67
+ messages: ReadonlyArray<Message>,
68
+ strategy: NonNullable<CachePolicyObject["messages"]>,
69
+ hint: CacheHint,
70
+ ): ReadonlyArray<Message> => {
71
+ if (messages.length === 0) return messages
72
+ if (strategy === "latest-user-message") return markMessageAt(messages, lastIndexOfRole(messages, "user"), hint)
73
+ if (strategy === "latest-assistant") return markMessageAt(messages, lastIndexOfRole(messages, "assistant"), hint)
74
+ const start = Math.max(0, messages.length - strategy.tail)
75
+ let next = messages
76
+ for (let i = start; i < messages.length; i++) next = markMessageAt(next, i, hint)
77
+ return next
78
+ }
79
+
80
+ export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
81
+ if (!RESPECTS_INLINE_HINTS.has(request.model.route)) return request
82
+ const policy = resolve(request.cache)
83
+ if (!policy.tools && !policy.system && !policy.messages) return request
84
+
85
+ const hint = makeHint(policy.ttlSeconds)
86
+ const tools = policy.tools ? markLastTool(request.tools, hint) : request.tools
87
+ const system = policy.system ? markLastSystem(request.system, hint) : request.system
88
+ const messages = policy.messages ? markMessages(request.messages, policy.messages, hint) : request.messages
89
+
90
+ if (tools === request.tools && system === request.system && messages === request.messages) return request
91
+ return LLMRequest.update(request, { tools, system, messages })
92
+ }
package/src/index.ts ADDED
@@ -0,0 +1,62 @@
1
+ export const VERSION = "0.0.1"
2
+
3
+ export * from "./schema"
4
+ export {
5
+ Tool,
6
+ type AnyTool,
7
+ type AnyExecutableTool,
8
+ type ExecutableTool,
9
+ type ExecutableTools,
10
+ type Tools,
11
+ type ToolSchema,
12
+ type ToolExecute,
13
+ tool,
14
+ toDefinitions,
15
+ make,
16
+ } from "./tool"
17
+ export {
18
+ ToolRuntime,
19
+ stream as runtimeStream,
20
+ stepCountIs,
21
+ hasToolCall,
22
+ stopWhenAny,
23
+ type RunOptions,
24
+ type RunOptionsAuto,
25
+ type RunOptionsNone,
26
+ type StopCondition,
27
+ type StreamOptions,
28
+ type ToolExecution,
29
+ type RuntimeState,
30
+ } from "./tool-runtime"
31
+ export { Protocol } from "./route/protocol"
32
+ export { Endpoint } from "./route/endpoint"
33
+ export { Framing } from "./route/framing"
34
+ export { Auth, MissingCredentialError, type AuthInput, type AuthError, type Credential } from "./route/auth"
35
+ export { AuthOptions, type AtLeastOne, type ApiKeyMode, type ProviderAuthOption } from "./route/auth-options"
36
+ export { HttpTransport, type Transport, type TransportRuntime } from "./route/transport"
37
+ export { RequestExecutor } from "./route/executor"
38
+ export {
39
+ isOverflowMessage,
40
+ isOverflowStatus,
41
+ isOverflowBody,
42
+ extractOverflowNumbers,
43
+ } from "./route/overflow-detect"
44
+ export {
45
+ LLMClient,
46
+ Route,
47
+ type ModelRefInput,
48
+ type RouteModelInput,
49
+ type RouteRoutedModelInput,
50
+ type RouteDefaults,
51
+ modelRef,
52
+ modelLimits,
53
+ } from "./route/client"
54
+ export { ProviderShared } from "./protocols/shared"
55
+ export { OpenAIChat, type OpenAIChatBody } from "./protocols/openai-chat"
56
+ export { OpenAICompatibleChat, type OpenAICompatibleChatModelInput } from "./protocols/openai-compatible-chat"
57
+ export { Provider, type Definition as ProviderDefinition, type ModelFactory } from "./provider"
58
+ export { OpenAI } from "./providers/openai"
59
+ export { OpenAICompatible } from "./providers/openai-compatible"
60
+ export { profiles as openAICompatibleProfiles, type OpenAICompatibleProfile } from "./providers/openai-compatible-profile"
61
+ export { OpenAIProviderOptions, type OpenAIOptionsInput, type OpenAIProviderOptionsInput } from "./providers/openai-options"
62
+ export { LLM } from "./llm"
package/src/llm.ts ADDED
@@ -0,0 +1,210 @@
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"