@directive-run/ai 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic.d.cts +1 -1
- package/dist/anthropic.d.ts +1 -1
- package/dist/chunk-56LYSE63.js +6 -0
- package/dist/chunk-56LYSE63.js.map +1 -0
- package/dist/chunk-5JQ2A3JK.js +2 -0
- package/dist/chunk-5JQ2A3JK.js.map +1 -0
- package/dist/chunk-7DPTXZZI.cjs +67 -0
- package/dist/chunk-7DPTXZZI.cjs.map +1 -0
- package/dist/chunk-BFSRYCOS.js +4 -0
- package/dist/chunk-BFSRYCOS.js.map +1 -0
- package/dist/chunk-C6MQ4WL6.cjs +11 -0
- package/dist/chunk-C6MQ4WL6.cjs.map +1 -0
- package/dist/chunk-CAA6Q4YY.cjs +4 -0
- package/dist/chunk-CAA6Q4YY.cjs.map +1 -0
- package/dist/chunk-D5APTMCT.cjs +16 -0
- package/dist/chunk-D5APTMCT.cjs.map +1 -0
- package/dist/chunk-FBT73WFY.js +2 -0
- package/dist/chunk-FBT73WFY.js.map +1 -0
- package/dist/chunk-FN4GUZAI.js +67 -0
- package/dist/chunk-FN4GUZAI.js.map +1 -0
- package/dist/chunk-GTB6HTZV.js +30 -0
- package/dist/chunk-GTB6HTZV.js.map +1 -0
- package/dist/chunk-HRR45JZX.js +7 -0
- package/dist/chunk-HRR45JZX.js.map +1 -0
- package/dist/chunk-IR3IHBVQ.cjs +2 -0
- package/dist/chunk-IR3IHBVQ.cjs.map +1 -0
- package/dist/chunk-J2Q5KKPN.js +37 -0
- package/dist/chunk-J2Q5KKPN.js.map +1 -0
- package/dist/chunk-K64WKZ22.cjs +2 -0
- package/dist/chunk-K64WKZ22.cjs.map +1 -0
- package/dist/chunk-MDXDPECP.cjs +30 -0
- package/dist/chunk-MDXDPECP.cjs.map +1 -0
- package/dist/chunk-PB276BX2.cjs +6 -0
- package/dist/chunk-PB276BX2.cjs.map +1 -0
- package/dist/chunk-UR5BMWEN.js +2 -0
- package/dist/chunk-UR5BMWEN.js.map +1 -0
- package/dist/chunk-V2FCPNPP.js +11 -0
- package/dist/chunk-V2FCPNPP.js.map +1 -0
- package/dist/chunk-WCQK3JOR.cjs +7 -0
- package/dist/chunk-WCQK3JOR.cjs.map +1 -0
- package/dist/chunk-WOFIBIPW.cjs +2 -0
- package/dist/chunk-WOFIBIPW.cjs.map +1 -0
- package/dist/chunk-XN5LUOVS.cjs +37 -0
- package/dist/chunk-XN5LUOVS.cjs.map +1 -0
- package/dist/chunk-YT4QN3KO.js +16 -0
- package/dist/chunk-YT4QN3KO.js.map +1 -0
- package/dist/debug-timeline-DpnRMnLU.d.cts +87 -0
- package/dist/debug-timeline-L13P-U2I.d.ts +87 -0
- package/dist/devtools.cjs +2 -0
- package/dist/devtools.cjs.map +1 -0
- package/dist/devtools.d.cts +354 -0
- package/dist/devtools.d.ts +354 -0
- package/dist/devtools.js +2 -0
- package/dist/devtools.js.map +1 -0
- package/dist/evals.cjs +2 -0
- package/dist/evals.cjs.map +1 -0
- package/dist/evals.d.cts +361 -0
- package/dist/evals.d.ts +361 -0
- package/dist/evals.js +2 -0
- package/dist/evals.js.map +1 -0
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts +1 -1
- package/dist/gemini.d.ts +1 -1
- package/dist/gemini.js +1 -1
- package/dist/gemini.js.map +1 -1
- package/dist/guardrails.cjs +2 -0
- package/dist/guardrails.cjs.map +1 -0
- package/dist/guardrails.d.cts +618 -0
- package/dist/guardrails.d.ts +618 -0
- package/dist/guardrails.js +2 -0
- package/dist/guardrails.js.map +1 -0
- package/dist/health-monitor-C6xoXrQz.d.cts +55 -0
- package/dist/health-monitor-qL9RNMH3.d.ts +55 -0
- package/dist/index.cjs +21 -99
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1197 -4735
- package/dist/index.d.ts +1197 -4735
- package/dist/index.js +21 -99
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +2 -0
- package/dist/mcp.cjs.map +1 -0
- package/dist/mcp.d.cts +450 -0
- package/dist/mcp.d.ts +450 -0
- package/dist/mcp.js +2 -0
- package/dist/mcp.js.map +1 -0
- package/dist/multi-agent-orchestrator-KFYIDKTF.cjs +2 -0
- package/dist/{multi-agent-orchestrator-KFGTEGE5.cjs.map → multi-agent-orchestrator-KFYIDKTF.cjs.map} +1 -1
- package/dist/multi-agent-orchestrator-ZHSMWIKP.js +2 -0
- package/dist/{multi-agent-orchestrator-4PXNYRHB.js.map → multi-agent-orchestrator-ZHSMWIKP.js.map} +1 -1
- package/dist/multi-agent.cjs +2 -0
- package/dist/multi-agent.cjs.map +1 -0
- package/dist/multi-agent.d.cts +1429 -0
- package/dist/multi-agent.d.ts +1429 -0
- package/dist/multi-agent.js +2 -0
- package/dist/multi-agent.js.map +1 -0
- package/dist/ollama.d.cts +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.cjs.map +1 -1
- package/dist/openai.d.cts +2 -2
- package/dist/openai.d.ts +2 -2
- package/dist/openai.js +1 -1
- package/dist/openai.js.map +1 -1
- package/dist/{orchestrator-types-CTfIKk0W.d.ts → orchestrator-types-CbNE7Rjp.d.cts} +6 -139
- package/dist/{orchestrator-types-Bh8r3_Sq.d.cts → orchestrator-types-ZK9lv5Sm.d.ts} +6 -139
- package/dist/predicate.cjs +2 -0
- package/dist/predicate.cjs.map +1 -0
- package/dist/predicate.d.cts +371 -0
- package/dist/predicate.d.ts +371 -0
- package/dist/predicate.js +2 -0
- package/dist/predicate.js.map +1 -0
- package/dist/{semantic-cache-nBpQqILc.d.cts → semantic-cache-DM7ev7NQ.d.cts} +1 -1
- package/dist/{semantic-cache-nBpQqILc.d.ts → semantic-cache-DM7ev7NQ.d.ts} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +4 -2
- package/dist/testing.d.ts +4 -2
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/{types-CRmwFnVk.d.cts → types-DJ09LjZX.d.cts} +1 -1
- package/dist/{types-CRmwFnVk.d.ts → types-DJ09LjZX.d.ts} +1 -1
- package/package.json +32 -2
- package/dist/chunk-Q3PQLWBR.js +0 -16
- package/dist/chunk-Q3PQLWBR.js.map +0 -1
- package/dist/chunk-RW4R3O5P.js +0 -72
- package/dist/chunk-RW4R3O5P.js.map +0 -1
- package/dist/chunk-X3VQ5F7D.cjs +0 -72
- package/dist/chunk-X3VQ5F7D.cjs.map +0 -1
- package/dist/chunk-XV2QSBBE.cjs +0 -16
- package/dist/chunk-XV2QSBBE.cjs.map +0 -1
- package/dist/multi-agent-orchestrator-4PXNYRHB.js +0 -2
- package/dist/multi-agent-orchestrator-KFGTEGE5.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-56LYSE63.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,ra as createMultiAgentOrchestrator,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,ka as findAgentsByCapability,R as forkFromCheckpoint,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,u as matchBreakpoint,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,x as validateCheckpoint,L as withReflection}from'./chunk-FN4GUZAI.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent.js.map
|
|
2
|
+
//# sourceMappingURL=multi-agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent.js"}
|
package/dist/ollama.d.cts
CHANGED
package/dist/ollama.d.ts
CHANGED
package/dist/openai.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs');var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c,temperature:n,topP:l,stop:a,responseFormat:p}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return chunk3WO4MWJM_cjs.f({fetch:b,hooks:c,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,hooks:i,temperature:c,topP:n,stop:l,responseFormat:a}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIStreamingRunner");let p=a==="json"?{type:"json_object"}:a??void 0;return async(o,t,u)=>{let d=chunkKP3G32S7_cjs.e(i,o,t);try{let e=await b(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h,...m!=null?{max_tokens:m}:{},...c!=null?{temperature:c}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"OpenAI");let f=chunkKP3G32S7_cjs.b(e),{fullText:
|
|
1
|
+
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs');var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c,temperature:n,topP:l,stop:a,responseFormat:p}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return chunk3WO4MWJM_cjs.f({fetch:b,hooks:c,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,hooks:i,temperature:c,topP:n,stop:l,responseFormat:a}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIStreamingRunner");let p=a==="json"?{type:"json_object"}:a??void 0;return async(o,t,u)=>{let d=chunkKP3G32S7_cjs.e(i,o,t);try{let e=await b(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h,...m!=null?{max_tokens:m}:{},...c!=null?{temperature:c}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"OpenAI");let f=chunkKP3G32S7_cjs.b(e),{fullText:A,inputTokens:O,outputTokens:S}=await chunkKP3G32S7_cjs.d(f,u.onToken,k=>{let y={},w=k.choices?.[0]?.delta;return w?.content&&(y.text=w.content),k.usage&&(y.inputTokens=k.usage.prompt_tokens??0,y.outputTokens=k.usage.completion_tokens??0),y},"OpenAI"),_={inputTokens:O,outputTokens:S},j=O+S;return u.onMessage?.({role:"assistant",content:A}),chunkKP3G32S7_cjs.f(i,o,t,A,j,_,d),chunkKP3G32S7_cjs.h(t,A,j,_)}catch(e){throw chunkKP3G32S7_cjs.g(i,o,t,e,d),e}}}
|
|
2
2
|
exports.OPENAI_PRICING=L;exports.createOpenAIEmbedder=M;exports.createOpenAIRunner=B;exports.createOpenAIStreamingRunner=v;//# sourceMappingURL=openai.cjs.map
|
|
3
3
|
//# sourceMappingURL=openai.cjs.map
|
package/dist/openai.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"qHAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1C,cAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,EAC1C,QAAA,CAAU,CAAE,MAAO,GAAA,CAAK,MAAA,CAAQ,EAAG,CAAA,CACnC,aAAA,CAAe,CAAE,KAAA,CAAO,IAAM,MAAA,CAAQ,EAAI,EAC1C,aAAA,CAAe,CAAE,MAAO,EAAA,CAAI,MAAA,CAAQ,EAAG,CAAA,CACvC,UAAW,CAAE,KAAA,CAAO,IAAK,MAAA,CAAQ,GAAI,EACrC,EAAA,CAAI,CAAE,KAAA,CAAO,EAAA,CAAI,OAAQ,EAAG,CAAA,CAC5B,UAAW,CAAE,KAAA,CAAO,IAAK,MAAA,CAAQ,GAAI,CACvC,EAsDK,SAASC,CAAAA,CAAmBC,CAAAA,CAA2C,CAC5E,GAAM,CACJ,OAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,QAAA,CACR,UAAAC,CAAAA,CACA,OAAA,C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AMS,CAAAA,CAASC,oBAAaV,CAAQ,CAAA,CAE9B,CAAE,QAAA,CAAAW,EAAU,WAAA,CAAAf,CAAAA,CAAa,aAAAC,CAAa,CAAA,CAAI,MAAMe,mBAAAA,CACpDH,CAAAA,CACAJ,CAAAA,CAAU,OAAA,CACTQ,GAAU,CACT,IAAMC,EAIF,EAAC,CAECC,EAASF,CAAAA,CAAM,OAAA,GAA6C,CAAC,CAAA,EAC/D,MACJ,OAAIE,CAAAA,EAAO,UACTD,CAAAA,CAAO,IAAA,CAAOC,EAAM,OAAA,CAAA,CAGlBF,CAAAA,CAAM,KAAA,GACRC,CAAAA,CAAO,YACHD,CAAAA,CAAM,KAAA,CACL,eAA4B,CAAA,CACjCC,CAAAA,CAAO,aACHD,CAAAA,CAAM,KAAA,CACL,iBAAA,EAAgC,CAAA,CAAA,CAGhCC,CACT,CAAA,CACA,QACF,EAEME,CAAAA,CAAa,CAAE,YAAApB,CAAAA,CAAa,YAAA,CAAAC,CAAa,CAAA,CACzCoB,EAAcrB,CAAAA,CAAcC,CAAAA,CAElC,OAAAQ,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASM,CAAS,CAAC,CAAA,CAC9DO,mBAAAA,CACEtC,EACAS,CAAAA,CACAe,CAAAA,CACAO,EACAM,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,oBAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,mBAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.cjs","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Array<Record<string, unknown>>)?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"qHAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1C,cAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,EAC1C,QAAA,CAAU,CAAE,MAAO,GAAA,CAAK,MAAA,CAAQ,EAAG,CAAA,CACnC,aAAA,CAAe,CAAE,KAAA,CAAO,IAAM,MAAA,CAAQ,EAAI,EAC1C,aAAA,CAAe,CAAE,MAAO,EAAA,CAAI,MAAA,CAAQ,EAAG,CAAA,CACvC,UAAW,CAAE,KAAA,CAAO,IAAK,MAAA,CAAQ,GAAI,EACrC,EAAA,CAAI,CAAE,KAAA,CAAO,EAAA,CAAI,OAAQ,EAAG,CAAA,CAC5B,UAAW,C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E3Cc,CACR,CACF,CACF","file":"openai.cjs","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Record<string, unknown>[])?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
package/dist/openai.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { E as EmbedderFn } from './semantic-cache-DM7ev7NQ.cjs';
|
|
2
|
+
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.cjs';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/openai.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { E as EmbedderFn } from './semantic-cache-DM7ev7NQ.js';
|
|
2
|
+
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.js';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/openai.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c,e,a,b,d as d$1,f as f$1,h,g}from'./chunk-3PGRBK4E.js';import {d,f}from'./chunk-ZFLHWJ56.js';var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c$1,temperature:n,topP:l,stop:a,responseFormat:p}=g;d(r),c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return f({fetch:b,hooks:c$1,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return d(r),c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g$1){let{apiKey:s,model:h$1="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b$1=globalThis.fetch,hooks:i,temperature:c$1,topP:n,stop:l,responseFormat:a$1}=g$1;d(r),c(s,"createOpenAIStreamingRunner");let p=a$1==="json"?{type:"json_object"}:a$1??void 0;return async(o,t,u)=>{let d=e(i,o,t);try{let e=await b$1(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h$1,...m!=null?{max_tokens:m}:{},...c$1!=null?{temperature:c$1}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await a(e,"OpenAI");let f=b(e),{fullText:
|
|
1
|
+
import {c,e,a,b,d as d$1,f as f$1,h,g}from'./chunk-3PGRBK4E.js';import {d,f}from'./chunk-ZFLHWJ56.js';var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c$1,temperature:n,topP:l,stop:a,responseFormat:p}=g;d(r),c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return f({fetch:b,hooks:c$1,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return d(r),c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g$1){let{apiKey:s,model:h$1="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b$1=globalThis.fetch,hooks:i,temperature:c$1,topP:n,stop:l,responseFormat:a$1}=g$1;d(r),c(s,"createOpenAIStreamingRunner");let p=a$1==="json"?{type:"json_object"}:a$1??void 0;return async(o,t,u)=>{let d=e(i,o,t);try{let e=await b$1(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h$1,...m!=null?{max_tokens:m}:{},...c$1!=null?{temperature:c$1}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await a(e,"OpenAI");let f=b(e),{fullText:A,inputTokens:O,outputTokens:S}=await d$1(f,u.onToken,k=>{let y={},w=k.choices?.[0]?.delta;return w?.content&&(y.text=w.content),k.usage&&(y.inputTokens=k.usage.prompt_tokens??0,y.outputTokens=k.usage.completion_tokens??0),y},"OpenAI"),_={inputTokens:O,outputTokens:S},j=O+S;return u.onMessage?.({role:"assistant",content:A}),f$1(i,o,t,A,j,_,d),h(t,A,j,_)}catch(e){throw g(i,o,t,e,d),e}}}
|
|
2
2
|
export{L as OPENAI_PRICING,M as createOpenAIEmbedder,B as createOpenAIRunner,v as createOpenAIStreamingRunner};//# sourceMappingURL=openai.js.map
|
|
3
3
|
//# sourceMappingURL=openai.js.map
|
package/dist/openai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1C,cAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,EAC1C,QAAA,CAAU,CAAE,MAAO,GAAA,CAAK,MAAA,CAAQ,EAAG,CAAA,CACnC,aAAA,CAAe,CAAE,KAAA,CAAO,IAAM,MAAA,CAAQ,EAAI,EAC1C,aAAA,CAAe,CAAE,MAAO,EAAA,CAAI,MAAA,CAAQ,EA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AaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.js","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Array<Record<string, unknown>>)?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1C,cAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,EAC1C,QAAA,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OAAA,CAASM,CAAS,CAAC,CAAA,CAC9DO,GAAAA,CACEtC,EACAS,CAAAA,CACAe,CAAAA,CACAO,EACAM,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,EAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.js","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Record<string, unknown>[])?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { M as Message$1,
|
|
2
|
-
import {
|
|
1
|
+
import { M as Message$1, q as RunResult, b as AgentLike, m as GuardrailFn, O as OutputGuardrailData, p as StreamingCallbackRunner, c as AgentRunner, r as OrchestratorState, N as NamedGuardrail, I as InputGuardrailData, C as Checkpoint, B as BreakpointModifications, d as BreakpointRequest, s as OrchestratorConstraint, t as OrchestratorResolver, u as GuardrailsConfig, A as ApprovalRequest, v as OrchestratorDebugConfig, w as AgentRetryConfig, x as OrchestratorLifecycleHooks, y as SelfHealingConfig, h as CheckpointStore, z as BreakpointConfig, R as RunOptions, T as ToolCallGuardrailData, P as PatternCheckpointConfig, k as DagPattern, E as GoalPattern, F as GoalNode, J as AgentSelectionStrategy, K as RelaxationTier, L as GoalResult, Q as GoalCheckpointState, U as SequentialCheckpointState, V as SupervisorCheckpointState, W as ReflectCheckpointState, X as DebateCheckpointState, Y as DagCheckpointState, S as Scratchpad, Z as MultiAgentLifecycleHooks, _ as MultiAgentSelfHealingConfig, $ as MultiAgentBreakpointType, a0 as CrossAgentDerivationFn } from './types-DJ09LjZX.cjs';
|
|
2
|
+
import { System, Requirement, Plugin } from '@directive-run/core';
|
|
3
3
|
import { CircuitBreaker } from '@directive-run/core/plugins';
|
|
4
|
+
import { D as DebugTimeline } from './debug-timeline-DpnRMnLU.cjs';
|
|
5
|
+
import { H as HealthMonitor } from './health-monitor-C6xoXrQz.cjs';
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* Agent Memory System
|
|
@@ -600,89 +602,6 @@ interface MergedTaggedStreamResult {
|
|
|
600
602
|
*/
|
|
601
603
|
declare function mergeTaggedStreams(sources: TaggedSource[]): MergedTaggedStreamResult;
|
|
602
604
|
|
|
603
|
-
/**
|
|
604
|
-
* Debug Timeline — AI-specific event log with snapshot correlation.
|
|
605
|
-
*
|
|
606
|
-
* Records agent lifecycle events (start, complete, error, guardrail checks,
|
|
607
|
-
* approvals, handoffs, patterns) and correlates them with core time-travel
|
|
608
|
-
* snapshots for visual timeline UIs and fork-and-replay debugging.
|
|
609
|
-
*
|
|
610
|
-
* Zero-cost when debug=false — the timeline is simply `null`.
|
|
611
|
-
*
|
|
612
|
-
* @module
|
|
613
|
-
*/
|
|
614
|
-
|
|
615
|
-
/** Callback fired when a new event is recorded */
|
|
616
|
-
type DebugTimelineListener = (event: DebugEvent) => void;
|
|
617
|
-
/** Debug timeline instance */
|
|
618
|
-
interface DebugTimeline {
|
|
619
|
-
/** Record a new event (id is auto-assigned) */
|
|
620
|
-
record(event: Omit<DebugEvent, "id"> & Record<string, unknown>): DebugEvent;
|
|
621
|
-
/** Get all events in order */
|
|
622
|
-
getEvents(): DebugEvent[];
|
|
623
|
-
/** Get events for a specific agent */
|
|
624
|
-
getEventsForAgent(agentId: string): DebugEvent[];
|
|
625
|
-
/** Get events by type with type narrowing */
|
|
626
|
-
getEventsByType<T extends DebugEventType>(type: T): Extract<DebugEvent, {
|
|
627
|
-
type: T;
|
|
628
|
-
}>[];
|
|
629
|
-
/** Get events at a specific snapshot */
|
|
630
|
-
getEventsAtSnapshot(snapshotId: number): DebugEvent[];
|
|
631
|
-
/** Get events in a time range */
|
|
632
|
-
getEventsInRange(startMs: number, endMs: number): DebugEvent[];
|
|
633
|
-
/** Fork from a snapshot — truncates events after it and calls goTo */
|
|
634
|
-
forkFrom(snapshotId: number): void;
|
|
635
|
-
/** Export timeline as JSON */
|
|
636
|
-
export(): string;
|
|
637
|
-
/** Import timeline from JSON */
|
|
638
|
-
import(json: string): void;
|
|
639
|
-
/** Clear all events */
|
|
640
|
-
clear(): void;
|
|
641
|
-
/** Subscribe to new events. Returns unsubscribe function. */
|
|
642
|
-
subscribe(listener: DebugTimelineListener): () => void;
|
|
643
|
-
/** Current number of events */
|
|
644
|
-
readonly length: number;
|
|
645
|
-
}
|
|
646
|
-
/** Options for creating a debug timeline */
|
|
647
|
-
interface DebugTimelineOptions {
|
|
648
|
-
/** Maximum events before eviction. @default 2000 */
|
|
649
|
-
maxEvents?: number;
|
|
650
|
-
/** Callback to get current snapshot ID from the system */
|
|
651
|
-
getSnapshotId?: () => number | null;
|
|
652
|
-
/** Callback to navigate to a snapshot (for forkFrom) */
|
|
653
|
-
goToSnapshot?: (snapshotId: number) => void;
|
|
654
|
-
}
|
|
655
|
-
/**
|
|
656
|
-
* Create a debug timeline for recording and correlating AI events.
|
|
657
|
-
*
|
|
658
|
-
* @example
|
|
659
|
-
* ```typescript
|
|
660
|
-
* const timeline = createDebugTimeline({ maxEvents: 1000 });
|
|
661
|
-
*
|
|
662
|
-
* timeline.record({
|
|
663
|
-
* type: "agent_start",
|
|
664
|
-
* timestamp: Date.now(),
|
|
665
|
-
* agentId: "researcher",
|
|
666
|
-
* snapshotId: null,
|
|
667
|
-
* inputLength: 42,
|
|
668
|
-
* });
|
|
669
|
-
*
|
|
670
|
-
* const agentEvents = timeline.getEventsForAgent("researcher");
|
|
671
|
-
* ```
|
|
672
|
-
*/
|
|
673
|
-
declare function createDebugTimeline(options?: DebugTimelineOptions): DebugTimeline;
|
|
674
|
-
/**
|
|
675
|
-
* Create a Directive plugin that bridges core constraint/resolver events
|
|
676
|
-
* to the debug timeline.
|
|
677
|
-
*
|
|
678
|
-
* @example
|
|
679
|
-
* ```typescript
|
|
680
|
-
* const timeline = createDebugTimeline();
|
|
681
|
-
* const plugin = createDebugTimelinePlugin(timeline, () => system.history?.currentIndex ?? null);
|
|
682
|
-
* ```
|
|
683
|
-
*/
|
|
684
|
-
declare function createDebugTimelinePlugin(timeline: DebugTimeline, getSnapshotId: () => number | null): Plugin;
|
|
685
|
-
|
|
686
605
|
/**
|
|
687
606
|
* P6: Structured Outputs — Schema validation with auto-retry for LLM responses.
|
|
688
607
|
*
|
|
@@ -1063,58 +982,6 @@ interface AgentOrchestrator<F extends Record<string, unknown>> {
|
|
|
1063
982
|
*/
|
|
1064
983
|
declare function createAgentOrchestrator<F extends Record<string, unknown> = Record<string, never>>(options: OrchestratorOptions<F>): AgentOrchestrator<F>;
|
|
1065
984
|
|
|
1066
|
-
/**
|
|
1067
|
-
* Health Monitor — tracks per-agent health metrics for self-healing networks.
|
|
1068
|
-
*
|
|
1069
|
-
* Pure computation module with zero Directive dependency.
|
|
1070
|
-
* Maintains a rolling window of success/failure events and computes a health
|
|
1071
|
-
* score from 0-100 based on configurable weights.
|
|
1072
|
-
*
|
|
1073
|
-
* @module
|
|
1074
|
-
*/
|
|
1075
|
-
|
|
1076
|
-
/** Circuit state values */
|
|
1077
|
-
type HealthCircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
|
|
1078
|
-
/** Per-agent health metrics */
|
|
1079
|
-
interface AgentHealthMetrics {
|
|
1080
|
-
agentId: string;
|
|
1081
|
-
circuitState: HealthCircuitState;
|
|
1082
|
-
successRate: number;
|
|
1083
|
-
avgLatencyMs: number;
|
|
1084
|
-
recentFailures: number;
|
|
1085
|
-
recentSuccesses: number;
|
|
1086
|
-
healthScore: number;
|
|
1087
|
-
/** Last N error messages (most recent last) */
|
|
1088
|
-
lastErrors: string[];
|
|
1089
|
-
}
|
|
1090
|
-
/** Health monitor instance */
|
|
1091
|
-
interface HealthMonitor {
|
|
1092
|
-
recordSuccess(agentId: string, latencyMs: number): void;
|
|
1093
|
-
recordFailure(agentId: string, latencyMs: number, error?: Error): void;
|
|
1094
|
-
getMetrics(agentId: string): AgentHealthMetrics;
|
|
1095
|
-
getAllMetrics(): Record<string, AgentHealthMetrics>;
|
|
1096
|
-
/** Returns a 0-100 health score. Returns 50 (neutral) when no data is available for the agent. */
|
|
1097
|
-
getHealthScore(agentId: string): number;
|
|
1098
|
-
updateCircuitState(agentId: string, state: HealthCircuitState): void;
|
|
1099
|
-
/** Reset all metrics. Useful for testing. */
|
|
1100
|
-
reset(): void;
|
|
1101
|
-
}
|
|
1102
|
-
/**
|
|
1103
|
-
* Create a health monitor that tracks per-agent metrics.
|
|
1104
|
-
*
|
|
1105
|
-
* @example
|
|
1106
|
-
* ```typescript
|
|
1107
|
-
* const monitor = createHealthMonitor({ windowMs: 30000 });
|
|
1108
|
-
*
|
|
1109
|
-
* monitor.recordSuccess("agent-a", 120);
|
|
1110
|
-
* monitor.recordFailure("agent-a", 5000, new Error("timeout"));
|
|
1111
|
-
*
|
|
1112
|
-
* const score = monitor.getHealthScore("agent-a");
|
|
1113
|
-
* console.log(score); // 0-100
|
|
1114
|
-
* ```
|
|
1115
|
-
*/
|
|
1116
|
-
declare function createHealthMonitor(config?: HealthMonitorConfig): HealthMonitor;
|
|
1117
|
-
|
|
1118
985
|
/**
|
|
1119
986
|
* Agent Reflection / Self-Improvement
|
|
1120
987
|
*
|
|
@@ -1383,7 +1250,7 @@ interface RaceSuccessEntry<T = unknown> {
|
|
|
1383
1250
|
interface RaceResult<T = unknown> {
|
|
1384
1251
|
winnerId: string;
|
|
1385
1252
|
result: T;
|
|
1386
|
-
allResults?:
|
|
1253
|
+
allResults?: RaceSuccessEntry<T>[];
|
|
1387
1254
|
}
|
|
1388
1255
|
/**
|
|
1389
1256
|
* Debate pattern - agents compete, evaluator judges across rounds.
|
|
@@ -1781,4 +1648,4 @@ interface MultiAgentOrchestrator {
|
|
|
1781
1648
|
destroy(): void;
|
|
1782
1649
|
}
|
|
1783
1650
|
|
|
1784
|
-
export { type
|
|
1651
|
+
export { type StreamingGuardrailResult as $, type AgentOrchestrator as A, type BackpressureStrategy as B, type RaceSuccessEntry as C, type DebatePattern as D, type ErrorChunk as E, type ReflectIterationRecord as F, type GuardrailTriggeredChunk as G, type HandoffRequest as H, type ReflectPattern as I, type ReflectionConfig as J, type ReflectionContext as K, type ReflectionEvaluation as L, type MultiAgentOrchestrator as M, ReflectionExhaustedError as N, type OrchestratorOptions as O, type ParallelPattern as P, type RunAgentRequirement as Q, type ReflectionEvaluator as R, type RunCallOptions as S, type TaskRegistration as T, type SafeParseResult as U, type SafeParseable as V, type SequentialPattern as W, type StreamChunk as X, type StreamRunOptions as Y, type StreamRunner as Z, type StreamingGuardrail as _, type MultiAgentOrchestratorOptions as a, type StreamingRunResult as a0, type StructuredOutputConfig as a1, StructuredOutputError as a2, type SupervisorPattern as a3, type TaskContext as a4, type TokenChunk as a5, type ToolEndChunk as a6, type ToolStartChunk as a7, adaptOutputGuardrail as a8, collectTokens as a9, combineStreamingGuardrails as aa, createAgentMemory as ab, createAgentOrchestrator as ac, createHybridStrategy as ad, createKeyPointsSummarizer as ae, createLLMSummarizer as af, createLengthStreamingGuardrail as ag, createPatternStreamingGuardrail as ah, createSlidingWindowStrategy as ai, createStreamingRunner as aj, createTokenBasedStrategy as ak, createToxicityStreamingGuardrail as al, createTruncationSummarizer as am, extractJsonFromOutput as an, filterStream as ao, mapStream as ap, mergeTaggedStreams as aq, tapStream as ar, withReflection as as, withStructuredOutput as at, type MultiplexedStreamChunk as b, type AgentMemory as c, type AgentMemoryConfig as d, type AgentRegistration as e, type AgentRegistry as f, type DebateResult as g, type DoneChunk as h, type ExecutionPattern as i, type HandoffResult as j, type MemoryManageResult as k, type MemoryState as l, type MemoryStrategy as m, type MemoryStrategyConfig as n, type MemoryStrategyResult as o, type MergedTaggedStreamResult as p, type MessageChunk as q, type MessageSummarizer as r, type MultiAgentRunCallOptions as s, type MultiAgentState as t, type MultiplexedStreamResult as u, type OrchestratorStreamChunk as v, type OrchestratorStreamResult as w, type ProgressChunk as x, type RacePattern as y, type RaceResult as z };
|