@cldmv/llm-translator 0.3.1 → 0.5.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/README.md +13 -7
- package/dist/api/convert/anthropic/messages/to/openai/chat/request.mjs +10 -10
- package/dist/api/convert/openai/chat/to/anthropic/messages/request.mjs +5 -3
- package/dist/api/convert/openai/chat/to/anthropic/messages/response.mjs +1 -1
- package/dist/api/convert/openai/chat/to/anthropic/messages/stream.mjs +1 -1
- package/dist/api/detect.mjs +1 -1
- package/dist/api/driver/vllm/request.mjs +1 -1
- package/dist/api/events/off.mjs +2 -0
- package/dist/api/events/on.mjs +2 -0
- package/dist/api/model/list.mjs +1 -1
- package/dist/api/request.mjs +2 -2
- package/dist/api/send.mjs +1 -1
- package/dist/api/server/plugin.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/lib/cli.mjs +7 -6
- package/dist/lib/config.mjs +1 -1
- package/dist/lib/effort.mjs +2 -0
- package/dist/lib/events.mjs +4 -0
- package/dist/lib/finish.mjs +1 -1
- package/dist/lib/route.mjs +1 -1
- package/dist/lib/routes.mjs +1 -1
- package/dist/lib/settings.mjs +1 -1
- package/dist/lib/usage.mjs +1 -1
- package/dist/lib/warn.mjs +1 -1
- package/package.json +4 -4
- package/types/src/api/convert/anthropic/messages/to/openai/chat/request.d.mts +2 -1
- package/types/src/api/convert/openai/chat/to/anthropic/messages/response.d.mts +1 -1
- package/types/src/api/driver/vllm/request.d.mts +3 -2
- package/types/src/api/events/off.d.mts +7 -0
- package/types/src/api/events/on.d.mts +8 -0
- package/types/src/api/request.d.mts +7 -2
- package/types/src/api/send.d.mts +1 -1
- package/types/src/api/server/plugin.d.mts +1 -1
- package/types/src/index.d.mts +33 -6
- package/types/src/lib/effort.d.mts +69 -0
- package/types/src/lib/events.d.mts +86 -0
- package/types/src/lib/finish.d.mts +21 -18
- package/types/src/lib/route.d.mts +11 -3
- package/types/src/lib/routes.d.mts +1 -1
- package/types/src/lib/settings.d.mts +22 -2
- package/types/src/lib/usage.d.mts +4 -2
- package/types/src/lib/warn.d.mts +12 -23
package/README.md
CHANGED
|
@@ -17,16 +17,18 @@ Use it as a library when you want the conversion without any I/O (`request`, `re
|
|
|
17
17
|
|
|
18
18
|
## ✨ What's New
|
|
19
19
|
|
|
20
|
-
### Latest: v0.
|
|
20
|
+
### Latest: v0.5.0 (November 2026)
|
|
21
21
|
|
|
22
|
-
- **
|
|
23
|
-
-
|
|
22
|
+
- **Events and opt-in logging** — everything the library logs is now an event: `translator.events.on(name, fn)`, `"*"` and an `onEvent` config callback, with general `log`/`warning`/`error` events alongside specific ones such as `fallback` and `usage`. Logging is off by default as a library; `logs: true` prints to the console and `logs: "<path>"` writes JSON lines.
|
|
23
|
+
- **Also:** `response_format: json_object` reaches Anthropic upstreams as a schema, falling back to a system instruction when an upstream refuses it; refusals carry `stop_details`.
|
|
24
|
+
- [View full v0.5.0 Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.5.0.md)
|
|
24
25
|
|
|
25
26
|
### Recent Releases
|
|
26
27
|
|
|
28
|
+
- **v0.4.0** (November 2026) — per-model effort levels and aliases that pin effort and thinking, non-standard finish reasons, a configurable tool-error marker, per-upstream `pingInterval` and a Node.js 22.15 floor ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.4.0.md))
|
|
29
|
+
- **v0.3.1** (November 2026) — patched the dev-only `minimatch` and `katex` lint dependencies and corrected the v0.3.0 issue links; no runtime changes ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.3.1.md))
|
|
27
30
|
- **v0.3.0** (November 2026) — usage reporting from `send()`, the `route()` leaf and the server `authorize` hook; drivers for llama.cpp, Ollama, SGLang and the DeepSeek API, endpoint pools, `reasoningRoundTrip` and `toolSearch`; requires Node.js 24 ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.3.0.md))
|
|
28
31
|
- **v0.2.0** (October 2026) — the first working translator: six Anthropic Messages and OpenAI Chat Completions converters, backend detection (vLLM, OpenAI, Anthropic, generic), model aliases, the optional Fastify server and the `llm-translator` CLI for Claude Code ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.2.0.md))
|
|
29
|
-
- **v0.1.0** (October 2026) — package scaffold: ESM and CommonJS entry points, tsup build, the `llm-translator-dev` condition with devcheck, tests on `@cldmv/vitest-runner` and the CLDMV v4 CI/release pipeline; the only export was a placeholder ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.1.0.md))
|
|
30
32
|
|
|
31
33
|
📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/llm-translator/tree/master/docs/changelog/) folder.**
|
|
32
34
|
|
|
@@ -64,8 +66,8 @@ Lines, statements, functions and branches are all at 100% and enforced on every
|
|
|
64
66
|
|
|
65
67
|
### Requirements
|
|
66
68
|
|
|
67
|
-
- Node.js
|
|
68
|
-
- Developing the package
|
|
69
|
+
- Node.js 22.15 or newer. Node.js 26 is fastest: PDF.js (through `unpdf`) uses newer built-ins such as `Promise.try`, `Float16Array` and `Map.prototype.getOrInsert`, which Node.js 22 and 24 run through PDF.js' own polyfills. npm warns on Node.js 22 because `unpdf` 2 declares Node.js 24; text extraction and page rendering work on 22.15.
|
|
70
|
+
- Developing the package needs Node.js 22.22 or newer (`devEngines` enforces it on install and `npm run`)
|
|
69
71
|
- Fastify 5, only for the server and the Fastify plugin (an optional peer dependency)
|
|
70
72
|
|
|
71
73
|
### Install
|
|
@@ -103,6 +105,9 @@ if (reply.stream) for await (const { event, data } of reply.stream) console.log(
|
|
|
103
105
|
// Where would a request go, and what did it cost? (see docs/server.md)
|
|
104
106
|
const { upstream, model } = api.route({ model: "claude-opus-5-5" }); // no I/O
|
|
105
107
|
const { input_tokens, output_tokens, reported, estimated } = await reply.usage; // or send(body, { onUsage }); `estimated` holds the guesses written into the client reply when the upstream sent no usage
|
|
108
|
+
|
|
109
|
+
// Fallbacks, failovers and warnings are events (see docs/events.md); logging is off unless you set `logs`.
|
|
110
|
+
const stop = api.events.on("fallback", ({ endpoint, status, reason }) => console.log(endpoint, status, reason));
|
|
106
111
|
```
|
|
107
112
|
|
|
108
113
|
### Server and Claude Code
|
|
@@ -122,7 +127,7 @@ Then point Claude Code at it with `ANTHROPIC_BASE_URL=http://127.0.0.1:8787`. Th
|
|
|
122
127
|
|
|
123
128
|
## 📚 Configuration
|
|
124
129
|
|
|
125
|
-
`createTranslator(config)` takes `front`, `upstreams` (URLs or objects with `url`, `apiKey`, `backend`, `models`, `default` and `settings`), `aliases
|
|
130
|
+
`createTranslator(config)` takes `front`, `upstreams` (URLs or objects with `url`, `apiKey`, `backend`, `models`, `default` and `settings`), `aliases` (a model name, or `{ model, effort, thinking }` to pin settings), `efforts` (the reasoning levels each model supports, see [docs/settings.md](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md#effort-levels-and-pinned-aliases-not-converter-settings)), global `settings`, `pool` (failover and load balancing between upstreams that serve the same model, see [docs/server.md](https://github.com/CLDMV/llm-translator/blob/master/docs/server.md#endpoint-pools-failover-and-load-balancing)), `detect`, `logs` (off by default; `true` prints warnings, a path appends JSON lines), `events` and `onEvent` (see [docs/events.md](https://github.com/CLDMV/llm-translator/blob/master/docs/events.md)) and a custom `transport`. `silent: true` is a deprecated alias for `logs: false`. The CLI reads the same keys from flags, `LLM_TRANSLATOR_*` environment variables and a JSON file, in that order of precedence.
|
|
126
131
|
|
|
127
132
|
Settings tune how the converters map one protocol onto the other (`inlineSystem`, `images`, `imageFallback`, `toolStreaming`, `pingInterval` and more); they are resolved per upstream from defaults, probed values, driver defaults and your overrides. The full table is in [docs/settings.md](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md).
|
|
128
133
|
|
|
@@ -135,6 +140,7 @@ Settings tune how the converters map one protocol onto the other (`inlineSystem`
|
|
|
135
140
|
- [Server and CLI](https://github.com/CLDMV/llm-translator/blob/master/docs/server.md)
|
|
136
141
|
- [Settings](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md)
|
|
137
142
|
- [Protocol support](https://github.com/CLDMV/llm-translator/blob/master/docs/protocol-support.md)
|
|
143
|
+
- [Events and logging](https://github.com/CLDMV/llm-translator/blob/master/docs/events.md)
|
|
138
144
|
- [Drivers, detection and routing](https://github.com/CLDMV/llm-translator/blob/master/docs/drivers.md)
|
|
139
145
|
|
|
140
146
|
### Guides
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var
|
|
1
|
+
var N=Object.defineProperty;var m=(e,t)=>N(e,"name",{value:t,configurable:!0});import{resolve as q}from"../../../../../../../lib/settings.mjs";import{TranslatorError as T}from"../../../../../../../lib/errors.mjs";import{createNameFitter as O}from"../../../../../../../lib/ids.mjs";import{sanitize as B}from"../../../../../../../lib/schema.mjs";import{NOTE as I}from"../../../../../../../lib/images.mjs";import{expand as A}from"../../../../../../../lib/documents.mjs";import{createBudget as L,unsign as z}from"../../../../../../../lib/thinking.mjs";import{plan as C,scan as D}from"../../../../../../../lib/toolsearch.mjs";const P=new Set(["model","messages","system","max_tokens","stream","temperature","top_p","top_k","stop_sequences","tools","tool_choice","thinking","output_config","output_format","context_management"]),W=new Set(["metadata","cache_control","service_tier"]),H=new Set(["mcp_servers","container","inference_geo"]),K="x-anthropic-billing-header:";async function ue(e,t,o){const n=q(t);if(e===null||typeof e!="object"||!Array.isArray(e.messages))throw new T("messages: Field required",{code:"invalid_request",param:"messages"});const i={front:"anthropic",model:e.model,stream:e.stream===!0,thinking:e.thinking?.type??null,reasoningField:n.reasoningField,toolNames:{},dropped:[]};o?.producer!==void 0&&(i.producer=o.producer);const r=O({max:64,map:i.toolNames});for(const c of e.tools??[])(c.type===void 0||c.type==="custom")&&r(c.name);const d=D(e.messages,new Set((e.tools??[]).map(c=>c.name))),l=C(e.tools??[],d,n,e.tool_choice);i.toolSearch={mode:n.toolSearch,loaded:l.loaded,hidden:l.hidden,stubbed:l.stubbed,capped:d.capped};for(const c of Object.keys(e))if(!(P.has(c)||W.has(c)))if(H.has(c))g(i,c);else{if(n.unknownFields==="error")throw new T(`${c}: Extra inputs are not permitted`,{code:"unsupported_field",param:c});g(i,c)}const s={model:e.model},h=F(e.system,n),k=await R(e.messages,n,i,r,h,U(e.context_management,i),o?.budget??L());s.messages=k.messages,k.prefill&&(s.continue_final_message=!0,s.add_generation_prompt=!1),e.max_tokens!==void 0&&(s[n.maxTokensField]=e.max_tokens),e.temperature!==void 0&&(s.temperature=e.temperature),e.top_p!==void 0&&(s.top_p=e.top_p),e.top_k!==void 0&&(n.topK?s.top_k=e.top_k:g(i,"top_k")),e.stop_sequences?.length>0&&(s.stop=e.stop_sequences),i.stream&&(s.stream=!0,n.streamUsage&&(s.stream_options={include_usage:!0},n.continuousUsage&&(s.stream_options.continuous_usage_stats=!0)));const f=X(l.offer,n,i,r);if(f.length>0){s.tools=f;const c=Y(e.tool_choice,n,i,r);c!==void 0&&(s.tool_choice=c),e.tool_choice?.disable_parallel_tool_use===!0&&n.parallelToolCalls&&(s.parallel_tool_calls=!1)}return Z(e,n,s,o?.listed===!0),b(e,n,i,s),{body:s,state:i}}m(ue,"request");function g(e,t){e.dropped.includes(t)||e.dropped.push(t)}m(g,"drop");function v(e,t,o){if(t.unknownFields==="error")throw new T(`${o}: is not supported by this translator`,{code:"unsupported_content",param:o});g(e,o)}m(v,"unsupported");function F(e,t){return e==null?"":(typeof e=="string"?[{type:"text",text:e}]:e).filter(n=>n.type==="text"&&!(t.stripBillingHeader&&n.text.trimStart().startsWith(K))).map(n=>n.text).join(`
|
|
2
2
|
|
|
3
|
-
`)}
|
|
3
|
+
`)}m(F,"textOf");function j(e){return typeof e=="string"?[{type:"text",text:e}]:e??[]}m(j,"asBlocks");async function R(e,t,o,n,i,r,d){const l=[],s=[],h=new Map,k=t.inlineSystem==="auto"?"user":t.inlineSystem,f=new Map;if(t.reasoningRoundTrip){for(let a=e.length-1;a>=0;a--)if(e[a].role==="assistant")for(const u of[...j(e[a].content)].reverse())u.type==="thinking"&&f.set(u,await z(u.signature,{producer:o.producer,budget:d}))}const c=m(a=>{const u=l.at(-1);u?.role==="user"?u.parts.push(...a):l.push({role:"user",parts:a})},"pushUser"),w=m(async(a,u)=>{switch(a.type){case"text":return a.text===""?[]:[{type:"text",text:a.text}];case"image":return V(a,t,o);case"document":{const _=[];for(const p of await A(a,{settings:t,toolInputs:h,toolUseId:u}))_.push(...await w(p,u));return _}case"search_result":{const _=(a.content??[]).map(p=>p.text).join(`
|
|
4
4
|
`);return[{type:"text",text:`[Search result: ${a.title??""} (${a.source??""})]
|
|
5
|
-
${_}`}]}case"tool_reference":return t.toolSearch==="native"&&t.deferredTools!=="drop"?[{type:"tool_reference",tool_name:a.tool_name}]:[{type:"text",text:o.toolSearch.loaded.includes(a.tool_name)?`[Tool loaded: ${a.tool_name}]`:`[Tool reference: ${a.tool_name}]`}];default:return v(o,t,`block:${a.type}`),[]}},"toParts");for(const a of e)if(a.role==="system"){const
|
|
6
|
-
${
|
|
7
|
-
</system-reminder>`;c([{type:"text",text:_}])}}else if(a.role==="user"){const
|
|
8
|
-
`);
|
|
5
|
+
${_}`}]}case"tool_reference":return t.toolSearch==="native"&&t.deferredTools!=="drop"?[{type:"tool_reference",tool_name:a.tool_name}]:[{type:"text",text:o.toolSearch.loaded.includes(a.tool_name)?`[Tool loaded: ${a.tool_name}]`:`[Tool reference: ${a.tool_name}]`}];default:return v(o,t,`block:${a.type}`),[]}},"toParts");for(const a of e)if(a.role==="system"){const u=F(a.content,t);if(u===""||k==="drop")continue;if(k==="keep")l.push({role:"system",content:u});else if(k==="hoist")s.push(u);else{const _=u.trimStart().startsWith("<system-reminder>")?u:`<system-reminder>
|
|
6
|
+
${u}
|
|
7
|
+
</system-reminder>`;c([{type:"text",text:_}])}}else if(a.role==="user"){const u=[],_=[];for(const y of j(a.content)){if(y.type!=="tool_result"){u.push(...await w(y,null));continue}const S=[];for(const x of j(y.content))S.push(...await w(x,y.tool_use_id));const M=S.filter(x=>x.type==="text").map(x=>x.text),E=S.filter(x=>x.type==="image_url");let $=S.some(x=>x.type==="tool_reference")?S.filter(x=>x.type!=="image_url"):M.join(`
|
|
8
|
+
`);E.length>0&&(_.push({type:"text",text:`Image output of tool call ${y.tool_use_id}:`},...E),$===""&&($="(image output attached in the next message)")),y.is_error===!0&&t.toolErrors&&($=typeof $=="string"?`${t.toolErrorMarker}${$}`:[{type:"text",text:t.toolErrorMarker.trimEnd()},...$]),l.push({role:"tool",tool_call_id:y.tool_use_id,content:$})}const p=[..._,...u];p.length>0&&c(p)}else if(a.role==="assistant"){const u={role:"assistant",texts:[],parts:[],tool_calls:[]};for(const p of j(a.content))if(p.type==="text")p.text!==""&&u.texts.push(p.text);else if(p.type==="thinking"){const y=f.get(p)??null;y?u.parts.push({restored:y}):p.thinking&&u.parts.push({text:p.thinking})}else p.type==="redacted_thinking"?g(o,"redacted_thinking"):p.type==="tool_use"?(h.set(p.id,p.input),u.tool_calls.push({id:p.id,type:"function",function:{name:n(p.name),arguments:JSON.stringify(p.input??{})}})):v(o,t,`block:${p.type}`);const _=l.at(-1);_?.role==="assistant"?(_.texts.push(...u.texts),_.parts.push(...u.parts),_.tool_calls.push(...u.tool_calls)):l.push(u)}else throw new T(`messages: unsupported role "${a.role}"`,{code:"invalid_request",param:"messages"});return Q(l,t,i,s,r,o)}m(R,"convertMessages");function U(e,t){let o=1/0;for(const n of e?.edits??[])typeof n.type=="string"&&n.type.startsWith("clear_thinking")?n.keep==="all"?o=1/0:o=n.keep?.value??1:g(t,`context_management.${n.type}`);return o}m(U,"thinkingTurnsToKeep");function G(e,t){const o=e.find(s=>s.restored&&(s.restored.reasoning_content!==void 0||s.restored.reasoning!==void 0)),n=o?o.restored.reasoning_content!==void 0?"reasoning_content":"reasoning":t;let i="",r,d=null;for(const s of e){const h=s.restored?s.restored.reasoning_content??s.restored.reasoning:s.text;s.restored?.reasoning_details&&(r=[...r??[],...s.restored.reasoning_details]),h!==void 0&&(i+=(d!==null&&!(d.restored&&s.restored)?`
|
|
9
9
|
|
|
10
|
-
`:"")+h,
|
|
10
|
+
`:"")+h,d=s)}const l={};return i!==""&&(l[n]=i),r&&(l.reasoning_details=r),l}m(G,"reasoningFields");function J(e){return!!(e.reasoning_content||e.reasoning||e.reasoning_details)}m(J,"reasoningSent");function Q(e,t,o,n,i,r){let d=i;for(let f=e.length-1;f>=0;f--)e[f].role!=="assistant"||e[f].parts.length===0||(d>0?d--:e[f].parts=[]);const l=[],s=[o,...n].filter(f=>f!=="").join(`
|
|
11
11
|
|
|
12
|
-
`);
|
|
12
|
+
`);s!==""&&l.push({role:"system",content:s});for(const f of e)if(f.role==="user"){const c=f.parts.every(w=>w.type==="text");l.push({role:"user",content:c?f.parts.map(w=>w.text).join(`
|
|
13
13
|
|
|
14
|
-
`):
|
|
14
|
+
`):f.parts})}else if(f.role==="assistant"){const c={role:"assistant",content:f.texts.join(`
|
|
15
15
|
|
|
16
|
-
`)};
|
|
16
|
+
`)};f.parts.length>0&&Object.assign(c,G(f.parts,t.reasoningField)),t.reasoningRoundTrip&&f.tool_calls.length>0&&!J(c)&&(r.reasoningMissing=(r.reasoningMissing??0)+1),f.tool_calls.length>0&&(c.tool_calls=f.tool_calls),l.push(c)}else l.push(f);const h=l.at(-1),k=t.prefill==="continue_final_message"&&h?.role==="assistant"&&!h.tool_calls&&h.content!=="";return{messages:l,prefill:k}}m(Q,"finalize");function V(e,t,o){if(!t.images)return g(o,"image"),[{type:"text",text:I}];const n=e.source;return n.type==="base64"?[{type:"image_url",image_url:{url:`data:${n.media_type};base64,${n.data}`}}]:n.type==="url"?[{type:"image_url",image_url:{url:n.url}}]:(g(o,"image.file"),[{type:"text",text:"[An image supplied as an uploaded file could not be forwarded.]"}])}m(V,"imageParts");function X(e,t,o,n){const i=[];for(const r of e){if(r.type!==void 0&&r.type!=="custom"){g(o,`tool:${r.name}`);continue}if(r.defer_loading===!0&&t.deferredTools==="drop"){g(o,"deferred_tools");continue}const d=r.input_schema??{type:"object",properties:{}},l={name:n(r.name),parameters:t.toolSchema==="sanitize"?B(d):d};r.description!==void 0&&(l.description=r.description),r.strict!==void 0&&(l.strict=r.strict),i.push(r.defer_loading===!0&&t.toolSearch==="native"?{type:"function",function:l,defer_loading:!0}:{type:"function",function:l})}return i}m(X,"convertTools");function Y(e,t,o,n){switch(e?.type){case void 0:return;case"auto":return"auto";case"any":return"required";case"none":return"none";case"tool":return{type:"function",function:{name:n(e.name)}};default:v(o,t,`tool_choice:${e.type}`);return}}m(Y,"convertToolChoice");function Z(e,t,o,n){const i=e.thinking,r=i?.type;let d;r==="disabled"?(t.thinking==="reasoning_effort"&&(d="none"),t.thinking==="chat_template_kwargs"&&(o.chat_template_kwargs={enable_thinking:!1})):(t.effort&&e.output_config?.effort!==void 0&&(d=e.output_config.effort),r==="enabled"&&(t.thinking==="chat_template_kwargs"&&(o.chat_template_kwargs={enable_thinking:!0},t.thinkingBudget&&i.budget_tokens!==void 0&&e.max_tokens!==void 0&&(o.thinking_token_budget=Math.max(0,Math.min(i.budget_tokens,e.max_tokens-1)))),t.thinking==="reasoning_effort"&&d===void 0&&!n&&(d="medium"))),d!==void 0&&(o.reasoning_effort=d)}m(Z,"applyThinking");function b(e,t,o,n){const i=e.output_config?.format??e.output_format;i!==void 0&&(t.responseFormat&&i.type==="json_schema"?n.response_format={type:"json_schema",json_schema:{name:"output",schema:i.schema}}:g(o,"output_config.format"));for(const r of Object.keys(e.output_config??{}))r!=="effort"&&r!=="format"&&g(o,`output_config.${r}`)}m(b,"applyOutputConfig");export{ue as request};
|
|
17
17
|
//# sourceMappingURL=request.mjs.map
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
var v=Object.defineProperty;var
|
|
1
|
+
var v=Object.defineProperty;var f=(e,r)=>v(e,"name",{value:r,configurable:!0});import{resolve as N}from"../../../../../../../lib/settings.mjs";import{TranslatorError as b}from"../../../../../../../lib/errors.mjs";import{anthropicToolId as w,createNameFitter as O}from"../../../../../../../lib/ids.mjs";import{parseArguments as S}from"../../../../../../../lib/arguments.mjs";import{sanitize as q}from"../../../../../../../lib/schema.mjs";import{blocksOf as E}from"../../../../../../../lib/thinking.mjs";const I=new Set(["model","messages","max_tokens","max_completion_tokens","temperature","top_p","top_k","stop","stream","stream_options","tools","tool_choice","parallel_tool_calls","reasoning_effort","response_format","user","n"]),$=new Set(["metadata","store","service_tier"]),x=/^data:([^;,]+);base64,(.*)$/s;async function P(e,r){const i=N(r);if(e===null||typeof e!="object"||!Array.isArray(e.messages))throw new b("messages is a required property",{code:"invalid_request",param:"messages"});if(e.n!==void 0&&e.n!==1)throw new b("n: only a single choice (n = 1) is supported",{code:"unsupported_field",param:"n"});const o={front:"openai",model:e.model,stream:e.stream===!0,includeUsage:e.stream_options?.include_usage===!0,reasoningField:i.reasoningField,toolNames:{},dropped:[]},a=O({max:128,map:o.toolNames});for(const t of Object.keys(e))if(!(I.has(t)||$.has(t))){if(i.unknownFields==="error")throw new b(`${t}: Unrecognized request argument`,{code:"unsupported_field",param:t});g(o,t)}const c=[],p=[],m=f((t,n)=>{const l=p.at(-1);l?.role===t?l.blocks.push(...n):p.push({role:t,blocks:[...n]})},"push");for(const t of e.messages)switch(t.role){case"system":case"developer":{const n=j(t.content);n!==""&&c.push(n);break}case"user":m("user",F(t.content,o));break;case"assistant":{const n=i.reasoningRoundTrip?E(t.reasoning_details):[],l=[],u=j(t.content);u!==""?l.push({type:"text",text:u}):typeof t.refusal=="string"&&t.refusal!==""&&l.push({type:"text",text:t.refusal}),M(t)&&!n.some(d=>d.block.type==="thinking")&&g(o,"reasoning");for(const d of t.tool_calls??[])l.push({type:"tool_use",id:w(d.id),name:a(d.function.name),input:S(d.function.arguments)});const k=A(n,l);k.length>0&&m("assistant",k);break}case"tool":{const n={type:"tool_result",tool_use_id:w(t.tool_call_id),content:j(t.content)};if(i.toolErrorInference){const u=i.toolErrorMarker.trimEnd();n.content.startsWith(u)&&(n.is_error=!0,n.content=n.content.slice(u.length).replace(/^\s/,""))}const l=p.at(-1);if(l?.role==="user"){const u=l.blocks.findIndex(k=>k.type!=="tool_result");l.blocks.splice(u===-1?l.blocks.length:u,0,n)}else p.push({role:"user",blocks:[n]});break}default:throw new b(`messages: unsupported role "${t.role}"`,{code:"invalid_request",param:"messages"})}const s={model:e.model,max_tokens:e.max_completion_tokens??e.max_tokens??i.defaultMaxTokens};c.length>0&&(s.system=c.join(`
|
|
2
2
|
|
|
3
|
-
`)),
|
|
3
|
+
`)),s.messages=p.map(t=>({role:t.role,content:t.blocks})),e.temperature!==void 0&&(s.temperature=Math.min(1,e.temperature)),e.top_p!==void 0&&(s.top_p=e.top_p),e.top_k!==void 0&&(s.top_k=e.top_k),e.stop!==void 0&&e.stop!==null&&(s.stop_sequences=[].concat(e.stop)),o.stream&&(s.stream=!0),typeof e.user=="string"&&(s.metadata={user_id:e.user});const y=[];for(const t of e.tools??[]){if(t.type!=="function"){g(o,`tool:${t.type}`);continue}const n=t.function,l=n.parameters??{type:"object",properties:{}},u={name:a(n.name),input_schema:i.toolSchema==="sanitize"?q(l):l};n.description!==void 0&&(u.description=n.description),y.push(u)}if(y.length>0){s.tools=y;let t=R(e.tool_choice,a);e.parallel_tool_calls===!1&&t.type!=="none"&&(t={...t,disable_parallel_tool_use:!0}),(e.tool_choice!==void 0||e.parallel_tool_calls===!1)&&(s.tool_choice=t)}const _=e.reasoning_effort;_==="none"?s.thinking={type:"disabled"}:_!=null&&(s.thinking={type:"adaptive"},s.output_config={effort:_==="minimal"?"low":_});const h=e.response_format;return h?.type==="json_schema"?s.output_config={...s.output_config,format:{type:"json_schema",schema:h.json_schema.schema}}:h?.type==="json_object"&&(i.jsonObject==="schema"?(s.output_config={...s.output_config,format:{type:"json_schema",schema:{type:"object"}}},o.jsonSchemaEmulated=!0):i.jsonObject==="instruction"?s.system=s.system===void 0?T:`${s.system}
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
${T}`:g(o,"response_format")),{body:s,state:o}}f(P,"request");const T="Respond with a single valid JSON object and nothing else.";function g(e,r){e.dropped.includes(r)||e.dropped.push(r)}f(g,"drop");function A(e,r){const i=[...e].sort((p,m)=>p.at-m.at),o=[];let a=0;const c=r.findIndex(p=>p.type==="tool_use");for(const p of i){const m=p.at<=1&&c!==-1?Math.min(p.at,c):p.at;for(;a<Math.min(m,r.length);)o.push(r[a++]);o.push(p.block)}return[...o,...r.slice(a)]}f(A,"interleave");function M(e){return!!(e.reasoning||e.reasoning_content)}f(M,"reasoningPresent");function j(e){return typeof e=="string"?e:(e??[]).filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
6
|
+
|
|
7
|
+
`)}f(j,"plainText");function F(e,r){if(typeof e=="string")return e===""?[]:[{type:"text",text:e}];const i=[];for(const o of e??[])if(o.type==="text")i.push({type:"text",text:o.text});else if(o.type==="image_url"){const a=x.exec(o.image_url.url);i.push({type:"image",source:a?{type:"base64",media_type:a[1],data:a[2]}:{type:"url",url:o.image_url.url}})}else if(o.type==="file"&&typeof o.file?.file_data=="string"&&x.test(o.file.file_data)){const a=x.exec(o.file.file_data);i.push({type:"document",source:{type:"base64",media_type:a[1],data:a[2]}})}else g(r,`content:${o.type}`);return i}f(F,"userBlocks");function R(e,r){return e==="none"?{type:"none"}:e==="required"?{type:"any"}:typeof e=="object"&&e!==null?{type:"tool",name:r(e.function.name)}:{type:"auto"}}f(R,"toolChoice");export{P as request};
|
|
6
8
|
//# sourceMappingURL=request.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var c=(t,n)=>y(t,"name",{value:n,configurable:!0});import{resolve as _}from"../../../../../../../lib/settings.mjs";import{TranslatorError as m}from"../../../../../../../lib/errors.mjs";import{messageId as k,anthropicToolId as T,restoreName as x}from"../../../../../../../lib/ids.mjs";import{sign as A,reasoningOf as w,reasoningKey as C,detailsText as N,splitThink as O}from"../../../../../../../lib/thinking.mjs";import{isComplete as S,parseArguments as U}from"../../../../../../../lib/arguments.mjs";import{finishError as v,toAnthropicStop as E,toAnthropicUsage as I}from"../../../../../../../lib/finish.mjs";function D(t,n,u){const f=_(u),l=t?.choices?.[0];if(!l)throw new m("Upstream response contained no choices",{code:"invalid_upstream_response",status:502});const g=v(l.finish_reason);if(g)throw new m(g.message,{code:g.code,status:g.status,type:g.type});const e=l.message??{},i=[];let a=w(e),s=typeof e.content=="string"?e.content:"";const o={};if(f.reasoningRoundTrip){const r=C(e);r&&(o[r]=e[r]),Array.isArray(e.reasoning_details)&&e.reasoning_details.length>0&&(o.reasoning_details=e.reasoning_details)}a===""&&f.thinkTags&&({reasoning:a,text:s}=O(s,f.thinkOpen)),a===""&&o.reasoning_details&&(a=N(o.reasoning_details)),(a!==""||o.reasoning_details)&&(i.push({type:"thinking",thinking:a,signature:A(Object.keys(o).length>0?o:void 0,n?.producer)}),s=s.trimStart()),s===""&&typeof e.refusal=="string"&&(s=e.refusal),s!==""&&i.push({type:"text",text:s});const h=n?.toolNames??{},p=e.tool_calls??[];for(const r of p)i.push({type:"tool_use",id:T(r.id),name:x(h,r.function.name),input:U(r.function.arguments)});i.length===0&&i.push({type:"text",text:""});const d=E(l.finish_reason,{hasToolCalls:p.length>0,matchedStop:l.stop_reason,refusal:e.refusal,argumentsComplete:p.length===0||S(p.at(-1).function.arguments)});return n&&t.usage&&(n.upstreamUsage=t.usage),{id:k(),type:"message",role:"assistant",model:n?.model??t.model,content:i,...d,usage:I(t.usage)}}c(D,"response");export{D as response};
|
|
2
2
|
//# sourceMappingURL=response.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var l=(b,a)=>L(b,"name",{value:a,configurable:!0});import{resolve as P}from"../../../../../../../lib/settings.mjs";import{TranslatorError as Q,openaiToAnthropicType as V,rewriteContextOverflow as W}from"../../../../../../../lib/errors.mjs";import{isComplete as X}from"../../../../../../../lib/arguments.mjs";import{messageId as Y,anthropicToolId as Z,restoreName as $}from"../../../../../../../lib/ids.mjs";import{sign as ee,reasoningOf as te,reasoningKey as ne,detailsText as ie,mergeDetail as oe,createThinkSplitter as se}from"../../../../../../../lib/thinking.mjs";import{finishError as le,toAnthropicStop as re,toAnthropicUsage as q}from"../../../../../../../lib/finish.mjs";import{messages as ae}from"../../../../../../../lib/sse.mjs";async function*_e(b,a,B){const u=P(B),F=a?.toolNames??{},d=u.thinkTags?se(u.thinkOpen):null,c=new Map;let _=!1,j=0,n=null,N=null,k=null,O=null,h="",v=!1,A=!1,C=0,T=!1,U=!1,E=!1;const w=[],s=l((e,t)=>({event:e,data:{type:e,...t}}),"event"),p=l((e,t)=>s("error",{error:{type:e,message:t}}),"fail"),J=l(e=>{const t={};return u.reasoningRoundTrip&&(e.key!==null&&(t[e.key]=e.text),e.details.length>0&&(t.reasoning_details=e.details)),Object.keys(t).length>0?t:void 0},"carried");function*y(){if(n!==null){n.kind==="thinking"?yield s("content_block_delta",{index:n.index,delta:{type:"signature_delta",signature:ee(J(n.carry),a?.producer)}}):n.kind==="tool"&&(n.entry.state="closed",n.entry.sent||(yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:"{}"}}))),yield s("content_block_stop",{index:n.index}),n=null;for(const e of c.values()){if(e.state!=="pending")continue;e.state="closed";const t=j++,i=e.args.join("");yield s("content_block_start",{index:t,content_block:e.block}),yield s("content_block_delta",{index:t,delta:{type:"input_json_delta",partial_json:i===""?"{}":i}}),yield s("content_block_stop",{index:t})}}}l(y,"close");function*K(){for(const e of I()){if(e.state!=="buffered")continue;yield*g("tool",e.block,e);const t=e.args.join("");t!==""&&(e.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:t}})),yield*y()}}l(K,"flushBuffered");function I(){return[...c.entries()].sort((e,t)=>e[0]-t[0]).map(e=>e[1])}l(I,"ordered");function*g(e,t,i){yield*y(),n={kind:e,index:j++,entry:i,carry:{key:null,text:"",details:[]}},yield s("content_block_start",{index:n.index,content_block:t})}l(g,"begin");function*r(e,t,i=null){if(e==="text"&&E&&(t=t.trimStart()),t==="")return;if(E=e==="thinking",e==="text"&&(v=!0),n?.kind==="tool"){w.push({kind:e,text:t,key:i});return}n?.kind!==e&&(yield*g(e,e==="text"?{type:"text",text:""}:{type:"thinking",thinking:"",signature:""})),i!==null&&(n.carry.key??=i,n.carry.text+=t);const o=e==="text"?{type:"text_delta",text:t}:{type:"thinking_delta",thinking:t};yield s("content_block_delta",{index:n.index,delta:o})}l(r,"piece");function*R(e){if(n?.kind==="tool"){w.push({kind:"details",items:e});return}n?.kind!=="thinking"&&(yield*g("thinking",{type:"thinking",thinking:"",signature:""}));for(const t of e)oe(n.carry.details,t);n.carry.key===null&&(yield*r("thinking",ie(e)))}l(R,"details");function*z(e){yield*r("thinking",e.reasoning),yield*r("text",e.text)}l(z,"pieces");function*M(e){let t=e.index;t===void 0&&(t=e.id===void 0?C:c.size),C=t;let i=c.get(t);if(i===void 0){const x=e.function?.name??"",m={type:"tool_use",id:Z(e.id),name:$(F,x),input:{}};d?.pending()&&(U=!0);const f=u.toolStreaming==="buffer"||U;i={state:f?"buffered":"pending",sent:!1,args:[],block:m},c.set(t,i),!f&&n?.kind!=="tool"&&(i.state="open",yield*g("tool",m,i))}let o=e.function?.arguments;o!==null&&typeof o=="object"&&(o=JSON.stringify(o)),!(o==null||o==="")&&(i.args.push(o),i.state==="open"&&(i.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:o}})))}l(M,"toolCall");try{for await(const e of ae(b)){if(e.data==="[DONE]"){A=!0;break}const t=e.data;if(t.error){const f=t.error.message??"Upstream error";yield p(V(t.error),W(f)??f);return}_||(_=!0,yield s("message_start",{message:{id:Y(),type:"message",role:"assistant",model:a?.model??t.model,content:[],stop_reason:null,stop_sequence:null,usage:q(t.usage)}})),t.usage&&(N=t.usage,a&&(a.upstreamUsage=t.usage));const i=t.choices?.[0];if(!i)continue;const o=i.delta??{},x=te(o);let m="";x!==""&&!T&&(T=!0,d&&(m=d.release().text)),yield*r("thinking",x,ne(o)),yield*r("text",m),u.reasoningRoundTrip&&Array.isArray(o.reasoning_details)&&o.reasoning_details.length>0&&(yield*R(o.reasoning_details)),typeof o.content=="string"&&o.content!==""&&(d&&!T?yield*z(d.push(o.content)):yield*r("text",o.content)),typeof o.refusal=="string"&&(h+=o.refusal);for(const f of o.tool_calls??[])yield*M(f);i.finish_reason&&(k=i.finish_reason),typeof i.stop_reason=="string"&&(O=i.stop_reason)}}catch(e){yield e instanceof Q?p(e.type,e.message):p("api_error",e.message);return}if(!_||k===null&&!A){yield p("api_error",_?"Upstream stream ended before completion":"Upstream stream ended without data");return}const S=le(k);if(S){yield p(S.type,S.message);return}d&&(yield*z(d.end())),yield*K();const D=I().at(-1),G=D===void 0||X(D.args.join(""));yield*y();for(const e of w)yield*e.kind==="details"?R(e.items):r(e.kind,e.text,e.key);!v&&h!==""&&(yield*r("text",h)),yield*y(),j===0&&(yield*g("text",{type:"text",text:""}),yield*y());const H=re(k,{hasToolCalls:c.size>0,matchedStop:O,argumentsComplete:G,refusal:h});yield s("message_delta",{delta:H,usage:q(N)}),yield s("message_stop",{})}l(_e,"stream");export{_e as stream};
|
|
2
2
|
//# sourceMappingURL=stream.mjs.map
|
package/dist/api/detect.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var n=(r,e)=>v(r,"name",{value:e,configurable:!0});import{context as g,self as m}from"../lib/runtime.mjs";import{capture as w}from"../lib/capture.mjs";import{TranslatorError as d}from"../lib/errors.mjs";import{warn as y}from"../lib/warn.mjs";import{emit as h}from"../lib/events.mjs";import*as p from"../lib/http.mjs";async function D(r={}){const e=w(m,g),{status:o}=m,f=r.network!==!1;for(const a of e.drivers){const s=a.info.fields;if(s!==void 0&&!(Array.isArray(s)&&s.every(i=>typeof i=="string")))throw new d(`Driver ${a.name}: info().fields must be an array of field names`,{code:"invalid_driver",status:500})}const t={transport:e.state.transport,signal:r.signal,timeout:e.config.detectTimeout};return await Promise.all(e.state.endpoints.map(a=>k(e,a,f,t))),o()}n(D,"detect");async function k(r,e,o,f){let t,a=null;if(e.backend!=="auto"){if(t=r.drivers.find(s=>s.name===e.backend),!t)throw new d(`Unknown backend "${e.backend}" for upstream ${e.name}`,{code:"unknown_backend",status:500});a={version:e.version}}else if(o){const s={endpoint:e,...f,probes:new Map};let i=!1;for(const[l,c]of r.drivers.entries()){if(!i&&c.info.probes?.length>0){i=!0;for(const u of r.drivers.slice(l))for(const b of u.info.probes??[])p.probe(s,b)}if(a=await $(c,s),a){t=c;break}}}if(t||(t=r.drivers.find(s=>s.name==="compatible"),a={reachable:null,models:[]}),e.driver=t.name,e.protocol=t.info.protocol,e.facts=a,e.driverSettings=await t.settings?.(a)??{},e.probed={},o&&e.backend==="auto"&&t.probe){const s=n(l=>e.settings[l]!==void 0||r.config.settings[l]!==void 0,"given"),i={inlineSystem:r.settings(e).inlineSystem==="auto",images:!s("images")};(i.inlineSystem||i.images)&&(e.probed=await t.probe({endpoint:e,facts:a,want:i,...f}))}a.reachable===!1?y(r.config,r.state,`Upstream ${e.name} (${e.url}) did not answer detection; using the generic OpenAI-compatible driver`,{type:"detect",kind:"unreachable",endpoint:e.name,url:e.url,driver:t.name}):h({config:r.config,state:r.state},{type:"detect",kind:"driver",level:"info",message:`Upstream ${e.name} (${e.url}): driver ${t.name}`,endpoint:e.name,url:e.url,driver:t.name})}n(k,"bind");async function $(r,e){try{return await r.detect?.(e)??null}catch{return null}}n($,"detectWith");export{D as detect};
|
|
2
2
|
//# sourceMappingURL=detect.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var r=Object.defineProperty;var n=(t,e)=>r(t,"name",{value:e,configurable:!0});import{noEmptyTools as s}from"../../../lib/normalize.mjs";const f=new Set(["xhigh","max"]);function h(t,e){const o=s(t);return f.has(o.reasoning_effort)&&e?.levels===void 0&&e?.settings?.effortPassthrough!==!0?{...o,reasoning_effort:"high"}:o}n(h,"request");export{h as request};
|
|
2
2
|
//# sourceMappingURL=request.mjs.map
|
package/dist/api/model/list.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var n=(t,i)=>m(t,"name",{value:i,configurable:!0});import{context as c,self as u}from"../../lib/runtime.mjs";import{capture as _}from"../../lib/capture.mjs";import{defaultOf as p,nearest as g}from"../../lib/effort.mjs";async function b(t={}){const i=_(u,c,t.front),o=new Map;await Promise.all(i.state.endpoints.map(async e=>{const s=i.driver(e),r=(s.list?await s.list({endpoint:e,transport:i.state.transport,signal:t.signal,timeout:i.config.detectTimeout}):null)??(e.models??e.facts?.models??[]).map(l=>({id:l}));for(const l of r)o.set(l.id,{...l,upstream:e.name})}));for(const e of Object.keys(i.config.aliases)){const s=o.get(i.config.aliases[e]);o.set(e,{...s,id:e,alias_of:i.config.aliases[e]})}const f=[...o.values()].map(e=>({...e,...v(i.config,e)}));if(i.front==="openai")return{object:"list",data:f.map(e=>({id:e.id,object:"model",created:e.created??0,owned_by:e.owned_by??e.upstream??"llm-translator",...e.max_model_len===void 0?{}:{max_model_len:e.max_model_len},...d(e)}))};const a=f.map(e=>({type:"model",id:e.id,display_name:e.id,created_at:new Date((e.created??0)*1e3).toISOString(),...e.max_model_len===void 0?{}:{max_input_tokens:e.max_model_len},...d(e)}));return{data:a,has_more:!1,first_id:a[0]?.id??null,last_id:a.at(-1)?.id??null}}n(b,"list");function v(t,i){const o=i.alias_of??i.id,f=Object.hasOwn(t.efforts,o)?t.efforts[o]:void 0,a=i.alias_of!==void 0&&Object.hasOwn(t.pins,i.id)?t.pins[i.id]:{},e={};return a.thinking!==void 0&&(e.thinking=a.thinking),a.thinking===!1||(a.effort!==void 0?(e.effort=f?g(f.levels,a.effort):a.effort,e.levels=[e.effort],e.default_effort=e.effort):f&&(e.levels=f.levels,e.default_effort=p(f))),e}n(v,"levelsOf");function d(t){return{...t.alias_of===void 0?{}:{alias_of:t.alias_of},...t.levels===void 0?{}:{efforts:t.levels,default_effort:t.default_effort},...t.effort===void 0?{}:{effort:t.effort},...t.thinking===void 0?{}:{thinking:t.thinking}}}n(d,"extras");export{b as list};
|
|
2
2
|
//# sourceMappingURL=list.mjs.map
|
package/dist/api/request.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
1
|
+
var _=Object.defineProperty;var p=(e,o)=>_(e,"name",{value:o,configurable:!0});import{context as q,self as T}from"../lib/runtime.mjs";import{capture as I}from"../lib/capture.mjs";import{resolve as L}from"../lib/route.mjs";import*as w from"../lib/http.mjs";import{filterChatBody as B}from"../lib/passthrough.mjs";import*as $ from"../lib/images.mjs";import*as y from"../lib/tools.mjs";import{LIMITS as M}from"../lib/toolsearch.mjs";import{warn as h}from"../lib/warn.mjs";import{emit as P}from"../lib/events.mjs";import{fit as R,pinBody as C}from"../lib/effort.mjs";function E(e){return`${e.driver}:${e.protocol}:${URL.canParse(e.url)?new URL(e.url).host:e.url}`}p(E,"producerOf");async function V(e,o={}){const r=I(T,q,o.front),c=L(r,e,{endpoint:o.endpoint,advance:o.hold===!0&&o.endpoint===void 0});if(o.hold!==!0)return O(r,e,o,c);c.endpoint.health.inflight++;try{return await O(r,e,o,c)}catch(t){throw c.endpoint.health.inflight--,t}}p(V,"request");async function O(e,o,r,c){const{endpoint:t,model:s,unserved:F,convert:m,pool:U,pin:g}=c,d=Object.hasOwn(e.config.efforts,s)?e.config.efforts[s]:void 0;g&&(o=C(o,g,e.front));const i=e.driver(t),u=`${t.name}
|
|
2
|
+
${s}`,k=r.images===!1||e.state.textOnly.has(u)&&e.settings(t).imageFallback,v=e.settings(t),x=r.jsonObject==="instruction"||e.state.jsonInstruction.has(u)&&v.jsonObjectFallback,l={...k?{...v,images:!1}:v,...x?{jsonObject:"instruction"}:{},...g?.effort===void 0?{}:{effort:!0}},j=o.stream===!0;let n,a;if(m?({body:n,state:a}=await m.request(o,l,{producer:E(t),budget:r.budget,listed:d!==void 0}),a.toolSearch?.capped&&h(e.config,e.state,`Tool search: more than ${M.definitions} tool definitions came back in ToolSearch results for ${t.name}; the rest are not offered.`,{kind:"toolsearch",endpoint:t.name,log:r.log})):n=e.front==="openai"&&(r.filter??l.passthroughFilter===!0)?B(o,i.info.fields):{...o},r.usage===!0&&j&&e.front==="openai"){if(m)a.includeUsage=!0;else if(l.streamUsage){const f=n.stream_options&&typeof n.stream_options=="object"?n.stream_options:{};n.stream_options={...f,include_usage:!0}}}k&&!m&&e.front==="openai"&&(n=$.strip(n)),r.tools===!1&&(n=y.strip(n)),n.model=s,d&&t.protocol==="openai.chat"&&R(n,d,s,(f,S)=>h(e.config,e.state,f,{type:"effort",endpoint:t.name,model:s,...S,log:r.log})),a?.reasoningMissing&&h(e.config,e.state,`Upstream ${t.name}: assistant turns with tool calls have no reasoning to send back (the client dropped its thinking blocks or their signatures), which servers that need it with tools will refuse.`,{kind:"reasoning",endpoint:t.name,log:r.log}),i.request&&(n=await i.request(n,{endpoint:t,settings:l,levels:d,state:a,warn:p(f=>h(e.config,e.state,f,{kind:"driver",endpoint:t.name,log:r.log}),"warn")})),a?.dropped?.length>0&&r.retry!==!0&&P(e,{type:"dropped",level:"debug",message:`Upstream ${t.name}: dropped ${a.dropped.join(", ")}`,endpoint:t.name,model:s,fields:[...a.dropped],log:r.log});const b=t.protocol==="openai.chat"?i.info.paths.chat:i.info.paths.messages;return{upstream:t.name,pool:U.map(f=>f.name),method:"POST",url:w.join(t.url,b),path:b,headers:{"content-type":"application/json",accept:j?"text/event-stream":"application/json",...i.info.headers,...m===null&&t.protocol==="anthropic.messages"?r.clientHeaders:void 0,...w.headers(t,i.info.auth,r.headers)},body:n,state:{v:1,upstream:t.name,front:e.front,native:m===null,model:o.model,stream:j,unserved:F,convert:a},images:{sent:$.carries(n),retry:l.imageFallback&&t.protocol==="openai.chat",key:u},tools:{sent:y.carries(n),retry:l.toolFallback&&t.protocol==="openai.chat"},json:{sent:a?.jsonSchemaEmulated===!0,retry:l.jsonObjectFallback&&t.protocol==="anthropic.messages",key:u}}}p(O,"prepare");export{V as request};
|
|
3
3
|
//# sourceMappingURL=request.mjs.map
|
package/dist/api/send.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Z=Object.defineProperty;var l=(u,r)=>Z(u,"name",{value:r,configurable:!0});import{context as L,self as K}from"../lib/runtime.mjs";import{TranslatorError as J}from"../lib/errors.mjs";import*as tt from"../lib/http.mjs";import*as et from"../lib/images.mjs";import*as at from"../lib/tools.mjs";import{parse as nt}from"../lib/upstream-error.mjs";import{meter as rt,normalize as st}from"../lib/usage.mjs";import{capture as ot}from"../lib/capture.mjs";import{estimate as it,bodyLength as lt,output as ut,patch as ct,stream as mt}from"../lib/estimate.mjs";import{warn as dt}from"../lib/warn.mjs";import{emit as Q}from"../lib/events.mjs";import*as V from"../lib/pool.mjs";import{createBudget as pt}from"../lib/thinking.mjs";const ft={"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"};async function St(u,r={}){const{transport:y,textOnly:d,jsonInstruction:k}=L.state,{request:j,response:_,stream:o,error:g}=K,p=g.build,{config:i,state:v}=L,h=ot(K,L,r.front),S=u&&typeof u=="object"&&!Array.isArray(u),x={model:null,requested:S&&typeof u.model=="string"?u.model:null,upstream:null,front:r.front??i.front,stream:S&&u.stream===!0},b=rt(x,r.onUsage,(c,E)=>dt(i,v,c,{type:"usage",...E,log:r.log})),O=l(c=>Object.defineProperty(c,"usage",{value:b.usage,enumerable:!1,configurable:!0}),"attach");try{return O(await gt({transport:y,textOnly:d,jsonInstruction:k,request:j,response:_,stream:o,error:g,captured:h},u,r,b))}catch(c){if(!(c instanceof J))throw r.signal?.aborted||Q(h,{type:"error",kind:"exception",level:"error",message:String(c?.message??c),log:r.log}),b.finish(r.signal?.aborted?"aborted":"error"),c;return b.finish("error"),O(p(c.status,c.message,{type:c.type,code:c.code,param:c.param,front:r.front}))}}l(St,"send");async function gt({transport:u,textOnly:r,jsonInstruction:y,request:d,response:k,stream:j,error:_,captured:o},g,p,i){const v={front:p.front,headers:p.headers,clientHeaders:p.clientHeaders,filter:p.filter,usage:!0,budget:pt(),log:p.log},h=l(e=>{Q(o,{...e,log:p.log})},"announce"),S=i.meta.front==="openai"&&g?.stream_options?.include_usage!==!0,x=l(e=>{i.meta.model=e.body.model??null,i.meta.upstream=e.upstream,e.state.native?i.source(null):i.source(()=>e.state.convert?.upstreamUsage,e.state.front==="anthropic"?"openai":"folded")},"note"),b=l(e=>{if(e.state.native)return{input:!1,output:!1};const t=st(e.state.front==="anthropic"?"openai":"folded",e.state.convert?.upstreamUsage);return t===null?{input:!0,output:!0}:{input:t.input_tokens===null&&t.cache_read_input_tokens===null&&t.cache_creation_input_tokens===null,output:t.output_tokens===null}},"gaps"),O=l(async e=>{const t=o.endpoint(e.upstream),a=o.driver(t);return(a.count&&!(S&&e.state.stream)?await a.count({endpoint:t,request:e.body,transport:u,signal:p.signal,timeout:o.config.detectTimeout}):null)??it(e.body)},"input"),c=l(async(e,t)=>{const a=b(e);return!a.input&&!a.output?null:{input_tokens:a.input?await O(e):null,output_tokens:a.output?ut(t):null}},"counts"),E=l((e,t,a,n,B)=>(i.finish(B),_(e,t,a,n)),"fail"),X=l(async e=>{let t=e,a=await W(u,t,p.signal,R());const n=a.status,B=n===400&&[t.images,t.tools].some(T=>T.sent&&T.retry),D=(n===400||n===422)&&t.json.sent&&t.json.retry;if(!a.ok&&(B||D)){const T=await M(a),$=nt(T,n).message,f={};if(n===400&&t.images.sent&&t.images.retry&&et.refused($)?(r.add(t.images.key),f.images=!1):n===400&&t.tools.sent&&t.tools.retry&&at.refused($)?f.tools=!1:D&&(f.jsonObject="instruction"),!("images"in f||"tools"in f||"jsonObject"in f))return{upstream:t,result:a,failure:T};const w={upstream:t,result:a,failure:T};if("images"in f||"tools"in f){const I="images"in f?"images":"tools";h({type:"fallback",kind:I,level:"warn",message:`Upstream ${t.upstream}: ${t.state.model} refused ${I==="images"?"images":"tools"} (${n}: "${String($).trim().slice(0,500)}"); sent the request again without them.`,endpoint:t.upstream,model:t.body.model,status:n,reason:String($).trim().slice(0,500),action:I==="images"?"text-only":"without-tools"})}if(t=await d(g,{...v,...f,endpoint:t.upstream,retry:!0}),x(t),a=await W(u,t,p.signal,R()),D&&"jsonObject"in f){if(!a.ok){try{await a.body?.cancel?.()}catch{}return x(w.upstream),w}y.add(w.upstream.json.key),h({type:"fallback",kind:"json_object",level:"warn",message:`Upstream ${w.upstream.upstream}: ${w.upstream.state.model} rejected the json_object schema emulation (${n}: "${String($).trim().slice(0,500)}"); sent it as a system instruction instead. Set jsonObject: "instruction" on this upstream to skip the first attempt.`,endpoint:w.upstream.upstream,model:w.upstream.body.model,status:n,reason:String($).trim().slice(0,500),action:"instruction"})}}return{upstream:t,result:a}},"attempt");let s=await d(g,{...v,hold:!0});const H=s.pool;let q=0;const P=H.length>1?o.config.pool:null,R=l(()=>P&&{connectTimeout:P.connectTimeout,headersTimeout:q+1<H.length?P.headersTimeout:0},"limitsNow");let U=o.endpoint(s.upstream);const F=l(()=>U.health.inflight--,"release");let m,N;try{for(;;){const e=U;e.health.requests++,x(s);let t=null;try{({upstream:s,result:m,failure:N}=await X(s)),!m.ok&&m.status>=500&&(t=`HTTP ${m.status}`,h({type:"error",kind:"upstream",level:"error",message:`Upstream ${e.name} answered HTTP ${m.status}`,endpoint:e.name,model:s.body.model,status:m.status}))}catch(n){if(!(n instanceof J)||n.code!=="upstream_unreachable")throw n;t=n.message,m=void 0,N=n,h({type:"error",kind:"transport",level:"error",message:n.message,endpoint:e.name,model:s.body.model})}if(t===null){V.succeeded(e);break}V.failed(o.config,e,t);let a=null;for(;a===null&&!p.signal?.aborted&&q+1<H.length;)try{a=await d(g,{...v,endpoint:H[++q],hold:!0})}catch(n){if(!(n instanceof J)||n.code!=="endpoint_not_in_pool")throw n}if(a===null){if(m===void 0)throw N;break}h({type:"failover",level:"warn",message:`Upstream ${e.name} failed (${t}); trying ${a.upstream}`,from:e.name,to:a.upstream,model:a.body.model,reason:t});try{await m?.body?.cancel?.()}catch{}F(),U=o.endpoint(a.upstream),s=a}}catch(e){throw F(),e}const Y=U;U=null,i.usage.then(()=>Y.health.inflight--);const G=tt.plain(m.headers);if(!m.ok)return E(m.status,N??await M(m),G,s.state,"upstream_error");if(s.state.stream){const e=j(m.body,s.state),t=s.state.native?e:mt(i.meta.front,e,{gaps:l(()=>b(s),"gaps"),input:l(()=>O(s),"input"),report:l(a=>i.estimate(a),"report")});return{status:200,headers:ft,stream:i.track(t,p.signal,S)}}const C=await M(m);if(C===null||typeof C!="object")return h({type:"error",kind:"upstream",level:"error",message:`Upstream ${s.upstream} returned a body that is not JSON`,endpoint:s.upstream,model:s.body.model,status:502}),E(502,"The upstream returned a body that is not JSON",G,s.state,"error");const A=await k(C,s.state),z=await c(s,lt(i.meta.front,A));return z&&(A.usage=ct(i.meta.front,A.usage,z),i.estimate(z)),i.json(A),i.finish("done"),{status:200,headers:{"content-type":"application/json"},body:A}}l(gt,"round");async function W(u,r,y,d=null){let k,j=!1,_=y;if(d&&d.headersTimeout>0){const o=new AbortController;_=y?AbortSignal.any([y,o.signal]):o.signal,k=setTimeout(()=>{j=!0,o.abort()},d.headersTimeout)}try{return await u(r.url,{method:r.method,headers:r.headers,body:JSON.stringify(r.body),signal:_,redirect:"error",...d&&d.connectTimeout>0?{connectTimeout:d.connectTimeout}:{}})}catch(o){if(y?.aborted)throw o;const g=j?`no response headers within ${d.headersTimeout} ms`:o.message;throw new J(`Could not reach the upstream (${r.upstream}): ${g}`,{code:"upstream_unreachable",status:502,details:{cause:o}})}finally{clearTimeout(k)}}l(W,"call");async function M(u){const r=await u.text();try{return JSON.parse(r)}catch{return r===""?null:r}}l(M,"parse");export{St as send};
|
|
2
2
|
//# sourceMappingURL=send.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var n=(o,t)=>w(o,"name",{value:t,configurable:!0});import{context as s,self as u}from"../../lib/runtime.mjs";import{TranslatorError as m}from"../../lib/errors.mjs";import{register as b}from"../../lib/routes.mjs";import{capture as k}from"../../lib/capture.mjs";import{resolve as x}from"../../lib/route.mjs";import{resolve as y}from"../../lib/settings.mjs";import{emit as I}from"../../lib/events.mjs";async function J(o,t={}){const{config:r}=s;if(t.front!==void 0&&t.front!=="anthropic"&&t.front!=="openai")throw new m(`front must be "anthropic" or "openai" (got ${JSON.stringify(t.front)})`,{code:"invalid_config",status:500});for(const e of["authorize","onUsage"])if(t[e]!==void 0&&typeof t[e]!="function")throw new m(`${e} must be a function`,{code:"invalid_config",status:500});const{send:d,route:p,token:h,model:c,error:v,sse:f}=u,l=t.front??r.front,{state:a}=s,{events:i}=a;i.logger=o.log,o.addHook("onClose",async()=>{i.logger===o.log&&(i.logger=null)});const g=k(u,s,l);b(o,t,{front:l,filter:r.settings.passthroughFilter!==!1,interval:n(e=>{try{return g.settings(x(g,e).endpoint).pingInterval}catch{return y(r.settings).pingInterval}},"interval"),send:d,route:p,count:h.count,list:c.list,get:c.get,emit:n(e=>I({config:r,state:a},e),"emit"),build:v.build,encode:f.encode,write:f.write})}n(J,"plugin");export{J as plugin};
|
|
2
2
|
//# sourceMappingURL=plugin.mjs.map
|
package/dist/index.cjs
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
|
|
36
36
|
if (!process.features?.require_module) {
|
|
37
37
|
const error = new Error(
|
|
38
|
-
`@cldmv/llm-translator: require() needs Node.js >=
|
|
38
|
+
`@cldmv/llm-translator: require() needs Node.js >=22.15.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
|
|
39
39
|
);
|
|
40
40
|
error.code = "ERR_REQUIRE_ESM";
|
|
41
41
|
throw error;
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i=Object.defineProperty;var
|
|
1
|
+
var i=Object.defineProperty;var a=(r,t)=>i(r,"name",{value:t,configurable:!0});import{fileURLToPath as d}from"node:url";import p from"@cldmv/slothlet";import{normalize as c}from"./lib/config.mjs";import{load as l}from"./lib/pdf.mjs";import{transport as f}from"./lib/transport.mjs";import{create as m,open as u}from"./lib/events.mjs";import{warn as s}from"./lib/warn.mjs";async function w(r){const t=c(r),o={endpoints:t.endpoints,transport:t.transport??f,servers:new Set,warned:new Set,events:m(t.onEvent),textOnly:new Set,jsonInstruction:new Set,cursors:new Map,front:void 0};u(o.events,t.logs);const e=await l();e.errors.canvas&&s(t,o,`@napi-rs/canvas could not be loaded (${e.errors.canvas}); PDFs will be read as text only, without page images`,{type:"detect",kind:"canvas",reason:String(e.errors.canvas)}),e.errors.unpdf&&s(t,o,`unpdf could not be loaded (${e.errors.unpdf}); PDF documents cannot be read and fall back to a note`,{type:"detect",kind:"unpdf",reason:String(e.errors.unpdf)});const n=await p({...r.slothlet,base:d(new URL("./api",import.meta.url)),mode:"eager",context:{config:t,state:o},silent:!0});return await n.detect({network:t.detect}),n}a(w,"createTranslator");import{TranslatorError as D}from"./lib/errors.mjs";var P=w;export{D as TranslatorError,w as createTranslator,P as default};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/lib/cli.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var c=(t,e)=>_(t,"name",{value:e,configurable:!0});import{readFile as d}from"node:fs/promises";import{parseArgs as g}from"node:util";const u=`llm-translator - run Claude Code (or any Anthropic/OpenAI client) against local LLM servers
|
|
2
2
|
|
|
3
3
|
Usage: llm-translator --upstream <url> [options]
|
|
4
4
|
|
|
@@ -13,7 +13,8 @@ Options:
|
|
|
13
13
|
--api-key <key> Key clients must send (x-api-key or Authorization: Bearer)
|
|
14
14
|
--allow-unauthenticated Allow a non-loopback --host without --api-key
|
|
15
15
|
--config <file> JSON config file (translator config plus a "server" object)
|
|
16
|
-
--
|
|
16
|
+
--logs [path] Log warnings and errors to the console (default), or append every event as a JSON line to <path>
|
|
17
|
+
--silent Same as logs: false (no console output, no file)
|
|
17
18
|
--no-detect Skip upstream detection
|
|
18
19
|
--version Print the version
|
|
19
20
|
--help Print this help
|
|
@@ -21,9 +22,9 @@ Options:
|
|
|
21
22
|
Environment: LLM_TRANSLATOR_FRONT, LLM_TRANSLATOR_UPSTREAM, LLM_TRANSLATOR_UPSTREAM_KEY, LLM_TRANSLATOR_BACKEND,
|
|
22
23
|
LLM_TRANSLATOR_HOST, LLM_TRANSLATOR_PORT, LLM_TRANSLATOR_API_KEY, LLM_TRANSLATOR_ALLOW_UNAUTHENTICATED (1), LLM_TRANSLATOR_CONFIG. Flags win over the
|
|
23
24
|
environment, which wins over the config file.
|
|
24
|
-
`;function
|
|
25
|
-
`),"out"),err:
|
|
26
|
-
`),"err"),onSignal:
|
|
25
|
+
`;function S(t){const e=t.map((o,l)=>o==="--logs"&&(l===t.length-1||t[l+1].startsWith("-"))?"--logs=":o);return g({args:e,allowPositionals:!1,options:{front:{type:"string"},upstream:{type:"string",multiple:!0},"upstream-key":{type:"string"},backend:{type:"string"},model:{type:"string",multiple:!0},host:{type:"string"},port:{type:"string"},"api-key":{type:"string"},"allow-unauthenticated":{type:"boolean"},config:{type:"string"},logs:{type:"string"},silent:{type:"boolean"},"no-detect":{type:"boolean"},version:{type:"boolean"},help:{type:"boolean"}}}).values}c(S,"parse");function h(t,e,o){const{server:l,...p}=o,s=t.upstream??(e.LLM_TRANSLATOR_UPSTREAM?e.LLM_TRANSLATOR_UPSTREAM.split(","):void 0),r={...p};if(s){const i=t["upstream-key"]??e.LLM_TRANSLATOR_UPSTREAM_KEY,a=t.backend??e.LLM_TRANSLATOR_BACKEND;r.upstreams=s.map(n=>({url:n,apiKey:i,...a?{backend:a}:{}}))}const T=t.front??e.LLM_TRANSLATOR_FRONT;if(T&&(r.front=T),t.model){r.aliases={...r.aliases};for(const i of t.model){const a=i.indexOf("=");if(a<1)throw new Error(`--model expects alias=target (got "${i}")`);r.aliases[i.slice(0,a)]=i.slice(a+1)}}t.silent&&(r.logs=!1),t.logs!==void 0&&(r.logs=t.logs===""?!0:t.logs),r.logs??=r.silent!==!0,delete r.silent,t["no-detect"]&&(r.detect=!1);const A=t.port??e.LLM_TRANSLATOR_PORT,L={...l,...t.host??e.LLM_TRANSLATOR_HOST?{host:t.host??e.LLM_TRANSLATOR_HOST}:{},...A?{port:Number(A)}:{},...t["api-key"]??e.LLM_TRANSLATOR_API_KEY?{apiKey:t["api-key"]??e.LLM_TRANSLATOR_API_KEY}:{},...t["allow-unauthenticated"]||e.LLM_TRANSLATOR_ALLOW_UNAUTHENTICATED==="1"?{allowUnauthenticated:!0}:{}};return{translator:r,server:L}}c(h,"merge");const y={out:c(t=>process.stdout.write(`${t}
|
|
26
|
+
`),"out"),err:c(t=>process.stderr.write(`${t}
|
|
27
|
+
`),"err"),onSignal:c(t=>{process.once("SIGINT",t),process.once("SIGTERM",t)},"onSignal")};async function w(t,e=process.env,o=y,l={}){let p;try{p=S(t)}catch(s){return o.err(`${s.message}
|
|
27
28
|
|
|
28
|
-
${u}`),2}if(p.help)return
|
|
29
|
+
${u}`),2}if(p.help)return o.out(u),0;if(p.version)return o.out(l.version??(await import("../../package.json",{with:{type:"json"}})).default.version),0;try{const s=p.config??e.LLM_TRANSLATOR_CONFIG,{translator:r,server:T}=h(p,e,s?JSON.parse(await d(s,"utf8")):{}),L=await(l.createTranslator??(await import("../index.mjs")).createTranslator)(r),i=await L.server.start(T),a=L.status();o.out(`llm-translator (${a.front} front) listening on ${i.url}`);for(const n of a.upstreams??[]){const f=n.version??"unknown",m=n.probed?.inlineSystem??"auto",R=n.probed?.images??"default";o.out(` upstream ${n.name} ${n.url}: driver=${n.driver} version=${f} inlineSystem=${m} images=${R}`)}return await new Promise(n=>o.onSignal(()=>n())),await L.server.stop(),await L.slothlet.shutdown(),0}catch(s){return o.err(`llm-translator: ${s.message}`),1}}c(w,"main");export{w as main,h as merge,S as parse,y as processIo};
|
|
29
30
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/lib/config.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var i=Object.defineProperty;var n=(t,r)=>i(t,"name",{value:r,configurable:!0});import{TranslatorError as o}from"./errors.mjs";import*as a from"./pool.mjs";import{normalizeAliases as l,normalizeEfforts as u}from"./effort.mjs";function p(t){let r=t.length;for(;t[r-1]==="/";)r--;const e=t.slice(0,r);return e.endsWith("/v1")?e.slice(0,-3):e}n(p,"baseUrl");function d(t,r){const e=typeof t=="string"?{url:t}:t;if(!e||typeof e!="object"||typeof e.url!="string"||e.url==="")throw new o(`upstreams[${r}] needs a "url"`,{code:"INVALID_CONFIG",status:500});return{name:e.name??`upstream-${r}`,url:p(e.url),apiKey:e.apiKey,headers:{...e.headers},backend:e.backend??"auto",models:Array.isArray(e.models)?[...e.models]:void 0,default:e.default===!0,settings:{...e.settings},version:e.version,driver:null,facts:null,driverSettings:{},probed:{},health:a.health()}}n(d,"endpoint");function I(t={}){const r=t.front??"anthropic";if(r!=="anthropic"&&r!=="openai")throw new o(`front must be "anthropic" or "openai" (got ${JSON.stringify(r)})`,{code:"INVALID_CONFIG",status:500});let e=t.upstreams??t.upstream;if(e!==void 0&&!Array.isArray(e)&&(e=[e]),!e||e.length===0)throw new o("at least one upstream is required (config.upstreams)",{code:"INVALID_CONFIG",status:500});const s=t.logs??!1;if(typeof s!="boolean"&&(typeof s!="string"||s===""))throw new o("logs must be true, false or a file path (got "+JSON.stringify(s)+")",{code:"INVALID_CONFIG",status:500});if(t.onEvent!==void 0&&typeof t.onEvent!="function")throw new o("onEvent must be a function",{code:"INVALID_CONFIG",status:500});return{front:r,endpoints:e.map(d),...l(t.aliases),efforts:u(t.efforts),pool:a.normalize(t.pool),settings:{...t.settings},detect:t.detect!==!1,detectTimeout:t.detectTimeout??5e3,transport:t.transport,logs:s,events:t.events!==!1,onEvent:t.onEvent}}n(I,"normalize");export{d as endpoint,I as normalize};
|
|
2
2
|
//# sourceMappingURL=config.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var c=Object.defineProperty;var l=(t,f)=>c(t,"name",{value:f,configurable:!0});import{TranslatorError as g}from"./errors.mjs";const s=Object.freeze(["minimal","low","medium","high","xhigh","max"]);function u(t){return new g(t,{code:"INVALID_CONFIG",status:500})}l(u,"invalid");function k(t){const f={};for(const[i,n]of Object.entries(t??{})){const e=Array.isArray(n)?n:n?.levels;if(!Array.isArray(e)||e.length===0)throw u(`efforts.${i} must be a non-empty list of levels or { levels, default }`);for(const a of e)if(!s.includes(a))throw u(`efforts.${i}: unknown level ${JSON.stringify(a)} (expected ${s.join(", ")})`);const o=s.filter(a=>e.includes(a)),r=Array.isArray(n)?void 0:n.default;if(r!=null&&!o.includes(r))throw u(`efforts.${i}.default must be one of its levels or null (got ${JSON.stringify(r)})`);f[i]={levels:o,default:r}}return f}l(k,"normalizeEfforts");function v(t){const f={},i={};for(const[n,e]of Object.entries(t??{})){if(typeof e=="string"){f[n]=e;continue}if(e===null||typeof e!="object"||typeof e.model!="string")throw u(`aliases.${n} must be a model name or { model, effort, thinking }`);if(e.effort!==void 0&&!s.includes(e.effort))throw u(`aliases.${n}.effort must be one of ${s.join(", ")} (got ${JSON.stringify(e.effort)})`);if(e.thinking!==void 0&&typeof e.thinking!="boolean")throw u(`aliases.${n}.thinking must be true or false`);f[n]=e.model;const o={};e.effort!==void 0&&(o.effort=e.effort),e.thinking!==void 0&&(o.thinking=e.thinking),Object.keys(o).length>0&&(i[n]=o)}return{aliases:f,pins:i}}l(v,"normalizeAliases");function d(t,f){const i=s.indexOf(f);let n=t[0];for(const e of t){const o=Math.abs(s.indexOf(e)-i),r=Math.abs(s.indexOf(n)-i);(o<r||o===r&&s.indexOf(e)>s.indexOf(n))&&(n=e)}return n}l(d,"nearest");function h(t){return t.default===void 0?d(t.levels,"medium"):t.default}l(h,"defaultOf");function x(t,f,i){const n={...t};return i==="openai"?(f.effort!==void 0&&(n.reasoning_effort=f.effort),f.thinking===!1?n.reasoning_effort="none":f.thinking===!0&&n.reasoning_effort==="none"&&delete n.reasoning_effort,n):(f.effort!==void 0&&(n.output_config={...t.output_config,effort:f.effort}),f.thinking===!1?n.thinking={type:"disabled"}:f.thinking===!0&&(t.thinking===void 0||t.thinking?.type==="disabled")&&(n.thinking={type:"adaptive"}),n)}l(x,"pinBody");function $(t,f,i,n){if(t.reasoning_effort==="none"||t.chat_template_kwargs?.enable_thinking===!1)return;const e=t.reasoning_effort;if(e==null){const r=h(f);r!==null&&(t.reasoning_effort=r);return}if(f.levels.includes(e)||!s.includes(e))return;const o=d(f.levels,e);n(`Effort "${e}" is not supported by ${i} (${f.levels.join(", ")}); using "${o}".`,{requested:e,used:o,levels:[...f.levels]}),t.reasoning_effort=o}l($,"fit");export{s as LEVELS,h as defaultOf,$ as fit,d as nearest,v as normalizeAliases,k as normalizeEfforts,x as pinBody};
|
|
2
|
+
//# sourceMappingURL=effort.mjs.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var m=Object.defineProperty;var s=(n,e)=>m(n,"name",{value:e,configurable:!0});import{closeSync as h,mkdirSync as $,openSync as k,appendFileSync as S}from"node:fs";import d from"node:path";function J(n){const e=new Map;return typeof n=="function"&&e.set("*",new Set([n])),{listeners:e,sink:{console:!1,file:null},logger:null}}s(J,"create");function M(n,e){if(n.sink.console=e===!0,n.sink.file=null,typeof e!="string")return;const o=d.resolve(e);try{$(d.dirname(o),{recursive:!0}),h(k(o,"a")),n.sink.file=o}catch(r){console.warn(`[llm-translator] could not open the log file ${o} (${r.message}); logging is off`)}}s(M,"open");function N(n,e,o){if(typeof e!="string"||typeof o!="function")throw new TypeError("events.on needs an event name and a function");return n.listeners.has(e)||n.listeners.set(e,new Set),n.listeners.get(e).add(o),()=>v(n,e,o)}s(N,"on");function v(n,e,o){n.listeners.get(e)?.delete(o)}s(v,"off");function u(n,e,o){const{sink:r}=n.events;if((o===!1?null:o??n.events.logger)?.[e.level]?.({event:e},e.message),r.console&&(e.level==="warn"||e.level==="error")&&!n.warned.has(e.message)&&(n.warned.add(e.message),console[e.level==="error"?"error":"warn"](`[llm-translator] ${e.message}`)),r.file!==null)try{S(r.file,`${JSON.stringify(e)}
|
|
2
|
+
`)}catch(i){const f=r.file;r.file=null,console.warn(`[llm-translator] could not write the log file ${f} (${i.message}); file logging is off`)}}s(u,"write");function g(n,e,o){const r=`Event listener for "${e}" failed: ${o?.message??o}`,l=`listener
|
|
3
|
+
${r}`;n.warned.has(l)||(n.warned.add(l),u(n,{type:"listener",level:"warn",message:r,time:Date.now(),event:e},!1))}s(g,"failed");function x(n,e,o,r){try{const l=o(r);typeof l?.then=="function"&&l.then(void 0,i=>g(n,e,i))}catch(l){g(n,e,l)}}s(x,"call");function O({config:n,state:e},o){const{type:r,kind:l,level:i="info",message:f,log:p,...w}=o,a={type:r,...l===void 0?{}:{kind:l},level:i,message:f,time:Date.now(),...w};if(n.events!==!1){const t=new Set([r]);i==="warn"&&t.add("warning"),i==="error"&&t.add("error"),t.add("log"),t.add("*");for(const c of t)for(const y of[...e.events.listeners.get(c)??[]])x(e,c,y,a)}return u(e,a,p),a}s(O,"emit");export{J as create,O as emit,v as off,N as on,M as open};
|
|
4
|
+
//# sourceMappingURL=events.mjs.map
|
package/dist/lib/finish.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _=Object.defineProperty;var
|
|
1
|
+
var _=Object.defineProperty;var r=(t,e)=>_(t,"name",{value:e,configurable:!0});const p={abort:{type:"api_error",status:502},aborted:{type:"api_error",status:502},error:{type:"api_error",status:502},insufficient_system_resource:{type:"overloaded_error",status:503}};function l(t){if(typeof t!="string"||!Object.hasOwn(p,t))return null;const{type:e,status:o}=p[t];return{type:e,status:o,code:"upstream_finish_"+t,message:`Upstream ended the response with finish_reason "${t}"`}}r(l,"finishError");function a(t,{hasToolCalls:e,matchedStop:o,argumentsComplete:s=!0,refusal:n}){return e&&(t!=="length"&&t!=="model_length"||s)?{stop_reason:"tool_use",stop_sequence:null}:t==="length"||t==="model_length"?{stop_reason:"max_tokens",stop_sequence:null}:t==="content_filter"?{stop_reason:"refusal",stop_sequence:null,stop_details:{type:"refusal",category:null,explanation:typeof n=="string"&&n!==""?n:null}}:typeof o=="string"&&o!==""?{stop_reason:"stop_sequence",stop_sequence:o}:{stop_reason:"end_turn",stop_sequence:null}}r(a,"toAnthropicStop");function i(t){switch(t){case"max_tokens":return"length";case"tool_use":return"tool_calls";case"refusal":return"content_filter";default:return"stop"}}r(i,"toOpenAIFinish");function k(t){const e=t?.prompt_tokens??0,o=t?.prompt_tokens_details?.cached_tokens??0;return{input_tokens:Math.max(0,e-o),output_tokens:t?.completion_tokens??0,cache_creation_input_tokens:0,cache_read_input_tokens:o}}r(k,"toAnthropicUsage");function d(t){const e=t?.cache_read_input_tokens??0,o=(t?.input_tokens??0)+e+(t?.cache_creation_input_tokens??0),s=t?.output_tokens??0,n={prompt_tokens:o,completion_tokens:s,total_tokens:o+s};return e>0&&(n.prompt_tokens_details={cached_tokens:e}),n}r(d,"toOpenAIUsage");export{l as finishError,a as toAnthropicStop,k as toAnthropicUsage,i as toOpenAIFinish,d as toOpenAIUsage};
|
|
2
2
|
//# sourceMappingURL=finish.mjs.map
|
package/dist/lib/route.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var u=(e,n)=>m(e,"name",{value:n,configurable:!0});import{TranslatorError as f}from"./errors.mjs";import{order as v}from"./pool.mjs";function h(e,n){return(e.models??e.facts?.models??[]).includes(n)?!0:e.protocol==="anthropic.messages"&&e.models===void 0&&/^claude-/.test(n)}u(h,"serves");function w(e,n,t,o,i=!1){const a=Object.hasOwn(e.aliases,t),r=a?e.aliases[t]:t,l=a&&Object.hasOwn(e.pins,t)?e.pins[t]:void 0,c=n.filter(d=>h(d,r)),s=n.find(d=>d.default)??n[0];if(c.length>0){const d=v(e,o,c,r,i);return{endpoint:d[0],model:r,unserved:!1,pool:d,pin:l}}const p=s.models??s.facts?.models??[];return p.length===1?{endpoint:s,model:p[0],unserved:!1,pool:[s],pin:l}:{endpoint:s,model:r,unserved:!0,pool:[s],pin:l}}u(w,"pick");function _(e,n,t={}){if(!n||typeof n!="object"||Array.isArray(n))throw new f("The request body must be a JSON object",{code:"invalid_body",status:400});const o=w(e.config,e.state.endpoints,n.model,e.state,t.advance===!0);if(t.endpoint!==void 0){const r=o.pool.find(l=>l.name===t.endpoint);if(!r)throw new f(`Endpoint ${t.endpoint} no longer serves ${o.model}`,{code:"endpoint_not_in_pool",status:500});return{endpoint:r,model:o.model,requested:n.model,unserved:o.unserved,pin:o.pin,convert:e.converters(r),pool:[r]}}const{endpoint:i,pool:a}=o;return{endpoint:i,model:o.model,requested:n.model,unserved:o.unserved,pin:o.pin,convert:e.converters(i),pool:a}}u(_,"resolve");export{w as pick,_ as resolve,h as serves};
|
|
2
2
|
//# sourceMappingURL=route.mjs.map
|