llm-large-files 0.5.0 → 0.7.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 +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "llm-large-files",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"llm",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"peerDependencies": {
|
|
95
95
|
"@cantoo/pdf-lib": "^2.11.1",
|
|
96
96
|
"jszip": "^3.10.0",
|
|
97
|
-
"unpdf": "^1.4.0"
|
|
97
|
+
"unpdf": "^1.4.0 || ^2.0.0"
|
|
98
98
|
},
|
|
99
99
|
"peerDependenciesMeta": {
|
|
100
100
|
"@cantoo/pdf-lib": {
|
package/src/analyze.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { TimeSlicer } from "./pause.js";
|
|
2
|
+
import { sliceWhole } from "./text.js";
|
|
1
3
|
import type { DocumentFormat, LogIssue, LogProfile, OutlineEntry } from "./types.js";
|
|
2
4
|
|
|
3
5
|
const MAX_OUTLINE_ENTRIES = 400;
|
|
@@ -9,7 +11,8 @@ const LEVEL_NAMES: Record<string, string> = { ERR: "ERROR", WARNING: "WARN", CRI
|
|
|
9
11
|
|
|
10
12
|
/** Treats text as a log when most early lines start with a timestamp or a level. */
|
|
11
13
|
export function looksLikeLog(lines: string[]): boolean {
|
|
12
|
-
const sample =
|
|
14
|
+
const sample: string[] = [];
|
|
15
|
+
for (let index = 0; index < lines.length && sample.length < 200; index++) if (lines[index]!.trim()) sample.push(lines[index]!);
|
|
13
16
|
if (sample.length < 5) return false;
|
|
14
17
|
const hits = sample.filter((line) => LINE_START_TIMESTAMP.test(line.trim()) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/.test(line.trim())).length;
|
|
15
18
|
return hits / sample.length >= 0.4;
|
|
@@ -20,36 +23,63 @@ export function buildOutline(lines: string[], format: DocumentFormat): OutlineEn
|
|
|
20
23
|
if (format === "log" || format === "json" || format === "csv") return [];
|
|
21
24
|
const entries: OutlineEntry[] = [];
|
|
22
25
|
for (let index = 0; index < lines.length; index++) {
|
|
23
|
-
const
|
|
24
|
-
if (
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
entry = { line: index + 1, level: 2, title: line };
|
|
36
|
-
}
|
|
26
|
+
const entry = outlineEntry(lines, index);
|
|
27
|
+
if (entry) entries.push(entry);
|
|
28
|
+
}
|
|
29
|
+
return pickOutline(entries);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
|
|
33
|
+
export async function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]> {
|
|
34
|
+
if (format === "log" || format === "json" || format === "csv") return [];
|
|
35
|
+
const entries: OutlineEntry[] = [];
|
|
36
|
+
for (let index = 0; index < lines.length; index++) {
|
|
37
|
+
const entry = outlineEntry(lines, index);
|
|
37
38
|
if (entry) entries.push(entry);
|
|
39
|
+
if ((index & 4095) === 4095) await slicer.maybePause();
|
|
40
|
+
}
|
|
41
|
+
return pickOutline(entries);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The heading on line `index` (0-based), if it is one. */
|
|
45
|
+
function outlineEntry(lines: string[], index: number): OutlineEntry | undefined {
|
|
46
|
+
const line = (lines[index] ?? "").trim();
|
|
47
|
+
if (!line || line.length > 120) return undefined;
|
|
48
|
+
const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
|
|
49
|
+
const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
50
|
+
if (markdown) return { line: index + 1, level: markdown[1]!.length, title: markdown[2]!.trim() };
|
|
51
|
+
// A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
|
|
52
|
+
if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
|
|
53
|
+
return { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
|
|
54
|
+
}
|
|
55
|
+
if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
|
|
56
|
+
return { line: index + 1, level: (line.split(" ")[0]!.match(/\./g)?.length ?? 0) + 2, title: line };
|
|
38
57
|
}
|
|
58
|
+
if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
|
|
59
|
+
return { line: index + 1, level: 2, title: line };
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The outline kept from all the headings found: at most 400 of them. */
|
|
65
|
+
function pickOutline(entries: OutlineEntry[]): OutlineEntry[] {
|
|
39
66
|
if (entries.length <= MAX_OUTLINE_ENTRIES) return entries;
|
|
40
|
-
// Keep the top
|
|
67
|
+
// Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
|
|
68
|
+
// a larger one is sampled evenly, so the outline still spans the document.
|
|
41
69
|
// A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
|
|
42
70
|
let minLevel = Number.POSITIVE_INFINITY;
|
|
43
71
|
for (const entry of entries) if (entry.level < minLevel) minLevel = entry.level;
|
|
44
72
|
const top = entries.filter((entry) => entry.level === minLevel);
|
|
45
73
|
const pool = top.length >= 20 ? top : entries;
|
|
74
|
+
if (pool.length <= MAX_OUTLINE_ENTRIES) return pool;
|
|
75
|
+
// The step is above 1 here, so each sampled index is greater than the one before it.
|
|
46
76
|
const step = pool.length / MAX_OUTLINE_ENTRIES;
|
|
47
|
-
return Array.from({ length:
|
|
77
|
+
return Array.from({ length: MAX_OUTLINE_ENTRIES }, (_, index) => pool[Math.floor(index * step)]!);
|
|
48
78
|
}
|
|
49
79
|
|
|
50
80
|
/** Replaces the variable parts of a log message so repeated failures group together. */
|
|
51
81
|
export function logTemplate(line: string): string {
|
|
52
|
-
|
|
82
|
+
const template = line
|
|
53
83
|
.replace(TIMESTAMP, "")
|
|
54
84
|
.replace(/^\W*\d{2}:\d{2}:\d{2}(?:[.,]\d+)?/, "")
|
|
55
85
|
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<id>")
|
|
@@ -58,40 +88,61 @@ export function logTemplate(line: string): string {
|
|
|
58
88
|
.replace(/"[^"]{0,200}"|'[^']{0,200}'/g, "<s>")
|
|
59
89
|
.replace(/\d+(?:\.\d+)?/g, "<n>")
|
|
60
90
|
.replace(/\s+/g, " ")
|
|
61
|
-
.trim()
|
|
62
|
-
|
|
91
|
+
.trim();
|
|
92
|
+
return sliceWhole(template, 180);
|
|
63
93
|
}
|
|
64
94
|
|
|
65
95
|
export function buildLogProfile(lines: string[]): LogProfile {
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
96
|
+
const profile = new LogProfiler();
|
|
97
|
+
for (let index = 0; index < lines.length; index++) profile.add(lines[index] ?? "", index);
|
|
98
|
+
return profile.result();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
|
|
102
|
+
export async function buildLogProfileInSlices(lines: string[], slicer: TimeSlicer): Promise<LogProfile> {
|
|
103
|
+
const profile = new LogProfiler();
|
|
70
104
|
for (let index = 0; index < lines.length; index++) {
|
|
71
|
-
|
|
105
|
+
profile.add(lines[index] ?? "", index);
|
|
106
|
+
if ((index & 4095) === 4095) await slicer.maybePause();
|
|
107
|
+
}
|
|
108
|
+
return profile.result();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Builds a log profile one line at a time. */
|
|
112
|
+
class LogProfiler {
|
|
113
|
+
private readonly levels: Record<string, number> = {};
|
|
114
|
+
private readonly templates = new Map<string, LogIssue>();
|
|
115
|
+
private firstTimestamp: string | undefined;
|
|
116
|
+
private lastTimestamp: string | undefined;
|
|
117
|
+
|
|
118
|
+
/** Adds line `index` (0-based). */
|
|
119
|
+
add(line: string, index: number): void {
|
|
72
120
|
const stamp = TIMESTAMP.exec(line)?.[0];
|
|
73
121
|
if (stamp) {
|
|
74
|
-
firstTimestamp ??= stamp;
|
|
75
|
-
lastTimestamp = stamp;
|
|
122
|
+
this.firstTimestamp ??= stamp;
|
|
123
|
+
this.lastTimestamp = stamp;
|
|
76
124
|
}
|
|
77
125
|
const raw = LEVEL.exec(line)?.[1];
|
|
78
|
-
if (!raw)
|
|
126
|
+
if (!raw) return;
|
|
79
127
|
const level = LEVEL_NAMES[raw] ?? raw;
|
|
80
|
-
levels[level] = (levels[level] ?? 0) + 1;
|
|
81
|
-
if (level !== "ERROR" && level !== "FATAL" && level !== "WARN")
|
|
128
|
+
this.levels[level] = (this.levels[level] ?? 0) + 1;
|
|
129
|
+
if (level !== "ERROR" && level !== "FATAL" && level !== "WARN") return;
|
|
82
130
|
const template = logTemplate(line);
|
|
83
|
-
const existing = templates.get(template);
|
|
131
|
+
const existing = this.templates.get(template);
|
|
84
132
|
if (existing) existing.count++;
|
|
85
|
-
else if (templates.size < MAX_TEMPLATES) templates.set(template, { template, level, count: 1, firstLine: index + 1 });
|
|
133
|
+
else if (this.templates.size < MAX_TEMPLATES) this.templates.set(template, { template, level, count: 1, firstLine: index + 1 });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
result(): LogProfile {
|
|
137
|
+
const severity = (issue: LogIssue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
|
|
138
|
+
const topIssues = [...this.templates.values()]
|
|
139
|
+
.sort((left, right) => severity(right) - severity(left) || right.count - left.count)
|
|
140
|
+
.slice(0, 15);
|
|
141
|
+
return {
|
|
142
|
+
levels: this.levels,
|
|
143
|
+
...(this.firstTimestamp ? { firstTimestamp: this.firstTimestamp } : {}),
|
|
144
|
+
...(this.lastTimestamp ? { lastTimestamp: this.lastTimestamp } : {}),
|
|
145
|
+
topIssues,
|
|
146
|
+
};
|
|
86
147
|
}
|
|
87
|
-
const severity = (issue: LogIssue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
|
|
88
|
-
const topIssues = [...templates.values()]
|
|
89
|
-
.sort((left, right) => severity(right) - severity(left) || right.count - left.count)
|
|
90
|
-
.slice(0, 15);
|
|
91
|
-
return {
|
|
92
|
-
levels,
|
|
93
|
-
...(firstTimestamp ? { firstTimestamp } : {}),
|
|
94
|
-
...(lastTimestamp ? { lastTimestamp } : {}),
|
|
95
|
-
topIssues,
|
|
96
|
-
};
|
|
97
148
|
}
|
package/src/anthropic/adapter.ts
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
// Claude (the Messages API) as a model of `askWithFiles`. No SDK, like the other adapters: the
|
|
2
2
|
// caller gives a key or a token, and may give the URL of a gateway that speaks the same API.
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { base64, idleWatch, noteCutReply, notJsonMessage, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, type HeaderSource, type IdleWatch, type SecretSource } from "../http.js";
|
|
5
|
+
import { laterResult, ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
|
|
5
6
|
import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
|
|
6
|
-
import { retryAfterMs } from "../retry.js";
|
|
7
|
-
import { parseSseJson } from "../sse.js";
|
|
7
|
+
import { noteNoRetry, retryAfterMs } from "../retry.js";
|
|
8
|
+
import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
|
|
9
|
+
import { estimateTokens, sliceWhole } from "../text.js";
|
|
8
10
|
import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
|
|
9
11
|
|
|
10
12
|
/** The API answered with an HTTP error, or could not be reached (`status` 0). `type` is the API's own word: "rate_limit_error". */
|
|
11
13
|
export class AnthropicRequestError extends ModelRequestError {
|
|
12
14
|
readonly type?: string;
|
|
13
|
-
constructor(message: string, status: number, options:
|
|
14
|
-
|
|
15
|
+
constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] & { type?: string } = {}) {
|
|
16
|
+
// The API's own word tells the kind: "request_too_large" is a request larger than Claude takes.
|
|
17
|
+
super(message, status, { ...options, ...(options.type ? { code: options.type } : {}) });
|
|
15
18
|
this.name = "AnthropicRequestError";
|
|
16
19
|
if (options.type) this.type = options.type;
|
|
17
20
|
}
|
|
@@ -93,6 +96,19 @@ export type AnthropicOptions = {
|
|
|
93
96
|
tokenScale?: number | undefined;
|
|
94
97
|
/** Milliseconds a part read may take. Defaults to 180,000. */
|
|
95
98
|
timeoutMs?: number | undefined;
|
|
99
|
+
/**
|
|
100
|
+
* The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
|
|
101
|
+
* a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
|
|
102
|
+
* whole at the end. A request that gets nothing for that long is aborted and sent again, once.
|
|
103
|
+
* Defaults to 600,000. 0 waits without end.
|
|
104
|
+
*/
|
|
105
|
+
firstByteTimeoutMs?: number | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
|
|
108
|
+
* arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
|
|
109
|
+
* again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
|
|
110
|
+
*/
|
|
111
|
+
idleTimeoutMs?: number | undefined;
|
|
96
112
|
/** Names the model in usage totals. Defaults to `model`. */
|
|
97
113
|
id?: string | undefined;
|
|
98
114
|
fetch?: typeof fetch | undefined;
|
|
@@ -101,16 +117,32 @@ export type AnthropicOptions = {
|
|
|
101
117
|
type Json = Record<string, any>;
|
|
102
118
|
type Block = Record<string, any>;
|
|
103
119
|
|
|
104
|
-
|
|
120
|
+
/**
|
|
121
|
+
* The status of an error event in a stream that began with 200, from its type. A type it does not
|
|
122
|
+
* know is the server's failure, 500, as an OpenAI-compatible stream's is.
|
|
123
|
+
*/
|
|
124
|
+
const STATUS_OF_TYPE: Record<string, number> = {
|
|
125
|
+
overloaded_error: 529, rate_limit_error: 429, api_error: 500, timeout_error: 408,
|
|
126
|
+
invalid_request_error: 400, authentication_error: 401, billing_error: 402, permission_error: 403, not_found_error: 404, request_too_large: 413,
|
|
127
|
+
};
|
|
105
128
|
|
|
106
129
|
/** Blocks of a model that declined part-way must not go back: only what came after the last switch to another model does. */
|
|
107
130
|
const INTERNAL_BEFORE_FALLBACK = new Set(["thinking", "redacted_thinking", "tool_use", "server_tool_use"]);
|
|
108
131
|
|
|
132
|
+
const isThinking = (block: Block | undefined) => block?.type === "thinking" || block?.type === "redacted_thinking";
|
|
133
|
+
|
|
109
134
|
/** The content of a reply as it goes back in the next request. */
|
|
110
135
|
function echoable(content: Block[]): Block[] {
|
|
111
136
|
const boundary = content.map((block) => block?.type).lastIndexOf("fallback");
|
|
112
|
-
|
|
113
|
-
|
|
137
|
+
const kept = boundary < 0 ? content : content.filter((block, index) => index >= boundary || !INTERNAL_BEFORE_FALLBACK.has(block?.type));
|
|
138
|
+
// A text block that a stream opened and closed with nothing in it is refused when it is sent back
|
|
139
|
+
// ("text content blocks must be non-empty"). One before a thinking block is left: the thinking
|
|
140
|
+
// is checked against what comes before it in its turn.
|
|
141
|
+
let lastThinking = -1;
|
|
142
|
+
kept.forEach((block, index) => {
|
|
143
|
+
if (isThinking(block)) lastThinking = index;
|
|
144
|
+
});
|
|
145
|
+
return kept.filter((block, index) => !(index > lastThinking && block?.type === "text" && !block.text && !(Array.isArray(block.citations) && block.citations.length > 0)));
|
|
114
146
|
}
|
|
115
147
|
|
|
116
148
|
function usageOf(usage: Json | undefined): GenerateUsage {
|
|
@@ -132,10 +164,16 @@ async function failure(response: Response): Promise<AnthropicRequestError> {
|
|
|
132
164
|
const data = await response.json().catch(() => null) as Json | null;
|
|
133
165
|
const wait = retryAfterMs(response.headers, data);
|
|
134
166
|
const type = typeof data?.error?.type === "string" ? data.error.type as string : undefined;
|
|
135
|
-
|
|
167
|
+
// The spending cap of the organization comes as a rate limit (HTTP 429): no wait mends it.
|
|
168
|
+
const spent = data?.error?.details?.error_code === "enforced_spend_limit_reached";
|
|
169
|
+
const error = new AnthropicRequestError(typeof data?.error?.message === "string" && data.error.message ? data.error.message : `Claude returned HTTP ${response.status}.`, response.status, {
|
|
136
170
|
...(wait === undefined ? {} : { retryAfterMs: wait }),
|
|
137
171
|
...(type ? { type } : {}),
|
|
172
|
+
...(spent ? { kind: "quota" as const } : {}),
|
|
138
173
|
});
|
|
174
|
+
// The API says when another try cannot help, as its own SDKs read it.
|
|
175
|
+
if (response.headers.get("x-should-retry") === "false") noteNoRetry(error);
|
|
176
|
+
return error;
|
|
139
177
|
}
|
|
140
178
|
|
|
141
179
|
const toolResultOf = (id: string, result: ToolResult, documents: Block[]): Block => ({
|
|
@@ -146,9 +184,33 @@ const toolResultOf = (id: string, result: ToolResult, documents: Block[]): Block
|
|
|
146
184
|
...(typeof result.error === "string" ? { is_error: true } : {}),
|
|
147
185
|
});
|
|
148
186
|
|
|
149
|
-
/**
|
|
150
|
-
|
|
151
|
-
|
|
187
|
+
/**
|
|
188
|
+
* The IDs of the calls of a round, as the API takes them: of the characters `[A-Za-z0-9_-]` only,
|
|
189
|
+
* and each once in a request. A call that came without one, or from another provider (Kimi's
|
|
190
|
+
* "functions.search:0"), or that has the ID of a call of an earlier round (two questions whose
|
|
191
|
+
* stored rounds were numbered alike), is given one that fits. `used` holds the IDs taken so far
|
|
192
|
+
* in the request. The IDs of Claude's own turns are its own, and are kept as they are.
|
|
193
|
+
*/
|
|
194
|
+
function callIds(round: ModelToolRound, number: number, used: Set<string>): string[] {
|
|
195
|
+
if (round.raw !== undefined) {
|
|
196
|
+
for (const block of Array.isArray(round.raw) ? round.raw as Block[] : []) {
|
|
197
|
+
if (block?.type === "tool_use" && typeof block.id === "string") used.add(block.id);
|
|
198
|
+
}
|
|
199
|
+
return round.calls.map((call, index) => call.id ?? `toolu_${number}_${index + 1}`);
|
|
200
|
+
}
|
|
201
|
+
return round.calls.map((call, index) => {
|
|
202
|
+
const base = (call.id ?? "").replace(/[^A-Za-z0-9_-]/g, "_") || `toolu_${number}_${index + 1}`;
|
|
203
|
+
let id = base;
|
|
204
|
+
for (let again = 2; used.has(id); again++) id = `${base}_${again}`;
|
|
205
|
+
used.add(id);
|
|
206
|
+
return id;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The two messages of one tool round, with the IDs `callIds` gave its calls. */
|
|
211
|
+
function roundMessages(round: ModelToolRound, ids: string[], files: "inside" | "beside" | "none"): AnthropicMessage[] {
|
|
212
|
+
const byCall = new Map(round.calls.map((call, index) => [call, ids[index]!]));
|
|
213
|
+
const idOf = (call: ToolCall, index: number) => byCall.get(call) ?? ids[index] ?? call.id ?? `toolu_${index + 1}`;
|
|
152
214
|
// Its own turn goes back exactly as it came: Claude checks its thinking blocks against the conversation they were written in.
|
|
153
215
|
const asked: AnthropicMessage = {
|
|
154
216
|
role: "assistant",
|
|
@@ -225,12 +287,25 @@ export function fromAnthropicMessages(history: AnthropicMessage[]): ChatMessage[
|
|
|
225
287
|
* an application that keeps its history in that form: put them between the question and its answer.
|
|
226
288
|
*/
|
|
227
289
|
export function anthropicToolTurns(turns: ToolTurn[]): AnthropicMessage[] {
|
|
290
|
+
const used = new Set<string>();
|
|
228
291
|
return turns.flatMap((turn, index) => {
|
|
229
|
-
|
|
230
|
-
|
|
292
|
+
// A call that came without an ID is given one that no round of another question has: these
|
|
293
|
+
// messages are kept, and sent again next to those of later questions.
|
|
294
|
+
const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `toolu_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
|
|
295
|
+
const round: ModelToolRound = { role: "tools", calls: answers.map((answer) => answer.call), answers };
|
|
296
|
+
return roundMessages(round, callIds(round, index + 1, used), "none");
|
|
231
297
|
});
|
|
232
298
|
}
|
|
233
299
|
|
|
300
|
+
/**
|
|
301
|
+
* True when `body` asks Claude to clear old tool results on its side (context editing with
|
|
302
|
+
* `clear_tool_uses`), or to compact the conversation: a result shown earlier may then be gone.
|
|
303
|
+
*/
|
|
304
|
+
function clearsToolResults(body: Record<string, unknown> | undefined): boolean {
|
|
305
|
+
const edits = (body?.context_management as { edits?: unknown } | null | undefined)?.edits;
|
|
306
|
+
return Array.isArray(edits) && edits.some((edit) => /^(?:clear_tool_uses|compact)/.test(String((edit as { type?: unknown } | null)?.type ?? "")));
|
|
307
|
+
}
|
|
308
|
+
|
|
234
309
|
/** A Claude model for `askWithFiles`. */
|
|
235
310
|
export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
236
311
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -247,6 +322,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
247
322
|
const streaming = options.stream !== false;
|
|
248
323
|
const eager = options.eagerInputStreaming ?? firstParty;
|
|
249
324
|
const cache = options.cache === false ? undefined : { type: "ephemeral", ...(options.cache === "1h" ? { ttl: "1h" } : {}) };
|
|
325
|
+
const scale = options.tokenScale ?? 1.35;
|
|
250
326
|
const betas = [...new Set([...(options.betas ?? []), ...(options.fallbacks ? [FALLBACK_BETA] : [])])];
|
|
251
327
|
|
|
252
328
|
const headersNow = async (): Promise<Record<string, string>> => {
|
|
@@ -261,18 +337,20 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
261
337
|
};
|
|
262
338
|
};
|
|
263
339
|
|
|
264
|
-
const built = new WeakMap<ModelToolRound, {
|
|
340
|
+
const built = new WeakMap<ModelToolRound, { key: string; messages: AnthropicMessage[] }>();
|
|
265
341
|
const toMessages = (messages: ModelMessage[]): AnthropicMessage[] => {
|
|
266
342
|
let rounds = 0;
|
|
343
|
+
const used = new Set<string>();
|
|
267
344
|
return joined(messages.flatMap((message): AnthropicMessage[] => {
|
|
268
345
|
if (message.role !== "tools") {
|
|
269
346
|
// The API refuses an empty text block.
|
|
270
347
|
return [{ role: message.role, content: message.parts.flatMap((part): Block[] => (part.native !== undefined ? [part.native as Block] : part.text ? [{ type: "text", text: part.text }] : [])) }];
|
|
271
348
|
}
|
|
272
|
-
const
|
|
349
|
+
const ids = callIds(message, ++rounds, used);
|
|
350
|
+
const key = ids.join(" ");
|
|
273
351
|
let known = built.get(message);
|
|
274
|
-
if (!known || known.
|
|
275
|
-
known = {
|
|
352
|
+
if (!known || known.key !== key) {
|
|
353
|
+
known = { key, messages: roundMessages(message, ids, files) };
|
|
276
354
|
built.set(message, known);
|
|
277
355
|
}
|
|
278
356
|
return known.messages;
|
|
@@ -298,13 +376,13 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
298
376
|
...options.body,
|
|
299
377
|
});
|
|
300
378
|
|
|
301
|
-
const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
|
|
379
|
+
const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => AnthropicRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
|
|
302
380
|
let response: Response;
|
|
303
381
|
try {
|
|
304
|
-
response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
382
|
+
response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
305
383
|
} catch (error) {
|
|
306
384
|
if (stopped()) throw error;
|
|
307
|
-
throw
|
|
385
|
+
throw lost(error);
|
|
308
386
|
}
|
|
309
387
|
if (!response.ok) throw await failure(response);
|
|
310
388
|
return response;
|
|
@@ -327,11 +405,13 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
327
405
|
}];
|
|
328
406
|
});
|
|
329
407
|
const category = typeof stopDetails?.category === "string" ? `: ${stopDetails.category as string}` : "";
|
|
408
|
+
const finish = finishOfClaude(stopReason);
|
|
330
409
|
return {
|
|
331
410
|
text,
|
|
332
411
|
calls,
|
|
333
412
|
raw: echoable(content),
|
|
334
413
|
...(typeof stopReason === "string" ? { finishReason: stopReason } : {}),
|
|
414
|
+
...(finish ? { finish } : {}),
|
|
335
415
|
...(refused ? { blockReason: `refusal${category}` } : {}),
|
|
336
416
|
...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
|
|
337
417
|
};
|
|
@@ -347,14 +427,21 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
347
427
|
messages: [{ role: "user", content: prompt }],
|
|
348
428
|
...options.analysisBody?.(limit),
|
|
349
429
|
}, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
|
|
350
|
-
const data = await response.
|
|
351
|
-
|
|
430
|
+
const data = await readJson<Json>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error));
|
|
431
|
+
const used = usageOf(data.usage as Json | undefined);
|
|
432
|
+
onUsage?.(used);
|
|
352
433
|
const content: Block[] = Array.isArray(data.content) ? data.content : [];
|
|
434
|
+
const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
|
|
353
435
|
return {
|
|
354
|
-
text
|
|
436
|
+
text,
|
|
355
437
|
cutOff: data.stop_reason === "max_tokens",
|
|
438
|
+
// Claude stopped before the end, for its safety rules or because its window was full: what
|
|
439
|
+
// it wrote is not all there is. (Not `cutOff`: a larger output limit would not help.)
|
|
440
|
+
stopped: data.stop_reason === "refusal" || data.stop_reason === "model_context_window_exceeded",
|
|
356
441
|
...(typeof data.stop_reason === "string" ? { reason: data.stop_reason } : {}),
|
|
357
|
-
thoughts:
|
|
442
|
+
// Claude does not count its thoughts apart: they are what it wrote besides its text, when it
|
|
443
|
+
// thought. A reply that thought most of its limit away is then asked for with a larger one.
|
|
444
|
+
thoughts: content.some(isThinking) ? Math.max(0, (used.outputTokens ?? 0) - Math.ceil(estimateTokens(text) * scale)) : 0,
|
|
358
445
|
};
|
|
359
446
|
};
|
|
360
447
|
return completeWithinLimit(`${url}|${options.model}`, maxOutputTokens, send, { signal, onTruncated });
|
|
@@ -367,21 +454,50 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
367
454
|
maxRequestBytes: options.maxRequestBytes ?? 32_000_000,
|
|
368
455
|
toolFiles: files,
|
|
369
456
|
pageTokens: options.pageTokens ?? 3_500,
|
|
370
|
-
tokenScale:
|
|
457
|
+
tokenScale: scale,
|
|
371
458
|
outputTokens: maxTokens,
|
|
372
459
|
// Claude checks its thinking blocks against the conversation they were written in: an
|
|
373
460
|
// earlier turn that is rewritten makes the later ones invalid.
|
|
374
461
|
appendOnly: true,
|
|
462
|
+
// With context editing, Claude may no longer have a result shown earlier: none is pointed to.
|
|
463
|
+
...(clearsToolResults(options.body) ? { clearsToolResults: true } : {}),
|
|
375
464
|
},
|
|
376
465
|
requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, streaming))),
|
|
377
466
|
generateText,
|
|
378
467
|
|
|
379
468
|
async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
|
|
380
|
-
|
|
469
|
+
// A key or token is fetched before the watch starts: the time that takes is not the model's.
|
|
470
|
+
const headers = await headersNow();
|
|
471
|
+
const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
|
|
472
|
+
// A request the watch aborted got nothing back for the whole wait: that is no failed connection.
|
|
473
|
+
const lost = (error: unknown) => (watch.expired ? new AnthropicRequestError(`Claude sent nothing for ${Math.round(watch.waitedMs / 1_000)} s.`, 0, { kind: "timeout" }) : unreachable(error));
|
|
474
|
+
try {
|
|
475
|
+
// The headers are no piece of the reply: a server may send them at once and then think.
|
|
476
|
+
const response = await post(bodyOf(request, streaming), watch.signal, () => Boolean(hooks.signal?.aborted), lost, headers);
|
|
477
|
+
return await readReply(response, hooks, watch, lost);
|
|
478
|
+
} finally {
|
|
479
|
+
watch.stop();
|
|
480
|
+
}
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
/** The reply of a request that was answered: streamed, or in one piece. */
|
|
485
|
+
async function readReply(answer: Response, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => AnthropicRequestError): Promise<ModelReply> {
|
|
486
|
+
{
|
|
381
487
|
const problems = new Map<number, string>();
|
|
382
|
-
|
|
488
|
+
let response = answer;
|
|
489
|
+
let events = false;
|
|
490
|
+
if (streaming && answer.body) {
|
|
491
|
+
try {
|
|
492
|
+
({ events, response } = await streamedReply(answer, watch));
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (hooks.signal?.aborted) throw error;
|
|
495
|
+
throw noteCutReply(lost(error));
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (!(events && response.body)) {
|
|
383
499
|
// In one piece: streaming is off, or the gateway answered without it.
|
|
384
|
-
const data = await response.
|
|
500
|
+
const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, (error) => notJson(answer, error));
|
|
385
501
|
const content: Block[] = Array.isArray(data.content) ? data.content : [];
|
|
386
502
|
const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
|
|
387
503
|
if (text) hooks.onText?.(text);
|
|
@@ -389,17 +505,23 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
389
505
|
}
|
|
390
506
|
const content: Block[] = [];
|
|
391
507
|
const inputs = new Map<number, string>();
|
|
508
|
+
/** Blocks whose stop event came: a call whose block was never closed did not arrive whole. */
|
|
509
|
+
const closed = new Set<number>();
|
|
392
510
|
let text = "";
|
|
393
511
|
let stopReason: unknown;
|
|
394
512
|
let stopDetails: Json | undefined;
|
|
395
513
|
let usage: Json | undefined;
|
|
514
|
+
// `message_stop` ends the reply: a gateway that leaves the connection open after it is not waited for.
|
|
515
|
+
const end = replyEnd(watch);
|
|
396
516
|
try {
|
|
397
|
-
for await (const event of parseSseJson<Json>(response.body)) {
|
|
517
|
+
for await (const event of parseSseJson<Json>(response.body, { onData: watch.pulse, signal: end.signal })) {
|
|
398
518
|
if (event.type === "error") {
|
|
399
519
|
const type = typeof event.error?.type === "string" ? event.error.type as string : undefined;
|
|
400
|
-
throw new AnthropicRequestError(String(event.error?.message ?? "Claude reported an error."), (type && STATUS_OF_TYPE[type]) ||
|
|
520
|
+
throw new AnthropicRequestError(String(event.error?.message ?? "Claude reported an error."), (type && STATUS_OF_TYPE[type]) || 500, type ? { type } : {});
|
|
401
521
|
}
|
|
402
|
-
if (event.type === "
|
|
522
|
+
if (event.type === "message_stop") {
|
|
523
|
+
end.reached();
|
|
524
|
+
} else if (event.type === "message_start") {
|
|
403
525
|
usage = { ...event.message?.usage };
|
|
404
526
|
} else if (event.type === "content_block_start" && typeof event.index === "number") {
|
|
405
527
|
content[event.index] = { ...event.content_block };
|
|
@@ -420,6 +542,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
420
542
|
(block.citations ??= []).push(delta.citation);
|
|
421
543
|
}
|
|
422
544
|
} else if (event.type === "content_block_stop" && typeof event.index === "number") {
|
|
545
|
+
closed.add(event.index);
|
|
423
546
|
const written = inputs.get(event.index);
|
|
424
547
|
const block = content[event.index];
|
|
425
548
|
if (block?.type === "tool_use" && written !== undefined && written.trim()) {
|
|
@@ -430,7 +553,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
430
553
|
block.input = input;
|
|
431
554
|
} catch {
|
|
432
555
|
block.input = {};
|
|
433
|
-
problems.set(event.index, `The arguments of this call were not valid JSON, and it was not run: ${written
|
|
556
|
+
problems.set(event.index, `The arguments of this call were not valid JSON, and it was not run: ${sliceWhole(written, 300)}. Send the call again.`);
|
|
434
557
|
}
|
|
435
558
|
}
|
|
436
559
|
} else if (event.type === "message_delta") {
|
|
@@ -440,15 +563,49 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
440
563
|
}
|
|
441
564
|
}
|
|
442
565
|
} catch (error) {
|
|
443
|
-
|
|
444
|
-
//
|
|
445
|
-
|
|
566
|
+
// The reply ended with `message_stop`, and the connection then stayed open, or broke rather
|
|
567
|
+
// than end: what came before it is whole.
|
|
568
|
+
const whole = end.left(error) || (end.whole && !hooks.signal?.aborted && !(error instanceof AnthropicRequestError));
|
|
569
|
+
if (!whole) {
|
|
570
|
+
if (hooks.signal?.aborted || error instanceof AnthropicRequestError) throw error;
|
|
571
|
+
// An event too long to read would come again: it is not sent again, like a page in the reply's place.
|
|
572
|
+
if (error instanceof SseEventTooLongError) throw new AnthropicRequestError(eventTooLongMessage("Claude's", error), answer.status, { kind: "invalid", cause: error });
|
|
573
|
+
// The connection went while the answer was on its way, or nothing came for the whole wait.
|
|
574
|
+
throw noteCutReply(lost(error));
|
|
575
|
+
}
|
|
576
|
+
} finally {
|
|
577
|
+
end.dispose();
|
|
446
578
|
}
|
|
579
|
+
// Every reply ends with the reason it stopped. A stream that closed without one was cut short
|
|
580
|
+
// (a gateway that ended it as if it were whole): its text is not the answer, and it is sent
|
|
581
|
+
// again like a connection that failed, when none of it was shown.
|
|
582
|
+
if (stopReason === undefined) throw noteCutReply(new AnthropicRequestError("Claude's reply ended before it was complete.", 0));
|
|
583
|
+
content.forEach((block, index) => {
|
|
584
|
+
if ((block?.type === "tool_use" || block?.type === "server_tool_use") && !closed.has(index)) problems.set(index, "This call did not arrive whole, and was not run. Send it again.");
|
|
585
|
+
});
|
|
447
586
|
const blocks = content.filter(Boolean);
|
|
448
587
|
// The problems were noted by the place of the block in the stream: the same place, with no gaps, in what is kept.
|
|
449
588
|
const placed = new Map<number, string>();
|
|
450
589
|
for (const [index, problem] of problems) placed.set(blocks.indexOf(content[index]!), problem);
|
|
451
590
|
return replyOf(blocks, stopReason, stopDetails, usage, placed, text);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** A body that came with a status of success but is no JSON (a gateway's page): it is not sent again. */
|
|
596
|
+
function notJson(response: Response, error: unknown): AnthropicRequestError {
|
|
597
|
+
return new AnthropicRequestError(notJsonMessage("Claude's", response), response.status, { kind: "invalid", cause: error });
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** A request that got no answer: the reason, without the stack of the HTTP client. */
|
|
601
|
+
function unreachable(error: unknown): AnthropicRequestError {
|
|
602
|
+
return new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** `stop_reason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
|
|
606
|
+
function finishOfClaude(reason: unknown): ModelReply["finish"] {
|
|
607
|
+
if (reason === "end_turn" || reason === "tool_use" || reason === "stop_sequence") return "complete";
|
|
608
|
+
if (reason === "max_tokens" || reason === "model_context_window_exceeded") return "cut";
|
|
609
|
+
if (reason === "refusal") return "filtered";
|
|
610
|
+
return undefined;
|
|
454
611
|
}
|