taugraph 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.
- package/CHANGELOG.md +62 -0
- package/README.md +232 -18
- package/README.zh-CN.md +232 -18
- 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/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/index.d.ts +2 -1
- package/dist/nodes/index.d.ts.map +1 -1
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/index.js.map +1 -1
- package/dist/nodes/llm.d.ts +98 -4
- package/dist/nodes/llm.d.ts.map +1 -1
- package/dist/nodes/llm.js.map +1 -1
- 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 +15 -3
- package/src/agent/index.ts +315 -0
- package/src/agent/state.ts +147 -0
- package/src/agent/util.ts +35 -0
- package/src/nodes/content.ts +100 -0
- package/src/nodes/index.ts +10 -0
- package/src/nodes/llm.ts +102 -6
- package/src/openai/index.ts +246 -0
|
@@ -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
|
+
}
|