taugraph 0.0.0-stage → 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.
- package/CHANGELOG.md +62 -0
- package/LICENSE +21 -0
- package/README.md +447 -2
- package/README.zh-CN.md +448 -0
- package/dist/agent/index.d.ts +66 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +228 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/state.d.ts +30 -0
- package/dist/agent/state.d.ts.map +1 -0
- package/dist/agent/state.js +135 -0
- package/dist/agent/state.js.map +1 -0
- package/dist/agent/util.d.ts +9 -0
- package/dist/agent/util.d.ts.map +1 -0
- package/dist/agent/util.js +28 -0
- package/dist/agent/util.js.map +1 -0
- package/dist/core/engine.d.ts +51 -0
- package/dist/core/engine.d.ts.map +1 -0
- package/dist/core/engine.js +412 -0
- package/dist/core/engine.js.map +1 -0
- package/dist/core/errors.d.ts +48 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +30 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/graph.d.ts +11 -0
- package/dist/core/graph.d.ts.map +1 -0
- package/dist/core/graph.js +134 -0
- package/dist/core/graph.js.map +1 -0
- package/dist/core/node.d.ts +7 -0
- package/dist/core/node.d.ts.map +1 -0
- package/dist/core/node.js +22 -0
- package/dist/core/node.js.map +1 -0
- package/dist/core/standard-schema.d.ts +39 -0
- package/dist/core/standard-schema.d.ts.map +1 -0
- package/dist/core/standard-schema.js +2 -0
- package/dist/core/standard-schema.js.map +1 -0
- package/dist/core/trace.d.ts +90 -0
- package/dist/core/trace.d.ts.map +1 -0
- package/dist/core/trace.js +290 -0
- package/dist/core/trace.js.map +1 -0
- package/dist/core/types.d.ts +175 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/util.d.ts +19 -0
- package/dist/core/util.d.ts.map +1 -0
- package/dist/core/util.js +85 -0
- package/dist/core/util.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/nodes/code.d.ts +12 -0
- package/dist/nodes/code.d.ts.map +1 -0
- package/dist/nodes/code.js +9 -0
- package/dist/nodes/code.js.map +1 -0
- package/dist/nodes/content.d.ts +18 -0
- package/dist/nodes/content.d.ts.map +1 -0
- package/dist/nodes/content.js +88 -0
- package/dist/nodes/content.js.map +1 -0
- package/dist/nodes/human.d.ts +17 -0
- package/dist/nodes/human.d.ts.map +1 -0
- package/dist/nodes/human.js +18 -0
- package/dist/nodes/human.js.map +1 -0
- package/dist/nodes/index.d.ts +5 -0
- package/dist/nodes/index.d.ts.map +1 -0
- package/dist/nodes/index.js +7 -0
- package/dist/nodes/index.js.map +1 -0
- package/dist/nodes/llm.d.ts +157 -0
- package/dist/nodes/llm.d.ts.map +1 -0
- package/dist/nodes/llm.js +54 -0
- package/dist/nodes/llm.js.map +1 -0
- package/dist/nodes/util.d.ts +5 -0
- package/dist/nodes/util.d.ts.map +1 -0
- package/dist/nodes/util.js +11 -0
- package/dist/nodes/util.js.map +1 -0
- package/dist/openai/index.d.ts +39 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +178 -0
- package/dist/openai/index.js.map +1 -0
- package/package.json +86 -4
- package/src/agent/index.ts +315 -0
- package/src/agent/state.ts +147 -0
- package/src/agent/util.ts +35 -0
- package/src/core/engine.ts +552 -0
- package/src/core/errors.ts +70 -0
- package/src/core/graph.ts +166 -0
- package/src/core/node.ts +24 -0
- package/src/core/standard-schema.ts +47 -0
- package/src/core/trace.ts +346 -0
- package/src/core/types.ts +206 -0
- package/src/core/util.ts +81 -0
- package/src/index.ts +46 -0
- package/src/nodes/code.ts +18 -0
- package/src/nodes/content.ts +100 -0
- package/src/nodes/human.ts +33 -0
- package/src/nodes/index.ts +25 -0
- package/src/nodes/llm.ts +219 -0
- package/src/nodes/util.ts +13 -0
- package/src/openai/index.ts +246 -0
package/src/nodes/llm.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { defineNode, type MaybePromise, type Node, type RetryPolicy, type StandardSchemaV1 } from "../index.js";
|
|
2
|
+
import { andThen, issuesMessage } from "./util.js";
|
|
3
|
+
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// Model contract. Adapt any SDK or HTTP API to this; taugraph/openai covers OpenAI-compatible endpoints.
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
/** A tool the model may call. Field names follow MCP; `inputSchema` is JSON Schema for the arguments object. */
|
|
9
|
+
export interface ToolSpec {
|
|
10
|
+
/** Letters, digits, `_` and `-`, at most 64 characters: what every major provider accepts. */
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly description?: string;
|
|
13
|
+
readonly inputSchema: Readonly<Record<string, unknown>>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A call the model asked for. Arguments are parsed JSON, as in MCP and Anthropic; adapters convert OpenAI's string. */
|
|
17
|
+
export interface ToolCall {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly arguments: Readonly<Record<string, unknown>>;
|
|
21
|
+
/** Set by an adapter that could not read the arguments as a JSON object; `arguments` is then `{}`. */
|
|
22
|
+
readonly parseError?: string;
|
|
23
|
+
/** The provider's opaque proof for this call (Gemini's thought signature). Send it back to the same model only. */
|
|
24
|
+
readonly signature?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** How the model may use tools: freely, not at all, at least one, or this one. */
|
|
28
|
+
export type ToolChoice = "auto" | "none" | "required" | { readonly name: string };
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* How much a model should think before it answers. Adapters map it to the provider's setting; an adapter that knows
|
|
32
|
+
* which levels a model has rounds to the nearest one.
|
|
33
|
+
*/
|
|
34
|
+
export type ReasoningLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* What a model thought before answering, in the order it gave. `signature` is the provider's opaque proof and is only
|
|
38
|
+
* valid for the model that wrote it: adapters send it back when the assistant message's `model` is their own `id`.
|
|
39
|
+
*/
|
|
40
|
+
export interface ReasoningPart {
|
|
41
|
+
readonly text: string;
|
|
42
|
+
readonly signature?: string;
|
|
43
|
+
/** The provider hid the text (a safety filter); `signature` holds the encrypted payload. */
|
|
44
|
+
readonly redacted?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Text in a message. */
|
|
48
|
+
export interface TextPart {
|
|
49
|
+
readonly type: "text";
|
|
50
|
+
readonly text: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* An image in a message: its bytes in base64 (`data`, without a `data:` prefix), or a URL. A URL may be `https:`,
|
|
55
|
+
* `data:`, or a reference of your own such as `media:abc` that the adapter reads when it calls the model, which keeps
|
|
56
|
+
* traces and snapshots small. Field names follow MCP. If both `data` and `url` are present, `data` wins; narrow with
|
|
57
|
+
* `"data" in image`.
|
|
58
|
+
*/
|
|
59
|
+
export type ImagePart =
|
|
60
|
+
| { readonly type: "image"; readonly data: string; readonly mimeType: string }
|
|
61
|
+
| { readonly type: "image"; readonly url: string; readonly mimeType?: string };
|
|
62
|
+
|
|
63
|
+
export type ContentPart = TextPart | ImagePart;
|
|
64
|
+
|
|
65
|
+
/** What a user message or a tool result carries: plain text, or text and images in order. */
|
|
66
|
+
export type MessageContent = string | readonly ContentPart[];
|
|
67
|
+
|
|
68
|
+
/** One message of a conversation. User messages and tool results may carry images; the others are text. */
|
|
69
|
+
export type ChatMessage =
|
|
70
|
+
| { readonly role: "system"; readonly content: string }
|
|
71
|
+
| { readonly role: "user"; readonly content: MessageContent }
|
|
72
|
+
| {
|
|
73
|
+
readonly role: "assistant";
|
|
74
|
+
readonly content: string;
|
|
75
|
+
readonly toolCalls?: readonly ToolCall[];
|
|
76
|
+
/** What the model thought first. */
|
|
77
|
+
readonly reasoning?: readonly ReasoningPart[];
|
|
78
|
+
/**
|
|
79
|
+
* The `LLMModel.id` that wrote this message (not `LLMResponse.model`). Adapters send reasoning signatures,
|
|
80
|
+
* `redacted` parts and `ToolCall.signature` back only when it equals their own `id`.
|
|
81
|
+
*/
|
|
82
|
+
readonly model?: string;
|
|
83
|
+
}
|
|
84
|
+
| {
|
|
85
|
+
readonly role: "tool";
|
|
86
|
+
readonly toolCallId: string;
|
|
87
|
+
readonly content: MessageContent;
|
|
88
|
+
readonly isError?: boolean;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Everything in a request is recorded in the trace, so keep it plain JSON. */
|
|
92
|
+
export interface LLMRequest {
|
|
93
|
+
readonly messages: readonly ChatMessage[];
|
|
94
|
+
readonly temperature?: number;
|
|
95
|
+
readonly maxTokens?: number;
|
|
96
|
+
/** Hint for adapters that support JSON mode. */
|
|
97
|
+
readonly responseFormat?: "text" | "json";
|
|
98
|
+
/** Provider-specific options, passed through by the adapter. */
|
|
99
|
+
readonly extra?: Readonly<Record<string, unknown>>;
|
|
100
|
+
/** Tools the model may call; adapters translate them to the provider's format. */
|
|
101
|
+
readonly tools?: readonly ToolSpec[];
|
|
102
|
+
readonly toolChoice?: ToolChoice;
|
|
103
|
+
/** How much the model should think first. Unset: the adapter sends nothing and the model uses its default. */
|
|
104
|
+
readonly reasoning?: ReasoningLevel;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface LLMResponse {
|
|
108
|
+
readonly content: string;
|
|
109
|
+
/** The provider's name for the model that answered, e.g. "gpt-4o-mini-2024-07-18". Not the `LLMModel.id`. */
|
|
110
|
+
readonly model?: string;
|
|
111
|
+
readonly finishReason?: string;
|
|
112
|
+
readonly usage?: {
|
|
113
|
+
readonly inputTokens?: number;
|
|
114
|
+
readonly outputTokens?: number;
|
|
115
|
+
/** Tokens spent thinking; already counted in `outputTokens`. */
|
|
116
|
+
readonly reasoningTokens?: number;
|
|
117
|
+
};
|
|
118
|
+
/** Tool calls the model asked for, in order. */
|
|
119
|
+
readonly toolCalls?: readonly ToolCall[];
|
|
120
|
+
/** What the model thought before answering, in order. */
|
|
121
|
+
readonly reasoning?: readonly ReasoningPart[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface LLMModel {
|
|
125
|
+
/**
|
|
126
|
+
* Recorded in every `llm_call` event, e.g. "openai:gpt-4o-mini" or "ollama:qwen3". It also decides which assistant
|
|
127
|
+
* messages count as this model's own for reasoning passback, so keep it stable and different for each model.
|
|
128
|
+
*/
|
|
129
|
+
readonly id: string;
|
|
130
|
+
complete(request: LLMRequest, options: { readonly signal: AbortSignal }): MaybePromise<LLMResponse>;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// LLMNode
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
interface LLMNodeBase<S> {
|
|
138
|
+
readonly model: LLMModel;
|
|
139
|
+
/** Builds the request from state. A string becomes a single user message. */
|
|
140
|
+
readonly prompt: (state: S) => LLMRequest | string;
|
|
141
|
+
/** Retries the whole call, including output parsing. */
|
|
142
|
+
readonly retry?: RetryPolicy;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface LLMTextNodeConfig<S> extends LLMNodeBase<S> {
|
|
146
|
+
/** Folds the reply into state. The return type does not drive inference; the graph does. */
|
|
147
|
+
readonly update: (state: S, text: string, response: LLMResponse) => NoInfer<S>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface LLMStructuredNodeConfig<S, T> extends LLMNodeBase<S> {
|
|
151
|
+
/** Parses the response content as JSON (code fences allowed) and validates it. */
|
|
152
|
+
readonly output: StandardSchemaV1<unknown, T>;
|
|
153
|
+
readonly update: (state: S, data: T, response: LLMResponse) => NoInfer<S>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Thrown when structured output is not JSON or fails its schema. Retryable. */
|
|
157
|
+
export class LLMOutputError extends Error {
|
|
158
|
+
override readonly name = "LLMOutputError";
|
|
159
|
+
constructor(
|
|
160
|
+
message: string,
|
|
161
|
+
readonly content: string,
|
|
162
|
+
readonly issues?: readonly StandardSchemaV1.Issue[],
|
|
163
|
+
) {
|
|
164
|
+
super(message);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Calls a model and folds the result into state. Every call is appended to the trace
|
|
170
|
+
* as an `llm_call` event (request in `input`, response in `output`).
|
|
171
|
+
* Stays synchronous when the model does, so mock models work with `runSync`.
|
|
172
|
+
*/
|
|
173
|
+
export function LLMNode<S, T>(config: LLMStructuredNodeConfig<S, T>): Node<S>;
|
|
174
|
+
export function LLMNode<S>(config: LLMTextNodeConfig<S>): Node<S>;
|
|
175
|
+
export function LLMNode<S, T>(config: LLMTextNodeConfig<S> | LLMStructuredNodeConfig<S, T>): Node<S> {
|
|
176
|
+
const { model, prompt } = config;
|
|
177
|
+
return defineNode<S>(
|
|
178
|
+
(state, ctx) => {
|
|
179
|
+
const built = prompt(state);
|
|
180
|
+
const request: LLMRequest = typeof built === "string" ? { messages: [{ role: "user", content: built }] } : built;
|
|
181
|
+
const startedAt = Date.now();
|
|
182
|
+
|
|
183
|
+
return andThen(model.complete(request, { signal: ctx.signal }), (response) => {
|
|
184
|
+
if (typeof response?.content !== "string") {
|
|
185
|
+
throw new TypeError(`Model "${model.id}" returned a response without a string \`content\``);
|
|
186
|
+
}
|
|
187
|
+
ctx.trace.append({
|
|
188
|
+
type: "llm_call",
|
|
189
|
+
input: request,
|
|
190
|
+
output: response,
|
|
191
|
+
meta: { model: model.id, durationMs: Date.now() - startedAt },
|
|
192
|
+
});
|
|
193
|
+
if (!("output" in config)) return config.update(state, response.content, response);
|
|
194
|
+
return andThen(parseStructured(config.output, response.content), (data) =>
|
|
195
|
+
config.update(state, data, response),
|
|
196
|
+
);
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
{ kind: "llm", ...(config.retry && { retry: config.retry }) },
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function parseStructured<T>(schema: StandardSchemaV1<unknown, T>, content: string): MaybePromise<T> {
|
|
204
|
+
const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(content);
|
|
205
|
+
const text = (fenced?.[1] ?? content).trim();
|
|
206
|
+
let json: unknown;
|
|
207
|
+
try {
|
|
208
|
+
json = JSON.parse(text);
|
|
209
|
+
} catch {
|
|
210
|
+
throw new LLMOutputError("Model output is not valid JSON", content);
|
|
211
|
+
}
|
|
212
|
+
return andThen(schema["~standard"].validate(json), (result) => {
|
|
213
|
+
if (result.issues) {
|
|
214
|
+
const detail = issuesMessage(result.issues);
|
|
215
|
+
throw new LLMOutputError(`Model output does not match the schema: ${detail}`, content, result.issues);
|
|
216
|
+
}
|
|
217
|
+
return result.value;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MaybePromise, StandardSchemaV1 } from "../index.js";
|
|
2
|
+
|
|
3
|
+
/** Chains without introducing a Promise when the value is synchronous, so nodes stay `runSync`-friendly. */
|
|
4
|
+
export function andThen<A, B>(value: MaybePromise<A>, fn: (value: A) => MaybePromise<B>): MaybePromise<B> {
|
|
5
|
+
if (value !== null && typeof value === "object" && typeof (value as PromiseLike<A>).then === "function") {
|
|
6
|
+
return Promise.resolve(value).then(fn);
|
|
7
|
+
}
|
|
8
|
+
return fn(value as A);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function issuesMessage(issues: readonly StandardSchemaV1.Issue[]): string {
|
|
12
|
+
return issues.map((issue) => issue.message).join("; ");
|
|
13
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// taugraph/openai: the LLMModel contract on any OpenAI-compatible /chat/completions endpoint (OpenAI, DeepSeek, Qwen,
|
|
2
|
+
// Kimi, Ollama, vLLM, LM Studio, ...), with tool calling, images and reasoning. A plugin like taugraph/agent: it uses
|
|
3
|
+
// the global fetch, or the one you pass, and adds no dependencies.
|
|
4
|
+
import type { MaybePromise } from "../index.js";
|
|
5
|
+
import {
|
|
6
|
+
type ChatMessage,
|
|
7
|
+
type ImagePart,
|
|
8
|
+
type ImageResolver,
|
|
9
|
+
type LLMModel,
|
|
10
|
+
type MessageContent,
|
|
11
|
+
type ReasoningLevel,
|
|
12
|
+
resolveImages,
|
|
13
|
+
type ToolCall,
|
|
14
|
+
type ToolChoice,
|
|
15
|
+
type ToolSpec,
|
|
16
|
+
textOf,
|
|
17
|
+
} from "../nodes/index.js";
|
|
18
|
+
|
|
19
|
+
export interface OpenAICompatibleOptions {
|
|
20
|
+
/** e.g. "https://api.openai.com/v1" or "http://localhost:11434/v1" for Ollama */
|
|
21
|
+
readonly baseURL: string;
|
|
22
|
+
readonly model: string;
|
|
23
|
+
readonly apiKey?: string | undefined;
|
|
24
|
+
/** Reads image URLs OpenAI cannot fetch, e.g. `media:abc` from your store. http(s) and data: URLs go as they are. */
|
|
25
|
+
readonly resolveImage?: ImageResolver | undefined;
|
|
26
|
+
/** Request parameters for a reasoning level, merged before `extra`. Default: `{ reasoning_effort }`, "off" as "none". */
|
|
27
|
+
readonly reasoningParams?: ((level: ReasoningLevel) => Record<string, unknown>) | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Send a model's own reasoning back as `reasoning_content`. Default true: DeepSeek V4 and Kimi refuse a tool loop
|
|
30
|
+
* without it. Set false for endpoints that refuse the field in input messages, such as Groq and Cerebras.
|
|
31
|
+
*/
|
|
32
|
+
readonly sendReasoning?: boolean | undefined;
|
|
33
|
+
/** Used instead of the global `fetch`, e.g. for a proxy, retries or tests. */
|
|
34
|
+
readonly fetch?: typeof fetch | undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A tool call as OpenAI sends it: arguments are a JSON string. */
|
|
38
|
+
export interface OpenAIToolCall {
|
|
39
|
+
readonly id?: string;
|
|
40
|
+
readonly type?: string;
|
|
41
|
+
readonly function?: { readonly name?: string; readonly arguments?: string };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ChatCompletion {
|
|
45
|
+
model?: string;
|
|
46
|
+
choices?: {
|
|
47
|
+
message?: {
|
|
48
|
+
content?: string | null;
|
|
49
|
+
tool_calls?: OpenAIToolCall[];
|
|
50
|
+
/** DeepSeek, Qwen, Kimi */
|
|
51
|
+
reasoning_content?: string | null;
|
|
52
|
+
/** OpenRouter, Ollama */
|
|
53
|
+
reasoning?: string | null;
|
|
54
|
+
};
|
|
55
|
+
finish_reason?: string;
|
|
56
|
+
}[];
|
|
57
|
+
usage?: {
|
|
58
|
+
prompt_tokens?: number;
|
|
59
|
+
completion_tokens?: number;
|
|
60
|
+
completion_tokens_details?: { reasoning_tokens?: number };
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const defaultReasoningParams = (level: ReasoningLevel): Record<string, unknown> => ({
|
|
65
|
+
reasoning_effort: level === "off" ? "none" : level,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** A model's own reasoning as `reasoning_content`, which DeepSeek V4 requires back in tool loops. Never another model's. */
|
|
69
|
+
function reasoningOf(
|
|
70
|
+
m: Extract<ChatMessage, { role: "assistant" }>,
|
|
71
|
+
modelId: string | undefined,
|
|
72
|
+
): Record<string, unknown> {
|
|
73
|
+
if (modelId === undefined || m.model !== modelId || !m.reasoning?.length) return {};
|
|
74
|
+
const text = m.reasoning
|
|
75
|
+
.filter((r) => !r.redacted)
|
|
76
|
+
.map((r) => r.text)
|
|
77
|
+
.join("\n");
|
|
78
|
+
return text === "" ? {} : { reasoning_content: text };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** URLs OpenAI takes as they are. */
|
|
82
|
+
const SENDABLE = /^(https?|data):/i;
|
|
83
|
+
const shown = (url: string): string => (url.length > 100 ? `${url.slice(0, 100)}…` : url);
|
|
84
|
+
|
|
85
|
+
function imageURL(image: ImagePart): string {
|
|
86
|
+
if ("data" in image) return `data:${image.mimeType};base64,${image.data}`;
|
|
87
|
+
if (!SENDABLE.test(image.url)) {
|
|
88
|
+
throw new TypeError(
|
|
89
|
+
`Image "${shown(image.url)}" cannot be sent as a URL; make resolveImage return { data, mimeType } or an http(s) URL`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
return image.url;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const imageOf = (image: ImagePart) => ({ type: "image_url", image_url: { url: imageURL(image) } });
|
|
96
|
+
|
|
97
|
+
const imagesIn = (content: MessageContent): ImagePart[] =>
|
|
98
|
+
typeof content === "string" ? [] : content.filter((p): p is ImagePart => p.type === "image");
|
|
99
|
+
|
|
100
|
+
/** OpenAI's tool messages take text only, and have no error flag: errors say so in the text. */
|
|
101
|
+
function toolText(m: Extract<ChatMessage, { role: "tool" }>): string {
|
|
102
|
+
const text = textOf(m.content, { imagePlaceholder: "" }) || (imagesIn(m.content).length > 0 ? "(image)" : "");
|
|
103
|
+
return m.isError && !text.startsWith("Error") ? `Error: ${text}` : text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* taugraph messages in OpenAI's wire format. Images from tool results go into one user message right after the
|
|
108
|
+
* tool messages, since OpenAI's tool messages take text only. Image references must be read first (`resolveImage`).
|
|
109
|
+
* Pass the adapter's id as `modelId` to send that model's own reasoning back.
|
|
110
|
+
*/
|
|
111
|
+
export function toOpenAIMessages(messages: readonly ChatMessage[], modelId?: string): Record<string, unknown>[] {
|
|
112
|
+
const out: Record<string, unknown>[] = [];
|
|
113
|
+
let toolImages: Record<string, unknown>[] = [];
|
|
114
|
+
const flush = () => {
|
|
115
|
+
if (toolImages.length > 0) out.push({ role: "user", content: toolImages });
|
|
116
|
+
toolImages = [];
|
|
117
|
+
};
|
|
118
|
+
for (const m of messages) {
|
|
119
|
+
if (m.role === "tool") {
|
|
120
|
+
out.push({ role: "tool", tool_call_id: m.toolCallId, content: toolText(m) });
|
|
121
|
+
const images = imagesIn(m.content);
|
|
122
|
+
if (images.length > 0) {
|
|
123
|
+
toolImages.push({ type: "text", text: `Images from tool call ${m.toolCallId}:` }, ...images.map(imageOf));
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
flush();
|
|
128
|
+
if (m.role === "assistant" && m.toolCalls?.length) {
|
|
129
|
+
out.push({
|
|
130
|
+
role: "assistant",
|
|
131
|
+
content: m.content === "" ? null : m.content,
|
|
132
|
+
tool_calls: m.toolCalls.map((c) => ({
|
|
133
|
+
id: c.id,
|
|
134
|
+
type: "function",
|
|
135
|
+
function: { name: c.name, arguments: JSON.stringify(c.arguments) },
|
|
136
|
+
})),
|
|
137
|
+
...reasoningOf(m, modelId),
|
|
138
|
+
});
|
|
139
|
+
} else if (m.role === "user" && typeof m.content !== "string") {
|
|
140
|
+
out.push({
|
|
141
|
+
role: "user",
|
|
142
|
+
content: m.content.map((p) => (p.type === "text" ? { type: "text", text: p.text } : imageOf(p))),
|
|
143
|
+
});
|
|
144
|
+
} else {
|
|
145
|
+
out.push({ role: m.role, content: m.content, ...(m.role === "assistant" && reasoningOf(m, modelId)) });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
flush();
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function toOpenAITools(tools: readonly ToolSpec[]): Record<string, unknown>[] {
|
|
153
|
+
return tools.map((t) => ({
|
|
154
|
+
type: "function",
|
|
155
|
+
function: { name: t.name, ...(t.description && { description: t.description }), parameters: t.inputSchema },
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function toOpenAIToolChoice(choice: ToolChoice): unknown {
|
|
160
|
+
return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** OpenAI's tool calls as taugraph's, arguments parsed. Unreadable arguments become `{}` with a `parseError`; missing ids become `call_<round>_<index>`. */
|
|
164
|
+
export function fromOpenAIToolCalls(calls: readonly OpenAIToolCall[], round = 1): ToolCall[] {
|
|
165
|
+
return calls.flatMap((c, i) => {
|
|
166
|
+
const name = c.function?.name;
|
|
167
|
+
if (!name) return [];
|
|
168
|
+
const raw = c.function?.arguments ?? "";
|
|
169
|
+
let parsed: unknown = {};
|
|
170
|
+
let parseError: string | undefined;
|
|
171
|
+
if (raw.trim() !== "") {
|
|
172
|
+
try {
|
|
173
|
+
parsed = JSON.parse(raw);
|
|
174
|
+
} catch {
|
|
175
|
+
parseError = "arguments are not valid JSON";
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
|
|
179
|
+
if (!parseError && !isObject) parseError = "arguments are not a JSON object";
|
|
180
|
+
return [
|
|
181
|
+
{
|
|
182
|
+
id: c.id || `call_${round}_${i}`,
|
|
183
|
+
name,
|
|
184
|
+
arguments: isObject && !parseError ? (parsed as Record<string, unknown>) : {},
|
|
185
|
+
...(parseError && { parseError }),
|
|
186
|
+
},
|
|
187
|
+
];
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function openAICompatible(options: OpenAICompatibleOptions): LLMModel {
|
|
192
|
+
const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
|
|
193
|
+
const id = `openai-compatible:${options.model}`;
|
|
194
|
+
const readImage = (image: string): MaybePromise<ImagePart> => {
|
|
195
|
+
if (/^https?:/i.test(image)) return { type: "image", url: image };
|
|
196
|
+
if (!options.resolveImage) throw new TypeError(`Image "${shown(image)}" needs resolveImage to be read`);
|
|
197
|
+
return options.resolveImage(image);
|
|
198
|
+
};
|
|
199
|
+
return {
|
|
200
|
+
id,
|
|
201
|
+
async complete(request, { signal }) {
|
|
202
|
+
const messages = await resolveImages(request.messages, readImage);
|
|
203
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
204
|
+
method: "POST",
|
|
205
|
+
signal,
|
|
206
|
+
headers: {
|
|
207
|
+
"content-type": "application/json",
|
|
208
|
+
...(options.apiKey && { authorization: `Bearer ${options.apiKey}` }),
|
|
209
|
+
},
|
|
210
|
+
body: JSON.stringify({
|
|
211
|
+
model: options.model,
|
|
212
|
+
messages: toOpenAIMessages(messages, options.sendReasoning === false ? undefined : id),
|
|
213
|
+
temperature: request.temperature,
|
|
214
|
+
max_tokens: request.maxTokens,
|
|
215
|
+
...(request.responseFormat === "json" && { response_format: { type: "json_object" } }),
|
|
216
|
+
...(request.tools?.length && { tools: toOpenAITools(request.tools) }),
|
|
217
|
+
...(request.toolChoice && { tool_choice: toOpenAIToolChoice(request.toolChoice) }),
|
|
218
|
+
...(request.reasoning && (options.reasoningParams ?? defaultReasoningParams)(request.reasoning)),
|
|
219
|
+
...request.extra,
|
|
220
|
+
}),
|
|
221
|
+
});
|
|
222
|
+
if (!response.ok) {
|
|
223
|
+
throw new Error(`${url} responded ${response.status}: ${(await response.text()).slice(0, 500)}`);
|
|
224
|
+
}
|
|
225
|
+
const body = (await response.json()) as ChatCompletion;
|
|
226
|
+
const choice = body.choices?.[0];
|
|
227
|
+
const calls = choice?.message?.tool_calls;
|
|
228
|
+
const round = request.messages.filter((m) => m.role === "assistant").length + 1;
|
|
229
|
+
const message = choice?.message;
|
|
230
|
+
const thought = message?.reasoning_content || message?.reasoning;
|
|
231
|
+
const reasoningTokens = body.usage?.completion_tokens_details?.reasoning_tokens;
|
|
232
|
+
return {
|
|
233
|
+
content: message?.content ?? "",
|
|
234
|
+
...(body.model && { model: body.model }),
|
|
235
|
+
...(choice?.finish_reason && { finishReason: choice.finish_reason }),
|
|
236
|
+
usage: {
|
|
237
|
+
inputTokens: body.usage?.prompt_tokens ?? 0,
|
|
238
|
+
outputTokens: body.usage?.completion_tokens ?? 0,
|
|
239
|
+
...(typeof reasoningTokens === "number" && { reasoningTokens }),
|
|
240
|
+
},
|
|
241
|
+
...(thought && { reasoning: [{ text: thought }] }),
|
|
242
|
+
...(calls?.length && { toolCalls: fromOpenAIToolCalls(calls, round) }),
|
|
243
|
+
};
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|