gitnexus 1.6.4-rc.81 → 1.6.4-rc.83
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/package.json +1 -1
- package/web/assets/{agent-BR6JgzUS.js → agent-DGm5BiXg.js} +2 -2
- package/web/assets/architecture-YZFGNWBL-S5CXDPWN-CzpqonpT.js +1 -0
- package/web/assets/{architectureDiagram-EMZXCZ2Q-DdOrld62.js → architectureDiagram-EMZXCZ2Q-DLWvvvUB.js} +1 -1
- package/web/assets/{blockDiagram-IGV67L2C-DBbcDJE6.js → blockDiagram-IGV67L2C-B47EUMKY.js} +1 -1
- package/web/assets/{c4Diagram-DFAF54RM-BI-8yWq5.js → c4Diagram-DFAF54RM-DvvVQASF.js} +1 -1
- package/web/assets/{chunk-3GS5O3IE-DnMyU1lf.js → chunk-3GS5O3IE-0H2zS7RE.js} +1 -1
- package/web/assets/{chunk-3YCYZ6SJ-BZslrNTQ.js → chunk-3YCYZ6SJ-DokVoiwM.js} +1 -1
- package/web/assets/{chunk-6NTNNK5N-Y67ka-rU.js → chunk-6NTNNK5N-B9jhOxT0.js} +1 -1
- package/web/assets/{chunk-A34GCYZU-ClNpO7ap.js → chunk-A34GCYZU-DfTldqlz.js} +1 -1
- package/web/assets/{chunk-DJ7UZH7F-tYXU3fBz.js → chunk-DJ7UZH7F-npvsBmvn.js} +1 -1
- package/web/assets/{chunk-DKKBVRCY-DfGJMrSz.js → chunk-DKKBVRCY-DbFEYV2a.js} +2 -2
- package/web/assets/{chunk-DU5LTGQ6-qCXmLiFZ.js → chunk-DU5LTGQ6-B1Mj73sD.js} +1 -1
- package/web/assets/{chunk-FXACKDTF-D-WiQLyP.js → chunk-FXACKDTF-CNljDI1M.js} +1 -1
- package/web/assets/{chunk-H3VCZNTA-D3vbWWyQ.js → chunk-H3VCZNTA-j4ZGeRTZ.js} +1 -1
- package/web/assets/{chunk-HN6EAY2L-CQC4-xpr.js → chunk-HN6EAY2L-CEc2xC-J.js} +1 -1
- package/web/assets/{chunk-O5ABG6QK-CqQgDXv5.js → chunk-O5ABG6QK-B_00CmQB.js} +1 -1
- package/web/assets/{chunk-PK6DOVAG-BCVBr6ZD.js → chunk-PK6DOVAG-lOMJKFOu.js} +1 -1
- package/web/assets/{chunk-RNJOYNJ4-Bs1qBdCE.js → chunk-RNJOYNJ4-BKKlhT6X.js} +1 -1
- package/web/assets/{chunk-RWUO3TPN-eG5qgc5e.js → chunk-RWUO3TPN-BhUzGpFd.js} +1 -1
- package/web/assets/{chunk-TBF5ZNIQ-CzrYvTQC.js → chunk-TBF5ZNIQ-BAsGZFMI.js} +1 -1
- package/web/assets/{chunk-TYMNRAUI-BBuddluh.js → chunk-TYMNRAUI-B47lwFjp.js} +1 -1
- package/web/assets/{chunk-W7ZLLLMY-JfkpG9pC.js → chunk-W7ZLLLMY-DGb6u0pB.js} +1 -1
- package/web/assets/{chunk-WSB5WSVC-BSmELgSM.js → chunk-WSB5WSVC-BiaAMFmd.js} +1 -1
- package/web/assets/{chunk-XGPFEOL4-CmPwWVXe.js → chunk-XGPFEOL4-Dqk5iHgi.js} +1 -1
- package/web/assets/classDiagram-PPOCWD7C-W4Gq4oYa.js +1 -0
- package/web/assets/classDiagram-v2-23LJLIIU-CbyGxpD-.js +1 -0
- package/web/assets/{cose-bilkent-PNC4W37J-B2PBKVII.js → cose-bilkent-PNC4W37J-CnOlxR0_.js} +1 -1
- package/web/assets/{dagre-E77IOHMT-DOJQpMhU.js → dagre-E77IOHMT-Cy3z5r06.js} +1 -1
- package/web/assets/{diagram-H7BISOXX-BwuBSflT.js → diagram-H7BISOXX-ChLdgktB.js} +1 -1
- package/web/assets/{diagram-JC5VWROH-RUxO3qvC.js → diagram-JC5VWROH-DdzGpm08.js} +1 -1
- package/web/assets/{diagram-LXUTUG65-DL3slkcr.js → diagram-LXUTUG65-Bq_ye_lS.js} +1 -1
- package/web/assets/{diagram-WEHSV5V5-D-xIWqCV.js → diagram-WEHSV5V5-WrNO_VoZ.js} +1 -1
- package/web/assets/{erDiagram-GCSMX5X6-BsNUcWxA.js → erDiagram-GCSMX5X6-Cx3Aq4SN.js} +1 -1
- package/web/assets/{flowDiagram-OTCZ4VVT-Dez0Lj1Y.js → flowDiagram-OTCZ4VVT-DRe-9T0b.js} +1 -1
- package/web/assets/{ganttDiagram-MUNLMDZQ-ChSXA0kN.js → ganttDiagram-MUNLMDZQ-CvtFMhi8.js} +1 -1
- package/web/assets/gitGraph-7Q5UKJZL-54BCDZD5-DZfbulFG.js +1 -0
- package/web/assets/{gitGraphDiagram-3HKGZ4G3-8iHl9xKL.js → gitGraphDiagram-3HKGZ4G3-BxDd7tFR.js} +1 -1
- package/web/assets/{index-DnjscxVd.js → index-ChQJsgDb.js} +5 -5
- package/web/assets/info-OMHHGYJF-BF2H5H6G-Dehqc8IA.js +1 -0
- package/web/assets/infoDiagram-MN7RKWGX-B0B5J4EY.js +2 -0
- package/web/assets/{ishikawaDiagram-YMYX4NHK-BPFoHRQ-.js → ishikawaDiagram-YMYX4NHK-TUICrJKY.js} +1 -1
- package/web/assets/{journeyDiagram-SO5T7YLQ-DVRJpEUc.js → journeyDiagram-SO5T7YLQ-C4Y1ypn8.js} +1 -1
- package/web/assets/{kanban-definition-LJHFXRCJ-DOUCiWuN.js → kanban-definition-LJHFXRCJ--cIG9jHd.js} +1 -1
- package/web/assets/{mindmap-definition-2EUWGEK5-BNXeeUBG.js → mindmap-definition-2EUWGEK5-BK54zuWp.js} +1 -1
- package/web/assets/packet-4T2RLAQJ-EV4IVRXR-BjetiCTk.js +1 -0
- package/web/assets/pie-ZZUOXDRM-N23DN5KN-zkxhGq7v.js +1 -0
- package/web/assets/{pieDiagram-3IATQBI2-6ktwo7Jm.js → pieDiagram-3IATQBI2-CMgPhL6Y.js} +1 -1
- package/web/assets/{quadrantDiagram-E256RVCF-Ckf5RsLj.js → quadrantDiagram-E256RVCF-CNmFSP0m.js} +1 -1
- package/web/assets/radar-PYXPWWZC-P6TP7ZYP-CHxbGrvk.js +1 -0
- package/web/assets/{requirementDiagram-M5DCFWZL-OMiwzJCW.js → requirementDiagram-M5DCFWZL-C6e8zmrF.js} +1 -1
- package/web/assets/{sankeyDiagram-L3NBLAOT-Bu3q2oR9.js → sankeyDiagram-L3NBLAOT-BDcHIgVE.js} +1 -1
- package/web/assets/{sequenceDiagram-ZOUHS735-CCaepW8A.js → sequenceDiagram-ZOUHS735-CGAlp5GL.js} +1 -1
- package/web/assets/{stateDiagram-MLPALWAM-D0pPSUeb.js → stateDiagram-MLPALWAM-CCKt0fuW.js} +1 -1
- package/web/assets/stateDiagram-v2-B5LQ5ZB2-OC7lFsht.js +1 -0
- package/web/assets/{timeline-definition-5SPVSISX-Bnt0tSZA.js → timeline-definition-5SPVSISX-D74jeyVQ.js} +1 -1
- package/web/assets/treeView-SZITEDCU-5DXDK3XO-8EO9YZIQ.js +1 -0
- package/web/assets/treemap-W4RFUUIX-WYLRDWKO-y8YnclBi.js +1 -0
- package/web/assets/{vennDiagram-IE5QUKF5-D1QPXqvM.js → vennDiagram-IE5QUKF5-ChHw0kJO.js} +1 -1
- package/web/assets/wardley-RL74JXVD-BCRCBASE-1QZagPhJ.js +1 -0
- package/web/assets/{wardleyDiagram-XU3VSMPF-DgVu-8V0.js → wardleyDiagram-XU3VSMPF-D5PsSVSp.js} +1 -1
- package/web/assets/{xychartDiagram-ZHJ5623Y-DY2IlISC.js → xychartDiagram-ZHJ5623Y-B7E396Z-.js} +1 -1
- package/web/index.html +1 -1
- package/web/assets/architecture-YZFGNWBL-S5CXDPWN-DJAeZ1fZ.js +0 -1
- package/web/assets/classDiagram-PPOCWD7C-CaCJnkFe.js +0 -1
- package/web/assets/classDiagram-v2-23LJLIIU-wdvhnHkq.js +0 -1
- package/web/assets/gitGraph-7Q5UKJZL-54BCDZD5-DkYkEmdA.js +0 -1
- package/web/assets/info-OMHHGYJF-BF2H5H6G-C3e2WXUC.js +0 -1
- package/web/assets/infoDiagram-MN7RKWGX-CIHfQ_Ot.js +0 -2
- package/web/assets/packet-4T2RLAQJ-EV4IVRXR-_hVXeTya.js +0 -1
- package/web/assets/pie-ZZUOXDRM-N23DN5KN-Cwk3Ms79.js +0 -1
- package/web/assets/radar-PYXPWWZC-P6TP7ZYP-BuQ3fcO-.js +0 -1
- package/web/assets/stateDiagram-v2-B5LQ5ZB2-DQ0mfMOw.js +0 -1
- package/web/assets/treeView-SZITEDCU-5DXDK3XO-B2JHGeuB.js +0 -1
- package/web/assets/treemap-W4RFUUIX-WYLRDWKO-BKeOEBXU.js +0 -1
- package/web/assets/wardley-RL74JXVD-BCRCBASE-DLAazngR.js +0 -1
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as e,t}from"./chunk-CilyBKbf.js";import{n,t as r}from"./index-
|
|
1
|
+
import{r as e,t}from"./chunk-CilyBKbf.js";import{n,t as r}from"./index-ChQJsgDb.js";import{buildDynamicSystemPrompt as i}from"./context-builder-CqQNhRj1.js";var a=Object.defineProperty,o=(e,t)=>{let n={};for(var r in e)a(n,r,{get:e[r],enumerable:!0});return t||a(n,Symbol.toStringTag,{value:`Module`}),n};function s(e){let t=Symbol.for(e);return{brand(n,r){let i=r?Symbol.for(`${e}.${r}`):t;class a extends n{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return typeof e==`object`&&!!e&&i in e&&e[i]===!0}}return Object.defineProperty(a,`name`,{value:n.name}),a},sub(t){return s(`${e}.${t}`)},isInstance(e){return typeof e==`object`&&!!e&&t in e&&e[t]===!0}}}var c=s(`langchain`),l=o({ContextOverflowError:()=>m,LangChainError:()=>f,ModelAbortError:()=>p,addLangChainErrorFields:()=>u,ns:()=>d});function u(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}var d=c.sub(`error`),f=class extends d.brand(Error){name=`LangChainError`;constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},p=class extends d.brand(f,`model-abort`){name=`ModelAbortError`;partialOutput;constructor(e,t){super(e),this.partialOutput=t}},m=class e extends d.brand(f,`context-overflow`){name=`ContextOverflowError`;cause;constructor(e){super(e??`Input exceeded the model's context window.`)}static fromError(t){let n=new e(t.message);return n.cause=t,n}};function h(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`tool_call`)}function g(e){return!!(e&&typeof e==`object`&&`toolCall`in e&&e.toolCall!=null&&typeof e.toolCall==`object`&&`id`in e.toolCall&&typeof e.toolCall.id==`string`)}var _=class extends Error{output;constructor(e,t){super(e),this.output=t}};function v(e,t=b){e=e.trim();let n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
|
|
2
2
|
`)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
|
|
3
3
|
`)&&(r=r.substring(1));let i=r.indexOf("```"),a=r;return i!==-1&&(a=r.substring(0,i)),t(a.trim())}function y(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw Error(`Unexpected end of JSON input`);let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function i(){if(t[n]!==`"`)throw Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e=``,r=!1;for(;n<t.length;){let i=t[n];if(r){if(i===`n`)e+=`
|
|
4
4
|
`;else if(i===`t`)e+=` `;else if(i===`r`)e+=`\r`;else if(i===`\\`)e+=`\\`;else if(i===`"`)e+=`"`;else if(i===`b`)e+=`\b`;else if(i===`f`)e+=`\f`;else if(i===`/`)e+=`/`;else if(i===`u`){let r=t.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(r))r.length===4?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length;else throw Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${n}`);r=!1}else if(i===`\\`)r=!0;else if(i===`"`)return n+=1,e;else e+=i;n+=1}return r&&(e+=`\\`),e}function a(){let e=n,r=``;if(t[n]===`-`&&(r+=`-`,n+=1),n<t.length&&t[n]===`0`&&(r+=`0`,n+=1,t[n]>=`0`&&t[n]<=`9`))throw Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>=`1`&&t[n]<=`9`)for(;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&t[n]===`.`)for(r+=`.`,n+=1;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&(t[n]===`e`||t[n]===`E`))for(r+=t[n],n+=1,n<t.length&&(t[n]===`+`||t[n]===`-`)&&(r+=t[n],n+=1);n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(r===`-`)return-0;let i=Number.parseFloat(r);if(Number.isNaN(i))throw n=e,Error(`Invalid number '${r}' at position ${e}`);return i}function o(){if(r(),n>=t.length)throw Error(`Unexpected end of input at position ${n}`);let e=t[n];if(e===`{`)return c();if(e===`[`)return s();if(e===`"`)return i();if(`null`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if(`true`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if(`false`.startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if(e===`-`||e>=`0`&&e<=`9`)return a();throw Error(`Unexpected character '${e}' at position ${n}`)}function s(){if(t[n]!==`[`)throw Error(`Expected '[' at position ${n}, got '${t[n]}'`);let e=[];if(n+=1,r(),n>=t.length)return e;if(t[n]===`]`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length||(e.push(o()),r(),n>=t.length))return e;if(t[n]===`]`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`)}return e}function c(){if(t[n]!==`{`)throw Error(`Expected '{' at position ${n}, got '${t[n]}'`);let e={};if(n+=1,r(),n>=t.length)return e;if(t[n]===`}`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length)return e;let a=i();if(r(),n>=t.length)return e;if(t[n]!==`:`)throw Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length||(e[a]=o(),r(),n>=t.length))return e;if(t[n]===`}`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`)}return e}let l=o();if(r(),n<t.length)throw Error(`Unexpected character '${t[n]}' at position ${n}`);return l}function b(e){try{return e===void 0?null:y(e)}catch{return null}}var ee=t(((e,t)=>{t.exports=function(e,t){if(typeof e!=`string`)throw TypeError(`Expected a string`);return t=t===void 0?`_`:t,e.replace(/([a-z\d])([A-Z])/g,`$1`+t+`$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1`+t+`$2`).toLowerCase()}})),x=t(((e,t)=>{var n=/[\p{Lu}]/u,r=/[\p{Ll}]/u,i=/^[\p{Lu}](?![\p{Lu}])/gu,a=/([\p{Alpha}\p{N}_]|$)/u,o=/[_.\- ]+/,s=RegExp(`^`+o.source),c=new RegExp(o.source+a.source,`gu`),l=RegExp(`\\d+`+a.source,`gu`),u=(e,t,i)=>{let a=!1,o=!1,s=!1;for(let c=0;c<e.length;c++){let l=e[c];a&&n.test(l)?(e=e.slice(0,c)+`-`+e.slice(c),a=!1,s=o,o=!0,c++):o&&s&&r.test(l)?(e=e.slice(0,c-1)+`-`+e.slice(c-1),s=o,o=!1,a=!0):(a=t(l)===l&&i(l)!==l,s=o,o=i(l)===l&&t(l)!==l)}return e},d=(e,t)=>(i.lastIndex=0,e.replace(i,e=>t(e))),f=(e,t)=>(c.lastIndex=0,l.lastIndex=0,e.replace(c,(e,n)=>t(n)).replace(l,e=>t(e))),p=(e,t)=>{if(!(typeof e==`string`||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join(`-`):e.trim(),e.length===0)return``;let n=t.locale===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),r=t.locale===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?r(e):n(e):(e!==n(e)&&(e=u(e,n,r)),e=e.replace(s,``),e=t.preserveConsecutiveUppercase?d(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),f(e,r))};t.exports=p,t.exports.default=p})),te=e(ee(),1),S=e(x(),1);function ne(e,t){return t?.[e]||(0,te.default)(e)}function re(e,t){return t?.[e]||(0,S.default)(e)}function ie(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var ae=`__lc_escaped__`;function oe(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function se(e){return{[ae]:e}}function ce(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function C(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function le(e){let t;return t=typeof e==`object`&&e?`lc_id`in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??`Object`]:[typeof e],{lc:1,type:`not_implemented`,id:t}}function ue(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return le(e);if(C(e))return e;t.add(e);let n=e;if(oe(n))return t.delete(e),se(n);let r={};for(let[e,i]of Object.entries(n))r[e]=ue(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>ue(e,t)):e}function de(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(ce(t))return t[ae];let n={};for(let[e,r]of Object.entries(t))n[e]=de(r);return n}return Array.isArray(e)?e.map(e=>de(e)):e}var fe=o({Serializable:()=>ge,get_lc_unique_name:()=>he});function pe(e){return Array.isArray(e)?[...e]:{...e}}function me(e,t){let n=pe(e);for(let[e,r]of Object.entries(t)){let[t,...i]=e.split(`.`).reverse(),a=n;for(let e of i.reverse()){if(a[e]===void 0)break;a[e]=pe(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function he(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name==`function`&&(typeof t.lc_name!=`function`||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var ge=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,he(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){this.lc_serializable_keys===void 0?this.lc_kwargs=e??{}:this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e)))}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||typeof this.lc_kwargs!=`object`||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},n={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,`lc_aliases`,this)),Object.assign(n,Reflect.get(e,`lc_secrets`,this)),Object.assign(r,Reflect.get(e,`lc_attributes`,this));Object.keys(n).forEach(e=>{let t=this,n=r,[i,...a]=e.split(`.`).reverse();for(let e of a.reverse()){if(!(e in t)||t[e]===void 0)return;(!(e in n)||n[e]===void 0)&&(typeof t[e]==`object`&&t[e]!=null?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&t[i]!==void 0&&(n[i]=n[i]||t[i])});let i={},a=new WeakSet;a.add(this);for(let[e,t]of Object.entries(r))i[e]=ue(t,a);let o=ie(Object.keys(n).length?me(i,n):i,ne,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function _e(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&`source_type`in e&&(e.source_type===`url`||e.source_type===`base64`||e.source_type===`text`||e.source_type===`id`)}function ve(e){return _e(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function ye(e){return _e(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function be(e){return _e(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function xe(e){return _e(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function Se(e){if(_e(e)){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url}};if(e.source_type===`base64`){if(!e.mime_type)throw Error(`mime_type key is required for base64 data.`);return{type:`image_url`,image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error(`Unsupported source type. Only 'url' and 'base64' are supported.`)}function Ce(e){let t=e.split(`;`)[0].split(`/`);if(t.length!==2)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let n=t[0].trim(),r=t[1].trim();if(n===``||r===``)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let t of e.split(`;`).slice(1)){let n=t.split(`=`);if(n.length!==2)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let r=n[0].trim(),a=n[1].trim();if(r===``)throw Error(`Invalid parameter syntax in mime type: "${e}".`);i[r]=a}return{type:n,subtype:r,parameters:i}}function we({dataUrl:e,asTypedArray:t=!1}){let n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function Te(e,t){if(e.type===`text`){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type===`image`){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type===`audio`){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type===`file`){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function w(e,t){return T(e)&&e.type===t}function T(e){return typeof e==`object`&&!!e}function Ee(e){return Array.isArray(e)}function E(e){return typeof e==`string`}function De(e){return typeof e==`number`}function Oe(e){return e instanceof Uint8Array}function D(e){try{return JSON.parse(e)}catch{return}}var ke=e=>e();function Ae(e){if(e.type===`char_location`&&E(e.document_title)&&De(e.start_char_index)&&De(e.end_char_index)&&E(e.cited_text)){let{document_title:t,start_char_index:n,end_char_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`char`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`page_location`&&E(e.document_title)&&De(e.start_page_number)&&De(e.end_page_number)&&E(e.cited_text)){let{document_title:t,start_page_number:n,end_page_number:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`page`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`content_block_location`&&E(e.document_title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(e.cited_text)){let{document_title:t,start_block_index:n,end_block_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`block`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`web_search_result_location`&&E(e.url)&&E(e.title)&&E(e.encrypted_index)&&E(e.cited_text)){let{url:t,title:n,encrypted_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`url`,url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(e.type===`search_result_location`&&E(e.source)&&E(e.title)&&De(e.start_block_index)&&De(e.end_block_index)&&E(e.cited_text)){let{source:t,title:n,start_block_index:r,end_block_index:i,cited_text:a,...o}=e;return{...o,type:`citation`,source:`search`,url:t,title:n??void 0,startIndex:r,endIndex:i,citedText:a}}}function je(e){if(w(e,`document`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&E(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(w(e,`image`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Me(e){function*t(){for(let t of e){let e=je(t);e?yield e:yield t}}return Array.from(t())}function Ne(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){let{text:e,citations:t,...r}=n;if(Ee(t)&&t.length){let n=t.reduce((e,t)=>{let n=Ae(t);return n?[...e,n]:e},[]);yield{...r,type:`text`,text:e,annotations:n};continue}else{yield{...r,type:`text`,text:e};continue}}else if(w(n,`thinking`)&&E(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(w(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`tool_use`)&&E(n.name)&&E(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(w(n,`input_json_delta`)){if(Fe(e)&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(w(n,`server_tool_use`)&&E(n.name)&&E(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.query))return n.input.query;if(E(n.partial_json)){let e=D(n.partial_json);if(e?.query)return e.query}return``})}};continue}else if(n.name===`code_execution`){yield{id:t,type:`server_tool_call`,name:`code_execution`,args:{code:ke(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.code))return n.input.code;if(E(n.partial_json)){let e=D(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(w(n,`web_search_tool_result`)&&E(n.tool_use_id)&&Ee(n.content)){let{content:e,tool_use_id:t}=n;yield{type:`server_tool_call_result`,name:`web_search`,toolCallId:t,status:`success`,output:{urls:e.reduce((e,t)=>w(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(w(n,`code_execution_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(w(n,`mcp_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`mcp_tool_use`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(w(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(w(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=je(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Pe={translateContent:Ne,translateContentChunk:Ne};function Fe(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Ie(e){return ve(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ye(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:xe(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Le(e){return e.map(Ie)}function Re(e){return!!(w(e,`image_url`)&&T(e.image_url)||w(e,`input_audio`)&&T(e.input_audio)||w(e,`file`)&&T(e.file))}function ze(e){if(w(e,`image_url`)&&T(e.image_url)&&E(e.image_url.url)){let t=we({dataUrl:e.image_url.url});return t?{type:`image`,mimeType:t.mime_type,data:t.data}:{type:`image`,url:e.image_url.url}}else if(w(e,`input_audio`)&&T(e.input_audio)&&E(e.input_audio.data)&&E(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(w(e,`file`)&&T(e.file)&&E(e.file.data)){let t=we({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(E(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function Be(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function Ve(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...He(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function He(e){let t=[];for(let n of e)Re(n)?t.push(ze(n)):t.push(n);return t}function Ue(e){if(e.type===`url_citation`){let{url:t,title:n,start_index:r,end_index:i}=e;return{type:`citation`,url:t,title:n,startIndex:r,endIndex:i}}if(e.type===`file_citation`){let{file_id:t,filename:n,index:r}=e;return{type:`citation`,title:n,startIndex:r,endIndex:r,fileId:t}}return e}function We(e){function*t(){T(e.additional_kwargs?.reasoning)&&Ee(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>T(t)&&E(t.text)?`${e}${t.text}`:e,``)});let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)if(w(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=T(i)?{...i}:{};E(r)&&(o.phase=r);let s=Object.keys(o).length>0?{extras:o}:{};Array.isArray(n)?yield{...a,...s,type:`text`,text:String(t),annotations:n.map(Ue)}:yield{...a,...s,type:`text`,text:String(t)}}for(let t of e.tool_calls??[])yield{type:`tool_call`,id:t.id,name:t.name,args:t.args};if(T(e.additional_kwargs)&&Ee(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(w(t,`web_search_call`)){let e={};if(T(t.action)&&E(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:`server_tool_call`,name:`web_search`,args:e},t.status===`completed`||t.status===`failed`){let e={};T(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(w(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:Ee(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:Ee(t.results)?{results:t.results}:{}});continue}else if(w(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`code_interpreter_call`)){if(E(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),Ee(t.outputs)){let e=ke(()=>{if(t.status!==`in_progress`){if(t.status===`completed`)return 0;if(t.status===`incomplete`)return 127;if(t.status!==`interpreting`&&t.status===`failed`)return 1}});for(let n of t.outputs)if(w(n,`logs`)){yield{type:`server_tool_call_result`,toolCallId:t.id??``,status:`success`,output:{type:`code_interpreter_output`,returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}continue}else if(w(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(w(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(w(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`tool_search_call`)){let e={};T(t.arguments)&&Object.assign(e,t.arguments);let n={};E(t.execution)&&(n.execution=t.execution),E(t.status)&&(n.status=t.status),E(t.call_id)&&(n.call_id=t.call_id),yield{id:E(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(w(t,`tool_search_output`)){let e={name:`tool_search`};E(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:Ee(t.tools)?t.tools:[]},extras:e};continue}else if(w(t,`image_generation_call`)){E(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:E(t.id)?t.id:void 0,metadata:{status:E(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}T(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function Ge(e){function*t(){yield*We(e);for(let t of e.tool_call_chunks??[])yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args}}return Array.from(t())}var Ke={translateContent:e=>typeof e.content==`string`?Be(e):We(e),translateContentChunk:e=>typeof e.content==`string`?Ve(e):Ge(e)};function qe(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Je(e,t=`pretty`){return t===`pretty`?Ye(e):JSON.stringify(e)}function Ye(e){let t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i=`=`.repeat(r),a=n.length%2==0?i:`${i}=`;if(t.push(`${i}${n}${a}`),e.type===`ai`){let n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push(`Tool Calls:`);for(let e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(` Args:`);for(let[n,r]of Object.entries(e.args))t.push(` ${n}: ${typeof r==`object`?JSON.stringify(r):r}`)}}}if(e.type===`tool`){let n=e;n.name&&t.push(`Name: ${n.name}`)}return typeof e.content==`string`&&e.content.trim()&&(t.length>1&&t.push(``),t.push(e.content)),t.join(`
|
|
@@ -210,7 +210,7 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
210
210
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
211
211
|
`);this.baseURL=i.baseURL,this.timeout=i.timeout??FY.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=LK(i.logLevel,`ClientOptions.logLevel`,this)??LK(NY(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??yK(),Y(this,IY,wK,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return Q([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Q([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Q([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return TK(e)}getUserAgent(){return`${this.constructor.name}/JS ${uK}`}defaultIdempotencyKey(){return`stainless-node-retry-${RG()}`}makeStatusError(e,t,n,r){return VG.generate(e,t,n,r)}buildURL(e,t,n){let r=!X(this,PY,`m`,LY).call(this)&&n||this.baseURL,i=eK(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!iK(a)||!iK(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Z(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new $K(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(HK(this).debug(`[${c}] sending request`,UK({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new HG;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(BG),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new HG;let i=zG(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return HK(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),HK(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,UK({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw HK(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),HK(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,UK({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new WG:new UG({cause:f})}let m=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await CK(f.body),HK(this).info(`${m} - ${e}`),HK(this).debug(`[${c}] response error (${e})`,UK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;HK(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>BG(e).message),o=sK(a),s=o?void 0:a;throw HK(this).debug(`[${c}] response error (${i})`,UK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return HK(this).info(m),HK(this).debug(`[${c}] response start`,UK({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new nq(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await lK(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new Z(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&oK(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=Q([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...vK(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Q([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:xK(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:X(this,IY,`f`).call(this,{body:e,headers:n})}};FY=BY,IY=new WeakMap,PY=new WeakSet,LY=function(){return this.baseURL!==`https://api.anthropic.com`},BY.Anthropic=FY,BY.HUMAN_PROMPT=RY,BY.AI_PROMPT=zY,BY.DEFAULT_TIMEOUT=6e5,BY.AnthropicError=Z,BY.APIError=VG,BY.APIConnectionError=UG,BY.APIConnectionTimeoutError=WG,BY.APIUserAbortError=HG,BY.NotFoundError=JG,BY.ConflictError=YG,BY.RateLimitError=ZG,BY.BadRequestError=GG,BY.AuthenticationError=KG,BY.InternalServerError=QG,BY.PermissionDeniedError=qG,BY.UnprocessableEntityError=XG,BY.toFile=vq;var VY=class extends BY{constructor(){super(...arguments),this.completions=new XJ(this),this.messages=new kY(this),this.models=new MY(this),this.beta=new YJ(this)}};VY.Completions=XJ,VY.Messages=kY,VY.Models=MY,VY.Beta=YJ;var HY=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function UY(e){return JSON.parse(JSON.stringify(e))}function WY(e){return GY(UY(e))}function GY(e){let t={},n=cK(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=cK(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=GY(n)}let i=cK(e,`type`),a=cK(e,`anyOf`),o=cK(e,`oneOf`),s=cK(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>GY(e));else if(Array.isArray(o))t.anyOf=o.map(e=>GY(e));else if(Array.isArray(s))t.allOf=s.map(e=>GY(e));else{if(i===void 0)throw Error(`JSON schema must have a type defined if anyOf/oneOf/allOf are not used`);t.type=i}let c=cK(e,`description`);c!==void 0&&(t.description=c);let l=cK(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=cK(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,GY(t)])),cK(e,`additionalProperties`),t.additionalProperties=!1;let r=cK(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=cK(e,`format`);n!==void 0&&HY.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=cK(e,`items`);n!==void 0&&(t.items=GY(n));let r=cK(e,`minItems`);r!==void 0&&(r===0||r===1)?t.minItems=r:r!==void 0&&(e.minItems=r)}if(Object.keys(e).length>0){let n=t.description;t.description=(n?n+`
|
|
212
212
|
|
|
213
|
-
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var KY={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},qY=4096;function JY(e){return e?Object.entries(KY).find(([t])=>e.startsWith(t))?.[1]??qY:qY}function YY(e){return!!(e.tools&&e.tools.length>0)}function XY(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function ZY(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function QY(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function $Y(e){return`input_schema`in e}function eX(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.type==`string`&&[`text_editor_`,`computer_`,`bash_`,`web_search_`,`web_fetch_`,`str_replace_editor_`,`str_replace_based_edit_tool_`,`code_execution_`,`memory_`,`tool_search_`,`mcp_toolset`].some(t=>typeof e.type==`string`&&e.type.startsWith(t))}function tX(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function nX(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var rX=class extends Sw{static lc_name(){return`ChatAnthropic`}get lc_secrets(){return{anthropicApiKey:`ANTHROPIC_API_KEY`,apiKey:`ANTHROPIC_API_KEY`}}get lc_aliases(){return{modelName:`model`}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName=`claude-sonnet-4-5-20250929`;model=`claude-sonnet-4-5-20250929`;invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:`disabled`};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};if(super(n??{}),this._addVersion(`@langchain/anthropic`,`1.3.27`),this.anthropicApiKey=n?.apiKey??n?.anthropicApiKey??pr(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=n?.anthropicApiUrl,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??JY(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,this.thinking=n?.thinking??this.thinking,this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new VY(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(e=>{if(KE(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(eX(e)||$Y(e))return e;if(sC(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(KE(e))return{name:e.name,description:e.description,input_schema:Nm(e.schema)?Vv(e.schema):e.schema,...e.extras?eG.parse(e.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=$W(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in tG){let n=tG[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=kG(this.model,r),o={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:tX(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers};return AG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,jG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=wG(e);t.cache_control&&(i=TG(i,t.cache_control));let a={...r,...i,stream:!0},o=!YY(a)&&!XY(a)&&!ZY(a)&&!QY(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=MG(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=nX(a),l=new Zl({message:new Xt({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async _generateNonStreaming(e,t,n,r){let i=wG(e);r&&(i=TG(i,r));let{content:a,...o}=await this.completionWithRetry({...t,stream:!1,...i},n),s=NG(a,o),{role:c,type:l,...u}=o;return{generations:s,llmOutput:u}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers},t.cache_control)}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.call(async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw IG(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw IG(e)}})}_llmType(){return`anthropic`}get profile(){return LG[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=WC(i);let e=WY(Vv(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,t;if(Nm(i)||ev(i)){let n=Vv(i);t=[{name:e,description:n.description??`A function available to call.`,input_schema:n}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(t=[i],e=i.name):t=[{name:e,description:i.description??``,input_schema:i}];if(r=GC(i,e,ZW),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:t,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:t,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},iX=class extends rX{};YD(`command`,[B({command:aO(`view`),path:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),insert_text:uD()}),B({command:aO(`delete`),path:uD()}),B({command:aO(`rename`),old_path:uD(),new_path:uD()})]),YD(`command`,[B({command:aO(`view`),path:uD(),view_range:$D([MD(),MD()]).optional()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),new_str:uD()})]);var aX=$D([MD(),MD()]),oX=B({action:aO(`screenshot`)}),sX=B({action:aO(`left_click`),coordinate:aX}),cX=B({action:aO(`right_click`),coordinate:aX}),lX=B({action:aO(`middle_click`),coordinate:aX}),uX=B({action:aO(`double_click`),coordinate:aX}),dX=B({action:aO(`triple_click`),coordinate:aX}),fX=B({action:aO(`left_click_drag`),start_coordinate:aX,end_coordinate:aX}),pX=B({action:aO(`left_mouse_down`),coordinate:aX}),mX=B({action:aO(`left_mouse_up`),coordinate:aX}),hX=B({action:aO(`scroll`),coordinate:aX,scroll_direction:rO([`up`,`down`,`left`,`right`]),scroll_amount:MD()}),gX=B({action:aO(`type`),text:uD()}),_X=B({action:aO(`key`),key:uD()}),vX=B({action:aO(`mouse_move`),coordinate:aX}),yX=B({action:aO(`hold_key`),key:uD()}),bX=B({action:aO(`wait`),duration:MD().optional()}),xX=B({action:aO(`zoom`),region:$D([MD(),MD(),MD(),MD()])});YD(`action`,[oX,sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX]),YD(`action`,[oX,sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX,xX]),qD([B({command:uD().describe(`The bash command to run`)}),B({restart:aO(!0).describe(`Set to true to restart the bash session`)})]);for(var SX=[],CX=0;CX<256;++CX)SX.push((CX+256).toString(16).slice(1));function wX(e,t=0){return(SX[e[t+0]]+SX[e[t+1]]+SX[e[t+2]]+SX[e[t+3]]+`-`+SX[e[t+4]]+SX[e[t+5]]+`-`+SX[e[t+6]]+SX[e[t+7]]+`-`+SX[e[t+8]]+SX[e[t+9]]+`-`+SX[e[t+10]]+SX[e[t+11]]+SX[e[t+12]]+SX[e[t+13]]+SX[e[t+14]]+SX[e[t+15]]).toLowerCase()}var TX,EX=new Uint8Array(16);function DX(){if(!TX&&(TX=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!TX))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return TX(EX)}var OX={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function kX(e,t,n){if(OX.randomUUID&&!t&&!e)return OX.randomUUID();e||={};var r=e.random||(e.rng||DX)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return wX(r)}function AX(e,t){return new Xt({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:kX()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function jX(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function MX(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function NX(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[jX(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[jX(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function PX(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function FX(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function IX(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return NX(e);if(e._getType()===`ai`)return MX(e);if(e._getType()===`system`)return PX(e);if(e._getType()===`tool`)return FX(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var LX=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},RX={searchParams:`URLSearchParams`in LX,iterable:`Symbol`in LX&&`iterator`in Symbol,blob:`FileReader`in LX&&`Blob`in LX&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in LX,arrayBuffer:`ArrayBuffer`in LX};function zX(e){return e&&DataView.prototype.isPrototypeOf(e)}if(RX.arrayBuffer)var BX=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],VX=ArrayBuffer.isView||function(e){return e&&BX.indexOf(Object.prototype.toString.call(e))>-1};function HX(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function UX(e){return typeof e!=`string`&&(e=String(e)),e}function WX(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return RX.iterable&&(t[Symbol.iterator]=function(){return t}),t}function GX(e){this.map={},e instanceof GX?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}GX.prototype.append=function(e,t){e=HX(e),t=UX(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},GX.prototype.delete=function(e){delete this.map[HX(e)]},GX.prototype.get=function(e){return e=HX(e),this.has(e)?this.map[e]:null},GX.prototype.has=function(e){return this.map.hasOwnProperty(HX(e))},GX.prototype.set=function(e,t){this.map[HX(e)]=UX(t)},GX.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},GX.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),WX(e)},GX.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),WX(e)},GX.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),WX(e)},RX.iterable&&(GX.prototype[Symbol.iterator]=GX.prototype.entries);function KX(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function qX(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function JX(e){var t=new FileReader,n=qX(t);return t.readAsArrayBuffer(e),n}function YX(e){var t=new FileReader,n=qX(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function XX(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function ZX(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function QX(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:RX.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:RX.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:RX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():RX.arrayBuffer&&RX.blob&&zX(e)?(this._bodyArrayBuffer=ZX(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):RX.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||VX(e))?this._bodyArrayBuffer=ZX(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):RX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},RX.blob&&(this.blob=function(){var e=KX(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return KX(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(RX.blob)return this.blob().then(JX);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=KX(this);if(e)return e;if(this._bodyBlob)return YX(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(XX(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},RX.formData&&(this.formData=function(){return this.text().then(nZ)}),this.json=function(){return this.text().then(JSON.parse)},this}var $X=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function eZ(e){var t=e.toUpperCase();return $X.indexOf(t)>-1?t:e}function tZ(e,t){if(!(this instanceof tZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof tZ){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new GX(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new GX(t.headers)),this.method=eZ(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in LX)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}tZ.prototype.clone=function(){return new tZ(this,{body:this._bodyInit})};function nZ(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function rZ(e){var t=new GX;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
213
|
+
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var KY={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},qY=4096;function JY(e){return e?Object.entries(KY).find(([t])=>e.startsWith(t))?.[1]??qY:qY}function YY(e){return!!(e.tools&&e.tools.length>0)}function XY(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function ZY(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function QY(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function $Y(e){return`input_schema`in e}function eX(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.type==`string`&&[`text_editor_`,`computer_`,`bash_`,`web_search_`,`web_fetch_`,`str_replace_editor_`,`str_replace_based_edit_tool_`,`code_execution_`,`memory_`,`tool_search_`,`mcp_toolset`].some(t=>typeof e.type==`string`&&e.type.startsWith(t))}function tX(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function nX(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var rX=class extends Sw{static lc_name(){return`ChatAnthropic`}get lc_secrets(){return{anthropicApiKey:`ANTHROPIC_API_KEY`,apiKey:`ANTHROPIC_API_KEY`}}get lc_aliases(){return{modelName:`model`}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName=`claude-sonnet-4-5-20250929`;model=`claude-sonnet-4-5-20250929`;invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:`disabled`};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};if(super(n??{}),this._addVersion(`@langchain/anthropic`,`1.3.28`),this.anthropicApiKey=n?.apiKey??n?.anthropicApiKey??pr(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=n?.anthropicApiUrl,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??JY(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,this.thinking=n?.thinking??this.thinking,this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new VY(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(e=>{if(KE(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(eX(e)||$Y(e))return e;if(sC(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(KE(e))return{name:e.name,description:e.description,input_schema:Nm(e.schema)?Vv(e.schema):e.schema,...e.extras?eG.parse(e.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=$W(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in tG){let n=tG[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=kG(this.model,r),o={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:tX(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers};return AG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,jG({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=wG(e);t.cache_control&&(i=TG(i,t.cache_control));let a={...r,...i,stream:!0},o=!YY(a)&&!XY(a)&&!ZY(a)&&!QY(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=MG(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=nX(a),l=new Zl({message:new Xt({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async _generateNonStreaming(e,t,n,r){let i=wG(e);r&&(i=TG(i,r));let{content:a,...o}=await this.completionWithRetry({...t,stream:!1,...i},n),s=NG(a,o),{role:c,type:l,...u}=o;return{generations:s,llmOutput:u}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers},t.cache_control)}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.call(async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw IG(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw IG(e)}})}_llmType(){return`anthropic`}get profile(){return LG[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=WC(i);let e=WY(Vv(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,t;if(Nm(i)||ev(i)){let n=Vv(i);t=[{name:e,description:n.description??`A function available to call.`,input_schema:n}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(t=[i],e=i.name):t=[{name:e,description:i.description??``,input_schema:i}];if(r=GC(i,e,ZW),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:t,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:t,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Vv(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},iX=class extends rX{};YD(`command`,[B({command:aO(`view`),path:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),insert_text:uD()}),B({command:aO(`delete`),path:uD()}),B({command:aO(`rename`),old_path:uD(),new_path:uD()})]),YD(`command`,[B({command:aO(`view`),path:uD(),view_range:$D([MD(),MD()]).optional()}),B({command:aO(`str_replace`),path:uD(),old_str:uD(),new_str:uD()}),B({command:aO(`create`),path:uD(),file_text:uD()}),B({command:aO(`insert`),path:uD(),insert_line:MD(),new_str:uD()})]);var aX=$D([MD(),MD()]),oX=B({action:aO(`screenshot`)}),sX=B({action:aO(`left_click`),coordinate:aX}),cX=B({action:aO(`right_click`),coordinate:aX}),lX=B({action:aO(`middle_click`),coordinate:aX}),uX=B({action:aO(`double_click`),coordinate:aX}),dX=B({action:aO(`triple_click`),coordinate:aX}),fX=B({action:aO(`left_click_drag`),start_coordinate:aX,end_coordinate:aX}),pX=B({action:aO(`left_mouse_down`),coordinate:aX}),mX=B({action:aO(`left_mouse_up`),coordinate:aX}),hX=B({action:aO(`scroll`),coordinate:aX,scroll_direction:rO([`up`,`down`,`left`,`right`]),scroll_amount:MD()}),gX=B({action:aO(`type`),text:uD()}),_X=B({action:aO(`key`),key:uD()}),vX=B({action:aO(`mouse_move`),coordinate:aX}),yX=B({action:aO(`hold_key`),key:uD()}),bX=B({action:aO(`wait`),duration:MD().optional()}),xX=B({action:aO(`zoom`),region:$D([MD(),MD(),MD(),MD()])});YD(`action`,[oX,sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX]),YD(`action`,[oX,sX,cX,lX,uX,dX,fX,pX,mX,hX,gX,_X,vX,yX,bX,xX]),qD([B({command:uD().describe(`The bash command to run`)}),B({restart:aO(!0).describe(`Set to true to restart the bash session`)})]);for(var SX=[],CX=0;CX<256;++CX)SX.push((CX+256).toString(16).slice(1));function wX(e,t=0){return(SX[e[t+0]]+SX[e[t+1]]+SX[e[t+2]]+SX[e[t+3]]+`-`+SX[e[t+4]]+SX[e[t+5]]+`-`+SX[e[t+6]]+SX[e[t+7]]+`-`+SX[e[t+8]]+SX[e[t+9]]+`-`+SX[e[t+10]]+SX[e[t+11]]+SX[e[t+12]]+SX[e[t+13]]+SX[e[t+14]]+SX[e[t+15]]).toLowerCase()}var TX,EX=new Uint8Array(16);function DX(){if(!TX&&(TX=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!TX))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return TX(EX)}var OX={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function kX(e,t,n){if(OX.randomUUID&&!t&&!e)return OX.randomUUID();e||={};var r=e.random||(e.rng||DX)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return wX(r)}function AX(e,t){return new Xt({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:kX()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function jX(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function MX(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function NX(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[jX(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[jX(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function PX(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function FX(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function IX(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return NX(e);if(e._getType()===`ai`)return MX(e);if(e._getType()===`system`)return PX(e);if(e._getType()===`tool`)return FX(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var LX=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},RX={searchParams:`URLSearchParams`in LX,iterable:`Symbol`in LX&&`iterator`in Symbol,blob:`FileReader`in LX&&`Blob`in LX&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in LX,arrayBuffer:`ArrayBuffer`in LX};function zX(e){return e&&DataView.prototype.isPrototypeOf(e)}if(RX.arrayBuffer)var BX=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],VX=ArrayBuffer.isView||function(e){return e&&BX.indexOf(Object.prototype.toString.call(e))>-1};function HX(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function UX(e){return typeof e!=`string`&&(e=String(e)),e}function WX(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return RX.iterable&&(t[Symbol.iterator]=function(){return t}),t}function GX(e){this.map={},e instanceof GX?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}GX.prototype.append=function(e,t){e=HX(e),t=UX(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},GX.prototype.delete=function(e){delete this.map[HX(e)]},GX.prototype.get=function(e){return e=HX(e),this.has(e)?this.map[e]:null},GX.prototype.has=function(e){return this.map.hasOwnProperty(HX(e))},GX.prototype.set=function(e,t){this.map[HX(e)]=UX(t)},GX.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},GX.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),WX(e)},GX.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),WX(e)},GX.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),WX(e)},RX.iterable&&(GX.prototype[Symbol.iterator]=GX.prototype.entries);function KX(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function qX(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function JX(e){var t=new FileReader,n=qX(t);return t.readAsArrayBuffer(e),n}function YX(e){var t=new FileReader,n=qX(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function XX(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function ZX(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function QX(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:RX.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:RX.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:RX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():RX.arrayBuffer&&RX.blob&&zX(e)?(this._bodyArrayBuffer=ZX(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):RX.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||VX(e))?this._bodyArrayBuffer=ZX(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):RX.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},RX.blob&&(this.blob=function(){var e=KX(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return KX(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(RX.blob)return this.blob().then(JX);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=KX(this);if(e)return e;if(this._bodyBlob)return YX(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(XX(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},RX.formData&&(this.formData=function(){return this.text().then(nZ)}),this.json=function(){return this.text().then(JSON.parse)},this}var $X=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function eZ(e){var t=e.toUpperCase();return $X.indexOf(t)>-1?t:e}function tZ(e,t){if(!(this instanceof tZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof tZ){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new GX(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new GX(t.headers)),this.method=eZ(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in LX)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}tZ.prototype.clone=function(){return new tZ(this,{body:this._bodyInit})};function nZ(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function rZ(e){var t=new GX;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
214
214
|
`)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}QX.call(tZ.prototype);function iZ(e,t){if(!(this instanceof iZ))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||={},this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw RangeError(`Failed to construct 'Response': The status provided (0) is outside the range [200, 599].`);this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?``:``+t.statusText,this.headers=new GX(t.headers),this.url=t.url||``,this._initBody(e)}QX.call(iZ.prototype),iZ.prototype.clone=function(){return new iZ(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new GX(this.headers),url:this.url})},iZ.error=function(){var e=new iZ(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var aZ=[301,302,303,307,308];iZ.redirect=function(e,t){if(aZ.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new iZ(null,{status:t,headers:{location:e}})};var oZ=LX.DOMException;try{new oZ}catch{oZ=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},oZ.prototype=Object.create(Error.prototype),oZ.prototype.constructor=oZ}function sZ(e,t){return new Promise(function(n,r){var i=new tZ(e,t);if(i.signal&&i.signal.aborted)return r(new oZ(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:rZ(a.getAllResponseHeaders()||``)};i.url.indexOf(`file://`)===0&&(a.status<200||a.status>599)?e.status=200:e.status=a.status,e.url=`responseURL`in a?a.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in a?a.response:a.responseText;setTimeout(function(){n(new iZ(t,e))},0)},a.onerror=function(){setTimeout(function(){r(TypeError(`Network request failed`))},0)},a.ontimeout=function(){setTimeout(function(){r(TypeError(`Network request timed out`))},0)},a.onabort=function(){setTimeout(function(){r(new oZ(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&LX.location.href?LX.location.href:e}catch{return e}}if(a.open(i.method,s(i.url),!0),i.credentials===`include`?a.withCredentials=!0:i.credentials===`omit`&&(a.withCredentials=!1),`responseType`in a&&(RX.blob?a.responseType=`blob`:RX.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof GX||LX.Headers&&t.headers instanceof LX.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(HX(e)),a.setRequestHeader(e,UX(t.headers[e]))}),i.headers.forEach(function(e,t){c.indexOf(t)===-1&&a.setRequestHeader(t,e)})}else i.headers.forEach(function(e,t){a.setRequestHeader(t,e)});i.signal&&(i.signal.addEventListener(`abort`,o),a.onreadystatechange=function(){a.readyState===4&&i.signal.removeEventListener(`abort`,o)}),a.send(i._bodyInit===void 0?null:i._bodyInit)})}sZ.polyfill=!0,LX.fetch||(LX.fetch=sZ,LX.Headers=GX,LX.Request=tZ,LX.Response=iZ);var cZ=`11434`,lZ=`http://127.0.0.1:${cZ}`,uZ=`0.6.3`,dZ=Object.defineProperty,fZ=(e,t,n)=>t in e?dZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,pZ=(e,t,n)=>(fZ(e,typeof t==`symbol`?t:t+``,n),n),mZ=class e extends Error{constructor(t,n){super(t),this.error=t,this.status_code=n,this.name=`ResponseError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},hZ=class{constructor(e,t,n){pZ(this,`abortController`),pZ(this,`itr`),pZ(this,`doneCallback`),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if(`error`in e)throw Error(e.error);if(yield e,e.done||e.status===`success`){this.doneCallback();return}}throw Error(`Did not receive done or success response in stream.`)}},gZ=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get(`content-type`)?.includes(`application/json`))try{n=await e.json(),t=n.error||t}catch{console.log(`Failed to parse error response as JSON`)}else try{console.log(`Getting text from response`),t=await e.text()||t}catch{console.log(`Failed to get text from error response`)}throw new mZ(t,e.status)};function _Z(){if(typeof window<`u`&&window.navigator){let e=navigator;return`userAgentData`in e&&e.userAgentData?.platform?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<`u`)return`${process.arch} ${process.platform} Node.js/${process.version}`;return``}function vZ(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}else if(Array.isArray(e))return Object.fromEntries(e);else return e||{}}var yZ=(e,t)=>e[t],bZ=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${uZ} (${_Z()})`};n.headers=vZ(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?yZ({},`OLLAMA_API_KEY`):void 0;!(n.headers.authorization||n.headers.Authorization)&&e&&(n.headers.Authorization=`Bearer ${e}`)}}catch(e){console.error(`error parsing url`,e)}let i=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...i},e(t,n)},xZ=async(e,t,n)=>{let r=await bZ(e,t,{headers:n?.headers});return await gZ(r),r},SZ=async(e,t,n,r)=>{let i=await bZ(e,t,{method:`POST`,body:(e=>typeof e==`object`&&!!e&&!Array.isArray(e))(n)?JSON.stringify(n):n,signal:r?.signal,headers:r?.headers});return await gZ(i),i},CZ=async(e,t,n,r)=>{let i=await bZ(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await gZ(i),i},wZ=async function*(e){let t=new TextDecoder(`utf-8`),n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0});let a=n.split(`
|
|
215
215
|
`);n=a.pop()??``;for(let e of a)try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}}n+=t.decode();for(let e of n.split(`
|
|
216
216
|
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},TZ=e=>{if(!e)return lZ;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:cZ;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},EZ=Object.defineProperty,DZ=(e,t,n)=>t in e?EZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,OZ=(e,t,n)=>(DZ(e,typeof t==`symbol`?t:t+``,n),n),kZ=class{constructor(e){OZ(this,`config`),OZ(this,`fetch`),OZ(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=TZ(e?.host??lZ)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await SZ(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new hZ(e,wZ(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await SZ(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await CZ(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await SZ(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await xZ(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await SZ(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await SZ(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await SZ(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await xZ(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await xZ(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await SZ(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await SZ(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new kZ;var AZ=class extends Sw{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.6`),this.baseUrl=n.baseUrl??pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new kZ({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>ak(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>ak(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?pl(r,i.message):i.message;let i=new qt({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=IX(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Zl({text:o,message:AX(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Zl({text:``,message:new Xt({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Vv(i);Nm(i)||ev(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:Nm(i)||ev(i)?o:i}}),r=GC(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=WC(i);let e=Vv(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return KC(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},jZ=e=>r.includes(e),MZ=e=>n.includes(e),NZ=e=>{let{executeQuery:t,search:r,grep:i,readFile:a}=e;return[FO(async({query:e,limit:t,groupByProcess:n})=>{let i=t??10,a=n??!0,o;try{o=await r(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./index-ChQJsgDb.js";import"./chunk-H3VCZNTA-j4ZGeRTZ.js";import"./chunk-FXACKDTF-CNljDI1M.js";import{n as e}from"./chunk-XGPFEOL4-Dqk5iHgi.js";export{e as createArchitectureServices};
|