Fit an embedding batch to the provider's own cap
Alibaba's Model Studio refuses a batch over 20 whole ("Value error, batch
size is invalid, it should not be larger than 20.: input.contents"), and
AppData.EmbeddingBatchSize is 32, so every knowledgebase document there
fell back to word search.
The adapter now reads the cap from the refusal, retries nothing-stored
batch at it, and remembers it per provider and model for the process, so
later documents start at a size that fits.
This commit is contained in:
@@ -230,7 +230,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; the newest messages are never trimmed; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process.
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
|
||||
@@ -177,4 +177,67 @@ describe("embed asks for input_type when the model needs it", () => {
|
||||
).rejects.toThrow("model not found");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed fits a provider's own batch cap", () => {
|
||||
/**
|
||||
* Alibaba's Model Studio compatible API: more than 20 texts in one batch
|
||||
* is refused whole, with the limit in the message.
|
||||
*/
|
||||
const alibaba: HarnessCandidate = {
|
||||
key: "20:qwen-embed",
|
||||
provider: {
|
||||
kind: "custom",
|
||||
base_url: "https://ws-test.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
|
||||
name: "Alibaba Cloud",
|
||||
},
|
||||
model: {
|
||||
slug: "qwen3.7-embedding",
|
||||
input_modalities: ["text"],
|
||||
output_modalities: ["text"],
|
||||
supports_tools: false,
|
||||
},
|
||||
source: "pinned",
|
||||
};
|
||||
|
||||
const capAtTwenty = (body: any) => {
|
||||
if (body.input.length > 20)
|
||||
throw new HarnessError({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
status: 400,
|
||||
});
|
||||
|
||||
return {
|
||||
data: body.input.map((_: string, index: number) => ({ index, embedding: [1, index] })),
|
||||
};
|
||||
};
|
||||
|
||||
test("the refused batch is retried at the size named, and that size is kept", async () => {
|
||||
answer = capAtTwenty;
|
||||
|
||||
const many = Array.from({ length: 45 }, (_, i) => `chunk ${i}`);
|
||||
const first = await embed({ candidate: alibaba, input: many, purpose: "passage", signal });
|
||||
|
||||
expect(first.vectors).toHaveLength(45);
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5]);
|
||||
expect(first.vectors[44]).toEqual([1, 4]);
|
||||
|
||||
await embed({ candidate: alibaba, input: ["a", "b", "c"], purpose: "passage", signal });
|
||||
expect(sent.map((body) => body.input.length)).toEqual([32, 20, 20, 5, 3]);
|
||||
});
|
||||
|
||||
test("one text refused for its size is a failure, not a retry loop", async () => {
|
||||
answer = () => {
|
||||
throw new HarnessError({
|
||||
message: "Alibaba Cloud: Value error, batch size is invalid, it should not be larger than 0.",
|
||||
status: 400,
|
||||
});
|
||||
};
|
||||
|
||||
await expect(
|
||||
embed({ candidate: alibaba, input: ["a document's text"], purpose: "passage", signal }),
|
||||
).rejects.toThrow("batch size is invalid");
|
||||
expect(sent).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@ import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAdapter, HarnessCandidate } from "../../types";
|
||||
import grabProviderPreset from "../grab-provider-preset";
|
||||
import providerRequest from "./provider-request";
|
||||
import sendEmbeddingsBatch from "./send-embeddings-batch";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
/**
|
||||
* Providers that want `input_type` on every batch, by provider and model:
|
||||
@@ -13,6 +14,14 @@ import providerRequest from "./provider-request";
|
||||
*/
|
||||
const wantsInputType = new Set<string>();
|
||||
|
||||
/**
|
||||
* The largest batch a provider and model already refused a bigger one over.
|
||||
* Alibaba's Model Studio caps a batch at 20 and refuses the whole request, so
|
||||
* the size it named is remembered for the process: every later document goes
|
||||
* straight to a batch that fits instead of paying for the refusal again.
|
||||
*/
|
||||
const batchLimits = new Map<string, number>();
|
||||
|
||||
const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
`${provider.base_url}|${model.slug}`;
|
||||
|
||||
@@ -22,7 +31,7 @@ const inputTypeKey = ({ provider, model }: HarnessCandidate) =>
|
||||
* request the provider may refuse.
|
||||
*/
|
||||
const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signal }) => {
|
||||
const { provider, model } = candidate;
|
||||
const { provider } = candidate;
|
||||
const preset = grabProviderPreset({ kind: provider.kind });
|
||||
const key = inputTypeKey(candidate);
|
||||
const vectors: number[][] = [];
|
||||
@@ -33,49 +42,46 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
let prompt_tokens = 0;
|
||||
|
||||
/**
|
||||
* Every OpenAI-compatible API puts embeddings at `/embeddings`.
|
||||
* The batch size in use: the install's, or the smaller one this provider
|
||||
* and model already made clear it wants.
|
||||
*/
|
||||
const path = "/embeddings";
|
||||
let limit = batchLimits.get(key) || AppData.EmbeddingBatchSize;
|
||||
|
||||
for (let start = 0; start < input.length; start += AppData.EmbeddingBatchSize) {
|
||||
for (let start = 0; start < input.length; ) {
|
||||
const batch = input
|
||||
.slice(start, start + AppData.EmbeddingBatchSize)
|
||||
.slice(start, start + limit)
|
||||
.map((text) => text.slice(0, AppData.EmbeddingMaxInputChars));
|
||||
|
||||
const body = { model: model.slug, input: batch };
|
||||
let res: Response;
|
||||
|
||||
try {
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: wantsInputType.has(key) ? { ...body, input_type: purpose } : body,
|
||||
const sent = await sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
with_input_type: wantsInputType.has(key),
|
||||
});
|
||||
|
||||
if (sent.asked_input_type) wantsInputType.add(key);
|
||||
|
||||
res = sent.res;
|
||||
} catch (error) {
|
||||
/**
|
||||
* The provider says the model embeds a passage and a query
|
||||
* differently and wants to be told which. Ask again with it,
|
||||
* then remember: only the first batch per provider and model
|
||||
* pays for finding out. Any other refusal is the caller's to
|
||||
* classify.
|
||||
* A provider may cap a batch below the install's size (Alibaba's
|
||||
* Model Studio: "batch size is invalid, it should not be larger
|
||||
* than 20"). Nothing of this batch was stored, so retry it whole
|
||||
* at the smaller size, and keep that size for the rest of the
|
||||
* run. Only a size refusal is retried; anything else is the
|
||||
* caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
const smaller = smallerBatchLimit({ error, size: batch.length });
|
||||
|
||||
res = await providerRequest({
|
||||
provider,
|
||||
path,
|
||||
json: { ...body, input_type: purpose },
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
wantsInputType.add(key);
|
||||
if (smaller === null) throw error;
|
||||
|
||||
limit = smaller;
|
||||
batchLimits.set(key, smaller);
|
||||
continue;
|
||||
}
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
@@ -142,6 +148,8 @@ const embed: HarnessAdapter["embed"] = async ({ candidate, input, purpose, signa
|
||||
}
|
||||
vectors.push(vector);
|
||||
}
|
||||
|
||||
start += batch.length;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
type Params = {
|
||||
candidate: HarnessCandidate;
|
||||
batch: string[];
|
||||
purpose: "query" | "passage";
|
||||
signal: AbortSignal;
|
||||
/**
|
||||
* Ask with `input_type` from the first try (this provider already said
|
||||
* its model needs it).
|
||||
*/
|
||||
with_input_type: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One `/embeddings` request for a batch. A provider that says its model
|
||||
* embeds a passage and a query differently (NVIDIA's asymmetric ones) is
|
||||
* asked again with `input_type`, and the answer says it was, so the caller
|
||||
* can remember and skip the probe next time.
|
||||
*/
|
||||
export default async function sendEmbeddingsBatch({
|
||||
candidate,
|
||||
batch,
|
||||
purpose,
|
||||
signal,
|
||||
with_input_type,
|
||||
}: Params): Promise<{ res: Response; asked_input_type: boolean }> {
|
||||
const { provider, model } = candidate;
|
||||
const body = { model: model.slug, input: batch };
|
||||
const send = async (json: unknown) =>
|
||||
await providerRequest({
|
||||
provider,
|
||||
path: "/embeddings",
|
||||
json,
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
if (with_input_type) {
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
|
||||
try {
|
||||
return { res: await send(body), asked_input_type: false };
|
||||
} catch (error) {
|
||||
/**
|
||||
* Any other refusal is the caller's to classify.
|
||||
*/
|
||||
if (
|
||||
!(error instanceof HarnessError) ||
|
||||
error.status !== 400 ||
|
||||
!/input_type/i.test(error.message)
|
||||
)
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { res: await send({ ...body, input_type: purpose }), asked_input_type: true };
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import HarnessError from "../../harness-error";
|
||||
import smallerBatchLimit from "./smaller-batch-limit";
|
||||
|
||||
const refusal = ({ message, status = 400 }: { message: string; status?: number }) =>
|
||||
new HarnessError({ message, status });
|
||||
|
||||
describe("smallerBatchLimit", () => {
|
||||
test("takes the limit the provider stated", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({
|
||||
message:
|
||||
"Alibaba Cloud: <400> InternalError.Algo.InvalidParameter: Value error, batch size is invalid, it should not be larger than 20.: input.contents",
|
||||
}),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(20);
|
||||
});
|
||||
|
||||
test("halves the batch when no number is named", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "batch size is invalid" }), size: 32 }),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("understands the other wordings providers use", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "too many inputs in the batch" }), size: 10 }),
|
||||
).toBe(5);
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "the batch size is at most 4" }), size: 10 }),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test("one text alone is never shrunk", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 0" }),
|
||||
size: 1,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a stated limit that doesn't shrink the batch still halves it", () => {
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid, it should not be larger than 32" }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBe(16);
|
||||
});
|
||||
|
||||
test("any other refusal is somebody else's to classify", () => {
|
||||
expect(
|
||||
smallerBatchLimit({ error: refusal({ message: "model not found" }), size: 32 }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
smallerBatchLimit({
|
||||
error: refusal({ message: "batch size is invalid", status: 500 }),
|
||||
size: 32,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(smallerBatchLimit({ error: new Error("batch size is invalid"), size: 32 })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
|
||||
type Params = {
|
||||
error: unknown;
|
||||
/**
|
||||
* How many texts the refused request carried.
|
||||
*/
|
||||
size: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The batch size to try when a provider refused a batch for being too large.
|
||||
*
|
||||
* Alibaba's Model Studio compatible API answers "Value error, batch size is
|
||||
* invalid, it should not be larger than 20.: input.contents" and refuses the
|
||||
* whole request, so nothing is embedded until the batch fits. Returns the
|
||||
* limit the provider stated, else half the refused batch; null when the
|
||||
* refusal is something else, or when one text alone was still refused (that
|
||||
* is a real failure, not a size one).
|
||||
*/
|
||||
export default function smallerBatchLimit({ error, size }: Params): number | null {
|
||||
if (!(error instanceof HarnessError) || error.status !== 400) return null;
|
||||
|
||||
if (!/batch size/i.test(error.message) && !/too many inputs/i.test(error.message)) return null;
|
||||
|
||||
const stated = /(?:larger than|at most|maximum of|limit of)\s*(\d+)/i.exec(error.message);
|
||||
const stated_limit = stated ? Number(stated[1]) : 0;
|
||||
const next = stated_limit > 0 && stated_limit < size ? stated_limit : Math.floor(size / 2);
|
||||
|
||||
return next >= 1 && next < size ? next : null;
|
||||
}
|
||||
Reference in New Issue
Block a user