@ag-ui/langgraph 0.0.33 → 0.0.34
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/index.d.mts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AbstractAgent as e,EventType as t,HttpAgent as n,randomUUID as r}from"@ag-ui/client";import{Observable as i}from"rxjs";import{Client as a}from"@langchain/langgraph-sdk";let o=function(e){return e.OnChainStart=`on_chain_start`,e.OnChainStream=`on_chain_stream`,e.OnChainEnd=`on_chain_end`,e.OnChatModelStart=`on_chat_model_start`,e.OnChatModelStream=`on_chat_model_stream`,e.OnChatModelEnd=`on_chat_model_end`,e.OnToolStart=`on_tool_start`,e.OnToolEnd=`on_tool_end`,e.OnToolError=`on_tool_error`,e.OnCustomEvent=`on_custom_event`,e.OnInterrupt=`on_interrupt`,e}({}),s=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const c=[`messages`,`tools`];function l(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function u({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=l(r,[...c,...n.input])),r}const d=new Set([`image`,`audio`,`video`,`document`]);function f(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function p(e){let t=[];for(let n of e)if(n.type===`text`&&n.text)t.push({type:`text`,text:n.text});else if(n.type===`image_url`){let e=typeof n.image_url==`string`?n.image_url:n.image_url?.url;if(!e)continue;if(e.startsWith(`data:`)){let[n,r]=e.split(`,`,2),i=n.includes(`:`)?n.split(`:`)[1].split(`;`)[0]:`image/png`;t.push({type:`image`,source:{type:`data`,value:r||``,mimeType:i}})}else t.push({type:`image`,source:{type:`url`,value:e}})}return t}function m(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(d.has(n.type)){let e=f(n.source);e?t.push({type:`image_url`,image_url:{url:e}}):console.warn(`[convertAguiMultimodalToLangchain] Dropping ${n.type} content: source could not be converted to URL`)}else if(n.type===`binary`){let e;if(n.url)e=n.url;else if(n.data)e=`data:${n.mimeType};base64,${n.data}`;else if(n.id)e=n.id;else{console.warn(`[convertAguiMultimodalToLangchain] Dropping BinaryInputContent: no url, data, or id provided`);continue}t.push({type:`image_url`,image_url:{url:e}})}return t}function h(e){return e.map(e=>{switch(e.type){case`human`:let t;return t=Array.isArray(e.content)?p(e.content):_(b(e.content)),{id:e.id,role:`user`,content:t};case`generic`:case`ai`:let n=b(e.content);return{id:e.id,role:`assistant`,content:n?_(n):``,toolCalls:e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args)}}))};case`system`:return{id:e.id,role:`system`,content:_(b(e.content))};case`tool`:return{id:e.id,role:`tool`,content:_(b(e.content)),toolCallId:e.tool_call_id};default:throw Error(`message type returned from LangGraph is not supported.`)}})}function g(e){return e.filter(e=>e.role!==`reasoning`&&e.role!==`developer`).map((e,t)=>{switch(e.role){case`user`:let t;return t=typeof e.content==`string`?e.content:Array.isArray(e.content)?m(e.content):String(e.content),{id:e.id,role:e.role,content:t,type:`human`};case`assistant`:return{id:e.id,type:`ai`,role:e.role,content:e.content??``,tool_calls:(e.toolCalls??[]).map(e=>({id:e.id,name:e.function.name,args:JSON.parse(e.function.arguments),type:`tool_call`}))};case`system`:return{id:e.id,role:e.role,content:e.content,type:`system`};case`tool`:return{content:e.content,role:e.role,type:e.role,tool_call_id:e.toolCallId,id:e.id};default:throw console.error(`Message role ${e.role} is not implemented`),Error(`message role is not supported.`)}})}function _(e){return typeof e==`string`?e:JSON.stringify(e)}function v(e){let t=e.chunk?.content;if(t&&Array.isArray(t)&&t.length&&t[0]){let e=t[0];if(e.type===`thinking`&&e.thinking){let t={text:e.thinking,type:`text`,index:e.index??0};return e.signature&&(t.signature=e.signature),t}if(e.type===`reasoning`&&e.reasoning)return{text:e.reasoning,type:`text`,index:e.index??0};if(e.type===`reasoning`&&e.summary?.[0]?.text)return{type:`text`,text:e.summary[0].text,index:e.summary[0].index??0};if(e.type===`reasoning_content`&&e.reasoning_content?.text)return{type:`text`,text:e.reasoning_content.text,index:e.reasoning_content.index??0}}if(e.chunk?.additional_kwargs?.reasoning?.summary?.[0]){let t=e.chunk.additional_kwargs.reasoning.summary[0];return!t||!t.text?null:{type:`text`,text:t.text,index:t.index??0}}return null}function y(e){let t=e.chunk?.content;return!t||!Array.isArray(t)||!t.length||!t[0]?null:t[0].type===`redacted_thinking`&&t[0].data?t[0].data:null}function b(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const x=`root`;var S=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=x,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=c,this.config=e,this.messagesInProcess={},this.agentName=e.agentName,this.graphId=e.graphId,this.assistantConfig=e.assistantConfig,this.reasoningProcess=null;let t=this,n=e.headerFactory??(()=>t.headers);e?.client&&e.headerFactory&&console.debug("[@ag-ui/langgraph] Both `config.client` and `config.headerFactory` were set. Custom clients bypass the adapter's onRequest hook — `headerFactory` will not be invoked. Either omit `client` to enable adapter-managed header forwarding, or wire headers into your custom client directly."),this.client=e?.client??new a({apiUrl:e.deploymentUrl,apiKey:e.langsmithApiKey,defaultHeaders:{...e.propertyHeaders??{}},onRequest:(e,t)=>{let r=n();return!r||Object.keys(r).length===0?t:{...t,headers:{...t.headers,...r}}}})}clone(){let e=Object.assign(super.clone(),{config:this.config,messagesInProcess:structuredClone(this.messagesInProcess),agentName:this.agentName,graphId:this.graphId,assistantConfig:this.assistantConfig,reasoningProcess:this.reasoningProcess?structuredClone(this.reasoningProcess):null,constantSchemaKeys:[...this.constantSchemaKeys],headers:{...this.headers},client:this.client,assistant:this.assistant,activeRun:this.activeRun?structuredClone(this.activeRun):void 0,cancelRequested:this.cancelRequested,cancelSent:this.cancelSent,subgraphs:this.subgraphs?new Set(this.subgraphs):new Set,currentSubgraph:x});if(!this.config.client){let t=this.config.headerFactory??(()=>e.headers);e.client=new a({apiUrl:this.config.deploymentUrl,apiKey:this.config.langsmithApiKey,defaultHeaders:{...this.config.propertyHeaders??{}},onRequest:(e,n)=>{let r=t();return!r||Object.keys(r).length===0?n:{...n,headers:{...n.headers,...r}}}})}return e}dispatchEvent(e){return this.subscriber.next(e),!0}run(e){return new i(t=>(this.runAgentStream(e,t).catch(e=>{console.error(`[LangGraph] runAgentStream error:`,e),t.closed||t.error(e)}),()=>{}))}async runAgentStream(e,t){this.activeRun={id:e.runId,threadId:e.threadId,hasFunctionStreaming:!1,modelMadeToolCall:!1},this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.subscriber=t,this.assistant||=await this.getAssistant();let n=e.threadId??r(),i=e.forwardedProps?.streamMode??[`events`,`values`,`updates`,`messages-tuple`],a=await this.prepareStream({...e,threadId:n},i);if(!a)return t.error(`No stream to regenerate`);await this.handleStreamEvents(a,n,t,e,Array.isArray(i)?i:[i])}async prepareRegenerateStream(e,t){let{threadId:n,messageCheckpoint:r,forwardedProps:i}=e,a=await this.getCheckpointByMessage(r.id,n);if(this.assistant||=await this.getAssistant(),!a)return this.subscriber.error(`No checkpoint found for message`);let o=await this.client.threads.updateState(n,{values:this.langGraphDefaultMergeState(a.values,[],e),checkpointId:a.checkpoint.checkpoint_id,asNode:a.next?.[0]??`__start__`}),s,c=[this.assistantConfig,i?.config].filter(Boolean);c.length&&(s=await this.mergeConfigs({configs:c,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys??null}));let l={...e.forwardedProps??{},input:this.langGraphDefaultMergeState(a.values,[r],e),checkpointId:o.checkpoint.checkpoint_id,streamMode:t,config:s};return{streamResponse:this.client.runs.stream(n,this.assistant.assistant_id,l),state:a,streamMode:t}}async prepareStream(e,n){let{threadId:i,state:a,messages:s,tools:c,context:l,forwardedProps:d}=e;this.activeRun.manuallyEmittedState=null;let f=d?.nodeName,p=i??r();this.assistant||=await this.getAssistant();let m=await this.getOrCreateThread(p,d?.threadMetadata);this.activeRun.threadId=m.thread_id;let h=await this.client.threads.getState(m.thread_id)??{values:{}},_=h.values.messages??[],v=g(s),y=this.langGraphDefaultMergeState({...a,messages:_},v,e),b={...h,values:{...y,messages:[..._,...y.messages??[]]}},x=b.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),_.filter(e=>e.type!==`system`).length>s.filter(e=>e.role!==`system`).length){let t=null;for(let e=s.length-1;e>=0;e--)if(s[e].role===`user`){t=g([s[e]])[0];break}return t?this.prepareRegenerateStream({...e,messageCheckpoint:t},n):this.subscriber.error(`No user message found in messages to regenerate`)}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let S=!d?.command?.resume&&p&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(S===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(p,{values:a,asNode:e?.source})}let C=u({mode:S,state:x,schemaKeys:this.activeRun.schemaKeys}),w,T=[this.assistantConfig,d?.config].filter(Boolean);T.length&&(w=await this.mergeConfigs({configs:T,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:E,...D}=d;if(E?.resume&&typeof E.resume==`string`)try{E.resume=JSON.parse(E.resume)}catch{}let O=new Set(this.activeRun.schemaKeys?.context??[]),k=w?.configurable??{},A={},j={};for(let[e,t]of Object.entries(k))O.has(e)?A[e]=t:j[e]=t;let M={...A},N=w?{...w,configurable:Object.keys(j).length>0?j:void 0}:void 0,P=Object.keys(M).length>0,F=N?.configurable!=null&&Object.keys(N.configurable).length>0;if(P&&F){let e=Object.keys(j);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let I=(()=>{if(!N)return;if(F&&!P)return N;let{configurable:e,...t}=N;return Object.keys(t).length>0?t:void 0})(),L={...D,command:E,streamMode:n,input:C,config:I,...P?{context:M}:{}},R=(h.tasks??[]).flatMap(e=>e.interrupts??[]);return R?.length&&!d?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:p,runId:e.runId}),this.handleNodeChange(f),R.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:p,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(p,this.assistant.assistant_id,L),state:b}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:c}=i,l=c?.nodeName;this.subscriber=r;let u=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:d,state:f}=e;this.activeRun.prevNodeName=null;let p={},m=f;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(l);for await(let e of d){if(this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId&&this.activeRun?.id){try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}try{await d?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,c=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),l=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!c&&!l&&e.event!==`error`)continue;let h=e;if(e.event===`error`){this.dispatchEvent({type:t.RUN_ERROR,message:e.data.message,rawEvent:e});break}if(e.event===`updates`)continue;if(e.event===`values`){p={...p,...h.data};continue}else if(r&&h.event.startsWith(`values|`)){p={...p,...h.data};continue}let g=h.data,_=g.metadata??{},v=_.langgraph_node,y=g.event,b=_.langgraph_checkpoint_ns??``,S=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&S&&this.subgraphs.add(S);let C=S&&this.subgraphs.has(S)?S:x;if(C!==this.currentSubgraph&&(this.currentSubgraph=C,await this.getStateAndMessagesSnapshots(n)),_.run_id&&(this.activeRun.id=_.run_id,this.activeRun.serverRunIdKnown=!0,this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId))try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}if(v&&v!==this.activeRun.nodeName&&this.handleNodeChange(v),u||=y===o.OnCustomEvent&&g.name===s.Exit,y===o.OnChainEnd&&g.data?.output!=null){let e=g.data.output;if(typeof e==`object`&&!Array.isArray(e))p={...p,...e};else if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&t.lg_name===`Command`&&t.update&&typeof t.update==`object`&&(p={...p,...t.update})}if(y===o.OnChainEnd&&this.activeRun.nodeName===v&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(p={...p,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===v)&&this.handleNodeChange(v),m.values=this.activeRun.manuallyEmittedState??p,!this.activeRun.nodeName)continue;let w=JSON.stringify(m)!==JSON.stringify(f);!this.activeRun.modelMadeToolCall&&(w||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(f=m,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(f),rawEvent:h})),this.dispatchEvent({type:t.RAW,event:g}),this.handleSingleEvent(g)}f=await this.client.threads.getState(n);let e=(f.tasks??[]).flatMap(e=>e.interrupts??[]),c=f.next.length===0,h=f.metadata?.writes??{},g=this.activeRun.nodeName;return e?.length||(g=c?`__end__`:f.next[0]??Object.keys(h)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(g),this.handleNodeChange(void 0),await this.getStateAndMessagesSnapshots(n),this.dispatchEvent({type:t.RUN_FINISHED,threadId:n,runId:this.activeRun.id}),this.cancelRequested=!1,this.cancelSent=!1,this.activeRun=void 0,r.complete()}catch(e){return r.error(e)}}async getStateAndMessagesSnapshots(e){let n=await this.client.threads.getState(e);this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(n)});let r=n.values.messages??[];this.dispatchEvent({type:t.MESSAGES_SNAPSHOT,messages:h(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===o.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case o.OnChatModelStream:let n=e.metadata[`emit-messages`]??!0,i=e.metadata[`emit-tool-calls`]??!0;if(e.data.chunk.response_metadata.finish_reason)return;let a=this.getMessageInProgress(this.activeRun.id),c=!!a?.id,l=e.data.chunk.tool_call_chunks?.[0],u=e.metadata.predict_state?.some(e=>e.tool===l?.name),d=!c&&l?.name,f=c&&a?.toolCallId&&l?.args,p=c&&a?.toolCallId&&!l;(p||f||d)&&(this.activeRun.hasFunctionStreaming=!0);let m=v(e.data),h=y(e.data),g=b(e.data.chunk.content),_=!!(!l&&g),x=c&&!a?.toolCallId&&!_;if(m){this.handleReasoningEvent(m);break}if(h&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:h});break}if(!m&&this.reasoningProcess&&(this.reasoningProcess.signature&&this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:this.reasoningProcess.signature}),this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),u&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),p){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(x){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(d&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:l.id,toolCallName:l.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(l.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:l.id,toolCallName:l.name}));break}if(f&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:l.args,rawEvent:e});break}if(_&&n){a||=(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.chunk.id,rawEvent:e}),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:null,toolCallName:null}),this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:a.id,delta:g,rawEvent:e});break}break;case o.OnChatModelEnd:if(this.getMessageInProgress(this.activeRun.id)?.toolCallId){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(this.getMessageInProgress(this.activeRun.id)?.id){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case o.OnCustomEvent:if(e.name===s.ManuallyEmitMessage){this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.message_id,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:e.data.message_id,delta:e.data.message,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:e.data.message_id,rawEvent:e});break}if(e.name===s.ManuallyEmitToolCall){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.data.id,toolCallName:e.data.name,parentMessageId:e.data.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:e.data.id,delta:e.data.args,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:e.data.id,rawEvent:e});break}e.name===s.ManuallyEmitState&&(this.activeRun.manuallyEmittedState=e.data,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:e})),this.dispatchEvent({type:t.CUSTOM,name:e.name,value:e.data,rawEvent:e});break;case o.OnToolEnd:let S=e.data?.output;if(S&&!S.tool_call_id&&S.update?.messages?.find(e=>e.type===`tool`)&&(S=S.update?.messages?.find(e=>e.type===`tool`)),S&&S.update?.messages?.length){S.update?.messages.filter(e=>e.type===`tool`).forEach(n=>{this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:n.tool_call_id,toolCallName:n.name??``,parentMessageId:n.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:n.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e})),this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:n.tool_call_id,content:typeof n?.content==`string`?n?.content:JSON.stringify(n?.content),messageId:r(),rawEvent:e,role:`tool`})}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}this.emittedToolCallStartIds.has(S.tool_call_id)||(this.emittedToolCallStartIds.add(S.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:S.tool_call_id,toolCallName:S.name,parentMessageId:S.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:S.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:S.tool_call_id,rawEvent:e}));let C=Array.isArray(S.content)?S.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):S.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:S.tool_call_id,content:C,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case o.OnToolError:this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}}handleMessagesTupleEvent(e){let n=e[0];if(n.type&&n.type!==`AIMessageChunk`)return;let r=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.find(e=>e.type===`text`)?.text:null,i=n.tool_call_chunks,a=n.response_metadata?.finish_reason===`stop`,o=this.getMessageInProgress(this.activeRun.id);if(i?.length>0){let e=i[0];e.name?(o?.id&&!o?.toolCallId&&(this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.id||n.id,toolCallName:e.name,parentMessageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:e.id||n.id,toolCallName:e.name}),this.activeRun.hasFunctionStreaming=!0):e.args&&o?.toolCallId&&this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:e.args});return}if(a){o?.toolCallId?this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:o.toolCallId}):o?.id&&this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null;return}!r&&!i?.length||r&&(o||(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:null,toolCallName:null})),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:(this.getMessageInProgress(this.activeRun.id)??{id:n.id}).id,delta:r}))}abortRun(){this.cancelRequested=!0;let e=this.activeRun?.threadId,t=this.activeRun?.id;e&&t&&!this.cancelSent&&this.client.runs.cancel(e,t).then(()=>{this.cancelSent=!0}).catch(()=>{}),super.abortRun()}handleReasoningEvent(e){if(!e||!e.type||!e.text)return;let n=e.index;if(this.reasoningProcess?.index&&this.reasoningProcess.index!==n&&(this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),!this.reasoningProcess){let e=r();this.dispatchEvent({type:t.REASONING_START,messageId:e}),this.reasoningProcess={index:n,messageId:e}}this.reasoningProcess.type!==e.type&&(this.dispatchEvent({type:t.REASONING_MESSAGE_START,messageId:this.reasoningProcess.messageId,role:`reasoning`}),this.reasoningProcess.type=e.type),e.signature&&(this.reasoningProcess.signature=e.signature),this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_CONTENT,messageId:this.reasoningProcess.messageId,delta:e.text})}getStateSnapshot(e){let t=e.values,n=this.activeRun.schemaKeys;return n?.output&&(t=l(t,[...this.constantSchemaKeys,...n.output])),t}async getOrCreateThread(e,t){let n;try{try{n=await this.getThread(e)}catch{n=await this.createThread({threadId:e,metadata:t})}}catch(e){throw Error(`Failed to create thread: ${e.message}`)}return n}async getThread(e){return this.client.threads.get(e)}async createThread(e){return this.client.threads.create(e)}async mergeConfigs({configs:e,assistant:t,schemaKeys:n}){return e.reduce((e,t)=>{let r=e.configurable;t.configurable&&(r=n?.config?l(t?.configurable,[...this.constantSchemaKeys,...n?.config??[],...n?.context??[]]):t?.configurable);let i={...e,...t,configurable:r},a=e.recursion_limit==null&&t.recursion_limit===25,o=JSON.stringify(i)!==JSON.stringify(e),s=a&&JSON.stringify({...i,recursion_limit:null})===JSON.stringify({...e,recursion_limit:null});return o&&!s?{...e,...i}:e},t.config)}getMessageInProgress(e){return this.messagesInProcess[e]}setMessageInProgress(e,t){this.messagesInProcess={...this.messagesInProcess,[e]:{...this.messagesInProcess[e],...t}}}async getAssistant(){try{let e=await this.client.assistants.search({graphId:this.graphId,limit:1}),t=e.find(e=>e.graph_id===this.graphId);if(!t){let t=`
|
|
1
|
+
import{AbstractAgent as e,EventType as t,HttpAgent as n,randomUUID as r}from"@ag-ui/client";import{Observable as i}from"rxjs";import{Client as a}from"@langchain/langgraph-sdk";let o=function(e){return e.OnChainStart=`on_chain_start`,e.OnChainStream=`on_chain_stream`,e.OnChainEnd=`on_chain_end`,e.OnChatModelStart=`on_chat_model_start`,e.OnChatModelStream=`on_chat_model_stream`,e.OnChatModelEnd=`on_chat_model_end`,e.OnToolStart=`on_tool_start`,e.OnToolEnd=`on_tool_end`,e.OnToolError=`on_tool_error`,e.OnCustomEvent=`on_custom_event`,e.OnInterrupt=`on_interrupt`,e}({}),s=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const c=[`messages`,`tools`];function l(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function u({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=l(r,[...c,...n.input])),r}const d=new Set([`image`,`audio`,`video`,`document`]);function f(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function p(e){let t=[];for(let n of e)if(n.type===`text`&&n.text)t.push({type:`text`,text:n.text});else if(n.type===`image_url`){let e=typeof n.image_url==`string`?n.image_url:n.image_url?.url;if(!e)continue;if(e.startsWith(`data:`)){let[n,r]=e.split(`,`,2),i=n.includes(`:`)?n.split(`:`)[1].split(`;`)[0]:`image/png`;t.push({type:`image`,source:{type:`data`,value:r||``,mimeType:i}})}else t.push({type:`image`,source:{type:`url`,value:e}})}return t}function m(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(d.has(n.type)){let e=f(n.source);e?t.push({type:`image_url`,image_url:{url:e}}):console.warn(`[convertAguiMultimodalToLangchain] Dropping ${n.type} content: source could not be converted to URL`)}else if(n.type===`binary`){let e;if(n.url)e=n.url;else if(n.data)e=`data:${n.mimeType};base64,${n.data}`;else if(n.id)e=n.id;else{console.warn(`[convertAguiMultimodalToLangchain] Dropping BinaryInputContent: no url, data, or id provided`);continue}t.push({type:`image_url`,image_url:{url:e}})}return t}function h(e){return e.map(e=>{switch(e.type){case`human`:let t;return t=Array.isArray(e.content)?p(e.content):_(b(e.content)),{id:e.id,role:`user`,content:t};case`generic`:case`ai`:let n=b(e.content);return{id:e.id,role:`assistant`,content:n?_(n):``,toolCalls:e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args)}}))};case`system`:return{id:e.id,role:`system`,content:_(b(e.content))};case`tool`:return{id:e.id,role:`tool`,content:_(b(e.content)),toolCallId:e.tool_call_id};default:throw Error(`message type returned from LangGraph is not supported.`)}})}function g(e){return e.filter(e=>e.role!==`reasoning`&&e.role!==`developer`).map((e,t)=>{switch(e.role){case`user`:let t;return t=typeof e.content==`string`?e.content:Array.isArray(e.content)?m(e.content):String(e.content),{id:e.id,role:e.role,content:t,type:`human`};case`assistant`:return{id:e.id,type:`ai`,role:e.role,content:e.content??``,tool_calls:(e.toolCalls??[]).map(e=>({id:e.id,name:e.function.name,args:JSON.parse(e.function.arguments),type:`tool_call`}))};case`system`:return{id:e.id,role:e.role,content:e.content,type:`system`};case`tool`:return{content:e.content,role:e.role,type:e.role,tool_call_id:e.toolCallId,id:e.id};default:throw console.error(`Message role ${e.role} is not implemented`),Error(`message role is not supported.`)}})}function _(e){return typeof e==`string`?e:JSON.stringify(e)}function v(e){let t=e.chunk?.content;if(t&&Array.isArray(t)&&t.length&&t[0]){let e=t[0];if(e.type===`thinking`&&e.thinking){let t={text:e.thinking,type:`text`,index:e.index??0};return e.signature&&(t.signature=e.signature),t}if(e.type===`reasoning`&&e.reasoning)return{text:e.reasoning,type:`text`,index:e.index??0};if(e.type===`reasoning`&&e.summary?.[0]?.text)return{type:`text`,text:e.summary[0].text,index:e.summary[0].index??0};if(e.type===`reasoning_content`&&e.reasoning_content?.text)return{type:`text`,text:e.reasoning_content.text,index:e.reasoning_content.index??0}}if(e.chunk?.additional_kwargs?.reasoning?.summary?.[0]){let t=e.chunk.additional_kwargs.reasoning.summary[0];return!t||!t.text?null:{type:`text`,text:t.text,index:t.index??0}}return null}function y(e){let t=e.chunk?.content;return!t||!Array.isArray(t)||!t.length||!t[0]?null:t[0].type===`redacted_thinking`&&t[0].data?t[0].data:null}function b(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const x=`root`;var S=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=x,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=c,this.config=e,this.messagesInProcess={},this.agentName=e.agentName,this.graphId=e.graphId,this.assistantConfig=e.assistantConfig,this.reasoningProcess=null;let t=this,n=e.headerFactory??(()=>t.headers);e?.client&&e.headerFactory&&console.debug("[@ag-ui/langgraph] Both `config.client` and `config.headerFactory` were set. Custom clients bypass the adapter's onRequest hook — `headerFactory` will not be invoked. Either omit `client` to enable adapter-managed header forwarding, or wire headers into your custom client directly."),this.client=e?.client??new a({apiUrl:e.deploymentUrl,apiKey:e.langsmithApiKey,defaultHeaders:{...e.propertyHeaders??{}},onRequest:(e,t)=>{let r=n();return!r||Object.keys(r).length===0?t:{...t,headers:{...t.headers,...r}}}})}clone(){let e=Object.assign(super.clone(),{config:this.config,messagesInProcess:structuredClone(this.messagesInProcess),agentName:this.agentName,graphId:this.graphId,assistantConfig:this.assistantConfig,reasoningProcess:this.reasoningProcess?structuredClone(this.reasoningProcess):null,constantSchemaKeys:[...this.constantSchemaKeys],headers:{...this.headers},client:this.client,assistant:this.assistant,activeRun:this.activeRun?structuredClone(this.activeRun):void 0,cancelRequested:this.cancelRequested,cancelSent:this.cancelSent,subgraphs:this.subgraphs?new Set(this.subgraphs):new Set,currentSubgraph:x});if(!this.config.client){let t=this.config.headerFactory??(()=>e.headers);e.client=new a({apiUrl:this.config.deploymentUrl,apiKey:this.config.langsmithApiKey,defaultHeaders:{...this.config.propertyHeaders??{}},onRequest:(e,n)=>{let r=t();return!r||Object.keys(r).length===0?n:{...n,headers:{...n.headers,...r}}}})}return e}dispatchEvent(e){return this.subscriber.next(e),!0}run(e){return new i(t=>(this.runAgentStream(e,t).catch(e=>{console.error(`[LangGraph] runAgentStream error:`,e),t.closed||t.error(e)}),()=>{}))}async runAgentStream(e,t){this.activeRun={id:e.runId,threadId:e.threadId,hasFunctionStreaming:!1,modelMadeToolCall:!1},this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.subscriber=t,this.assistant||=await this.getAssistant();let n=e.threadId??r(),i=e.forwardedProps?.streamMode??[`events`,`values`,`updates`,`messages-tuple`],a=await this.prepareStream({...e,threadId:n},i);if(!a)return t.error(`No stream to regenerate`);await this.handleStreamEvents(a,n,t,e,Array.isArray(i)?i:[i])}async prepareRegenerateStream(e,t){let{threadId:n,messageCheckpoint:r,forwardedProps:i}=e,a=await this.getCheckpointByMessage(r.id,n);if(this.assistant||=await this.getAssistant(),!a)return this.subscriber.error(`No checkpoint found for message`);let o=await this.client.threads.updateState(n,{values:this.langGraphDefaultMergeState(a.values,[],e),checkpointId:a.checkpoint.checkpoint_id,asNode:a.next?.[0]??`__start__`}),s,c=[this.assistantConfig,i?.config].filter(Boolean);c.length&&(s=await this.mergeConfigs({configs:c,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys??null}));let l={...e.forwardedProps??{},input:this.langGraphDefaultMergeState(a.values,[r],e),checkpointId:o.checkpoint.checkpoint_id,streamMode:t,config:s};return{streamResponse:this.client.runs.stream(n,this.assistant.assistant_id,l),state:a,streamMode:t}}async prepareStream(e,n){let{threadId:i,state:a,messages:s,tools:c,context:l,forwardedProps:d}=e;this.activeRun.manuallyEmittedState=null;let f=d?.nodeName,p=i??r();this.assistant||=await this.getAssistant();let m=await this.getOrCreateThread(p,d?.threadMetadata);this.activeRun.threadId=m.thread_id;let h=await this.client.threads.getState(m.thread_id)??{values:{}},_=h.values.messages??[],v=g(s),y=this.langGraphDefaultMergeState({...a,messages:_},v,e),b={...h,values:{...y,messages:[..._,...y.messages??[]]}},x=b.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),_.filter(e=>e.type!==`system`).length>s.filter(e=>e.role!==`system`).length){let t=null;for(let e=s.length-1;e>=0;e--)if(s[e].role===`user`){t=g([s[e]])[0];break}return t?this.prepareRegenerateStream({...e,messageCheckpoint:t},n):this.subscriber.error(`No user message found in messages to regenerate`)}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let S=!d?.command?.resume&&p&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(S===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(p,{values:a,asNode:e?.source})}let C=u({mode:S,state:x,schemaKeys:this.activeRun.schemaKeys}),w,T=[this.assistantConfig,d?.config].filter(Boolean);T.length&&(w=await this.mergeConfigs({configs:T,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:E,...D}=d;if(E?.resume&&typeof E.resume==`string`)try{E.resume=JSON.parse(E.resume)}catch{}let O=new Set(this.activeRun.schemaKeys?.context??[]),k=w?.configurable??{},A={},j={};for(let[e,t]of Object.entries(k))O.has(e)?A[e]=t:j[e]=t;let M={...A},N=w?{...w,configurable:Object.keys(j).length>0?j:void 0}:void 0,P=Object.keys(M).length>0,F=N?.configurable!=null&&Object.keys(N.configurable).length>0;if(P&&F){let e=Object.keys(j);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let I=(()=>{if(!N)return;if(F&&!P)return N;let{configurable:e,...t}=N;return Object.keys(t).length>0?t:void 0})(),L=Object.fromEntries(Object.entries(this.headers??{}).filter(([e])=>e.toLowerCase().startsWith(`x-`))),R=Object.keys(L).length>0?{...I??{},configurable:{...I?.configurable??{},copilotkit_forwarded_headers:L}}:I,z={...D,command:E,streamMode:n,input:C,config:R,...P?{context:M}:{}},B=(h.tasks??[]).flatMap(e=>e.interrupts??[]);return B?.length&&!d?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:p,runId:e.runId}),this.handleNodeChange(f),B.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:p,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(p,this.assistant.assistant_id,z),state:b}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:c}=i,l=c?.nodeName;this.subscriber=r;let u=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:d,state:f}=e;this.activeRun.prevNodeName=null;let p={},m=f;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(l);for await(let e of d){if(this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId&&this.activeRun?.id){try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}try{await d?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,c=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),l=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!c&&!l&&e.event!==`error`)continue;let h=e;if(e.event===`error`){this.dispatchEvent({type:t.RUN_ERROR,message:e.data.message,rawEvent:e});break}if(e.event===`updates`)continue;if(e.event===`values`){p={...p,...h.data};continue}else if(r&&h.event.startsWith(`values|`)){p={...p,...h.data};continue}let g=h.data,_=g.metadata??{},v=_.langgraph_node,y=g.event,b=_.langgraph_checkpoint_ns??``,S=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&S&&this.subgraphs.add(S);let C=S&&this.subgraphs.has(S)?S:x;if(C!==this.currentSubgraph&&(this.currentSubgraph=C,await this.getStateAndMessagesSnapshots(n)),_.run_id&&(this.activeRun.id=_.run_id,this.activeRun.serverRunIdKnown=!0,this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId))try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}if(v&&v!==this.activeRun.nodeName&&this.handleNodeChange(v),u||=y===o.OnCustomEvent&&g.name===s.Exit,y===o.OnChainEnd&&g.data?.output!=null){let e=g.data.output;if(typeof e==`object`&&!Array.isArray(e))p={...p,...e};else if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&t.lg_name===`Command`&&t.update&&typeof t.update==`object`&&(p={...p,...t.update})}if(y===o.OnChainEnd&&this.activeRun.nodeName===v&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(p={...p,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===v)&&this.handleNodeChange(v),m.values=this.activeRun.manuallyEmittedState??p,!this.activeRun.nodeName)continue;let w=JSON.stringify(m)!==JSON.stringify(f);!this.activeRun.modelMadeToolCall&&(w||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(f=m,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(f),rawEvent:h})),this.dispatchEvent({type:t.RAW,event:g}),this.handleSingleEvent(g)}f=await this.client.threads.getState(n);let e=(f.tasks??[]).flatMap(e=>e.interrupts??[]),c=f.next.length===0,h=f.metadata?.writes??{},g=this.activeRun.nodeName;return e?.length||(g=c?`__end__`:f.next[0]??Object.keys(h)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(g),this.handleNodeChange(void 0),await this.getStateAndMessagesSnapshots(n),this.dispatchEvent({type:t.RUN_FINISHED,threadId:n,runId:this.activeRun.id}),this.cancelRequested=!1,this.cancelSent=!1,this.activeRun=void 0,r.complete()}catch(e){return r.error(e)}}async getStateAndMessagesSnapshots(e){let n=await this.client.threads.getState(e);this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(n)});let r=n.values.messages??[];this.dispatchEvent({type:t.MESSAGES_SNAPSHOT,messages:h(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===o.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case o.OnChatModelStream:let n=e.metadata[`emit-messages`]??!0,i=e.metadata[`emit-tool-calls`]??!0;if(e.data.chunk.response_metadata.finish_reason)return;let a=this.getMessageInProgress(this.activeRun.id),c=!!a?.id,l=e.data.chunk.tool_call_chunks?.[0],u=e.metadata.predict_state?.some(e=>e.tool===l?.name),d=!c&&l?.name,f=c&&a?.toolCallId&&l?.args,p=c&&a?.toolCallId&&!l;(p||f||d)&&(this.activeRun.hasFunctionStreaming=!0);let m=v(e.data),h=y(e.data),g=b(e.data.chunk.content),_=!!(!l&&g),x=c&&!a?.toolCallId&&!_;if(m){this.handleReasoningEvent(m);break}if(h&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:h});break}if(!m&&this.reasoningProcess&&(this.reasoningProcess.signature&&this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:this.reasoningProcess.signature}),this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),u&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),p){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(x){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(d&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:l.id,toolCallName:l.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(l.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:l.id,toolCallName:l.name}));break}if(f&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:l.args,rawEvent:e});break}if(_&&n){a||=(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.chunk.id,rawEvent:e}),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:null,toolCallName:null}),this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:a.id,delta:g,rawEvent:e});break}break;case o.OnChatModelEnd:if(this.getMessageInProgress(this.activeRun.id)?.toolCallId){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(this.getMessageInProgress(this.activeRun.id)?.id){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case o.OnCustomEvent:if(e.name===s.ManuallyEmitMessage){this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.message_id,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:e.data.message_id,delta:e.data.message,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:e.data.message_id,rawEvent:e});break}if(e.name===s.ManuallyEmitToolCall){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.data.id,toolCallName:e.data.name,parentMessageId:e.data.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:e.data.id,delta:e.data.args,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:e.data.id,rawEvent:e});break}e.name===s.ManuallyEmitState&&(this.activeRun.manuallyEmittedState=e.data,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:e})),this.dispatchEvent({type:t.CUSTOM,name:e.name,value:e.data,rawEvent:e});break;case o.OnToolEnd:let S=e.data?.output;if(S&&!S.tool_call_id&&S.update?.messages?.find(e=>e.type===`tool`)&&(S=S.update?.messages?.find(e=>e.type===`tool`)),S&&S.update?.messages?.length){S.update?.messages.filter(e=>e.type===`tool`).forEach(n=>{this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:n.tool_call_id,toolCallName:n.name??``,parentMessageId:n.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:n.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e})),this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:n.tool_call_id,content:typeof n?.content==`string`?n?.content:JSON.stringify(n?.content),messageId:r(),rawEvent:e,role:`tool`})}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}this.emittedToolCallStartIds.has(S.tool_call_id)||(this.emittedToolCallStartIds.add(S.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:S.tool_call_id,toolCallName:S.name,parentMessageId:S.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:S.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:S.tool_call_id,rawEvent:e}));let C=Array.isArray(S.content)?S.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):S.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:S.tool_call_id,content:C,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case o.OnToolError:this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}}handleMessagesTupleEvent(e){let n=e[0];if(n.type&&n.type!==`AIMessageChunk`)return;let r=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.find(e=>e.type===`text`)?.text:null,i=n.tool_call_chunks,a=n.response_metadata?.finish_reason===`stop`,o=this.getMessageInProgress(this.activeRun.id);if(i?.length>0){let e=i[0];e.name?(o?.id&&!o?.toolCallId&&(this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.id||n.id,toolCallName:e.name,parentMessageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:e.id||n.id,toolCallName:e.name}),this.activeRun.hasFunctionStreaming=!0):e.args&&o?.toolCallId&&this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:e.args});return}if(a){o?.toolCallId?this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:o.toolCallId}):o?.id&&this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null;return}!r&&!i?.length||r&&(o||(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:null,toolCallName:null})),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:(this.getMessageInProgress(this.activeRun.id)??{id:n.id}).id,delta:r}))}abortRun(){this.cancelRequested=!0;let e=this.activeRun?.threadId,t=this.activeRun?.id;e&&t&&!this.cancelSent&&this.client.runs.cancel(e,t).then(()=>{this.cancelSent=!0}).catch(()=>{}),super.abortRun()}handleReasoningEvent(e){if(!e||!e.type||!e.text)return;let n=e.index;if(this.reasoningProcess?.index&&this.reasoningProcess.index!==n&&(this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),!this.reasoningProcess){let e=r();this.dispatchEvent({type:t.REASONING_START,messageId:e}),this.reasoningProcess={index:n,messageId:e}}this.reasoningProcess.type!==e.type&&(this.dispatchEvent({type:t.REASONING_MESSAGE_START,messageId:this.reasoningProcess.messageId,role:`reasoning`}),this.reasoningProcess.type=e.type),e.signature&&(this.reasoningProcess.signature=e.signature),this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_CONTENT,messageId:this.reasoningProcess.messageId,delta:e.text})}getStateSnapshot(e){let t=e.values,n=this.activeRun.schemaKeys;return n?.output&&(t=l(t,[...this.constantSchemaKeys,...n.output])),t}async getOrCreateThread(e,t){let n;try{try{n=await this.getThread(e)}catch{n=await this.createThread({threadId:e,metadata:t})}}catch(e){throw Error(`Failed to create thread: ${e.message}`)}return n}async getThread(e){return this.client.threads.get(e)}async createThread(e){return this.client.threads.create(e)}async mergeConfigs({configs:e,assistant:t,schemaKeys:n}){return e.reduce((e,t)=>{let r=e.configurable;t.configurable&&(r=n?.config?l(t?.configurable,[...this.constantSchemaKeys,...n?.config??[],...n?.context??[]]):t?.configurable);let i={...e,...t,configurable:r},a=e.recursion_limit==null&&t.recursion_limit===25,o=JSON.stringify(i)!==JSON.stringify(e),s=a&&JSON.stringify({...i,recursion_limit:null})===JSON.stringify({...e,recursion_limit:null});return o&&!s?{...e,...i}:e},t.config)}getMessageInProgress(e){return this.messagesInProcess[e]}setMessageInProgress(e,t){this.messagesInProcess={...this.messagesInProcess,[e]:{...this.messagesInProcess[e],...t}}}async getAssistant(){try{let e=await this.client.assistants.search({graphId:this.graphId,limit:1}),t=e.find(e=>e.graph_id===this.graphId);if(!t){let t=`
|
|
2
2
|
No agent found with graph ID ${this.graphId} found..\n
|
|
3
3
|
|
|
4
4
|
These are the available agents: [${e.map(e=>`${e.graph_id} (ID: ${e.assistant_id})`).join(`, `)}]
|