@ag-ui/langgraph 0.0.41 → 0.0.42-alpha.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/index.d.mts +14 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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";import{tool as o}from"@langchain/core/tools";import{SystemMessage as s}from"@langchain/core/messages";import{A2UI_OPERATIONS_KEY as c,BASIC_CATALOG_ID as l,GENERATE_A2UI_ARG_DESCRIPTIONS as u,RENDER_A2UI_TOOL_DEF as d,buildA2UIEnvelope as f,prepareA2UIRequest as p,resolveA2UIToolParams as m,runA2UIGenerationWithRecovery as h,wrapErrorEnvelope as g}from"@ag-ui/a2ui-toolkit";let _=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}({}),v=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const y=[`messages`,`tools`];function b(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function x({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=b(r,[...y,...n.input])),r}const S=new Set([`image`,`audio`,`video`,`document`]);function C(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function w(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 T(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(S.has(n.type)){let e=C(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 E(e){return e.map(e=>{switch(e.type){case`human`:let t;return t=Array.isArray(e.content)?w(e.content):O(j(e.content)),{id:e.id,role:`user`,content:t};case`generic`:case`ai`:let n=j(e.content);return{id:e.id,role:`assistant`,content:n?O(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:O(j(e.content))};case`tool`:return{id:e.id,role:`tool`,content:O(j(e.content)),toolCallId:e.tool_call_id};default:throw Error(`message type returned from LangGraph is not supported.`)}})}function D(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)?T(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 O(e){return typeof e==`string`?e:JSON.stringify(e)}function k(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 A(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 j(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const M=`root`;var N=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=M,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=y,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:M});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:o,tools:s,context:c,forwardedProps:l}=e;this.activeRun.manuallyEmittedState=null;let u=l?.nodeName,d=i??r();this.assistant||=await this.getAssistant();let f=await this.getOrCreateThread(d,l?.threadMetadata);this.activeRun.threadId=f.thread_id;let p=await this.client.threads.getState(f.thread_id)??{values:{}},m=p.values.messages??[],h=D(o),g=this.langGraphDefaultMergeState({...a,messages:m},h,e),v={...p,values:{...g,messages:[...m,...g.messages??[]]}},y=v.values;this.activeRun.schemaKeys=await this.getSchemaKeys();let b=m.filter(e=>e.type!==`system`).length,S=o.filter(e=>e.role!==`system`).length;if(!l?.command?.resume&&b>S){let t=null;for(let e=o.length-1;e>=0;e--)if(o[e].role===`user`){t=D([o[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 C=!l?.command?.resume&&d&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(C===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(d,{values:a,asNode:e?.source})}let w=x({mode:C,state:y,schemaKeys:this.activeRun.schemaKeys}),T,E=[this.assistantConfig,l?.config].filter(Boolean);E.length&&(T=await this.mergeConfigs({configs:E,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:O,...k}=l;if(O?.resume&&typeof O.resume==`string`)try{O.resume=JSON.parse(O.resume)}catch{}let A=new Set(this.activeRun.schemaKeys?.context??[]),j=T?.configurable??{},M={},N={};for(let[e,t]of Object.entries(j))A.has(e)?M[e]=t:N[e]=t;let P={...M},F=T?{...T,configurable:Object.keys(N).length>0?N:void 0}:void 0,I=Object.keys(P).length>0,L=F?.configurable!=null&&Object.keys(F.configurable).length>0;if(I&&L){let e=Object.keys(N);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let R=(()=>{if(!F)return;if(L&&!I)return F;let{configurable:e,...t}=F;return Object.keys(t).length>0?t:void 0})(),z=Object.fromEntries(Object.entries(this.headers??{}).filter(([e])=>e.toLowerCase().startsWith(`x-`))),B=Object.keys(z).length>0?{...R??{},configurable:{...R?.configurable??{},copilotkit_forwarded_headers:z}}:R,V={...k,command:O,streamMode:n,input:w,config:B,...I?{context:P}:{}},H=(p.tasks??[]).flatMap(e=>e.interrupts??[]);return H?.length&&!l?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:d,runId:e.runId}),this.handleNodeChange(u),H.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:_.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:d,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(d,this.assistant.assistant_id,V),state:v}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:o}=i,s=o?.nodeName;this.subscriber=r;let c=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:l,state:u}=e;this.activeRun.prevNodeName=null;let d={},f=u;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(s);for await(let e of l){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 l?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,o=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),s=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!o&&!s&&e.event!==`error`)continue;let p=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`){d={...d,...p.data};continue}else if(r&&p.event.startsWith(`values|`)){d={...d,...p.data};continue}let m=p.data,h=m.metadata??{},g=h.langgraph_node,y=m.event,b=h.langgraph_checkpoint_ns??``,x=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&x&&this.subgraphs.add(x);let S=x&&this.subgraphs.has(x)?x:M;if(S!==this.currentSubgraph&&(this.currentSubgraph=S,await this.getStateAndMessagesSnapshots(n)),h.run_id&&(this.activeRun.id=h.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(g&&g!==this.activeRun.nodeName&&this.handleNodeChange(g),c||=y===_.OnCustomEvent&&m.name===v.Exit,y===_.OnChainEnd&&m.data?.output!=null){let e=m.data.output;if(typeof e==`object`&&!Array.isArray(e))d={...d,...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`&&(d={...d,...t.update})}if(y===_.OnChainEnd&&this.activeRun.nodeName===g&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(d={...d,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===g)&&this.handleNodeChange(g),f.values=this.activeRun.manuallyEmittedState??d,!this.activeRun.nodeName)continue;let C=JSON.stringify(f)!==JSON.stringify(u);!this.activeRun.modelMadeToolCall&&(C||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(u=f,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(u),rawEvent:p})),this.dispatchEvent({type:t.RAW,event:m}),this.handleSingleEvent(m)}u=await this.client.threads.getState(n);let e=(u.tasks??[]).flatMap(e=>e.interrupts??[]),o=u.next.length===0,p=u.metadata?.writes??{},m=this.activeRun.nodeName;return e?.length||(m=o?`__end__`:u.next[0]??Object.keys(p)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:_.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(m),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:E(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===_.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case _.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),o=!!a?.id,s=e.data.chunk.tool_call_chunks?.[0],c=e.metadata.predict_state?.some(e=>e.tool===s?.name),l=!o&&s?.name,u=o&&a?.toolCallId&&s?.args,d=o&&a?.toolCallId&&!s;(d||u||l)&&(this.activeRun.hasFunctionStreaming=!0);let f=k(e.data),p=A(e.data),m=j(e.data.chunk.content),h=!!(!s&&m),g=o&&!a?.toolCallId&&!h;if(f){this.handleReasoningEvent(f);break}if(p&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:p});break}if(!f&&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),c&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),d){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(g){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(l&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:s.id,toolCallName:s.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(s.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:s.id,toolCallName:s.name}));break}if(u&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:s.args,rawEvent:e});break}if(h&&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:m,rawEvent:e});break}break;case _.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 _.OnCustomEvent:if(e.name===v.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===v.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===v.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 _.OnToolEnd:let y=e.data?.output;if(y&&!y.tool_call_id&&y.update?.messages?.find(e=>e.type===`tool`)&&(y=y.update?.messages?.find(e=>e.type===`tool`)),y&&y.update?.messages?.length){y.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(y.tool_call_id)||(this.emittedToolCallStartIds.add(y.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:y.tool_call_id,toolCallName:y.name,parentMessageId:y.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:y.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:y.tool_call_id,rawEvent:e}));let b=Array.isArray(y.content)?y.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):y.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:y.tool_call_id,content:b,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case _.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=b(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?b(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";import{tool as o}from"@langchain/core/tools";import{SystemMessage as s}from"@langchain/core/messages";import{A2UI_OPERATIONS_KEY as c,BASIC_CATALOG_ID as l,GENERATE_A2UI_ARG_DESCRIPTIONS as u,RENDER_A2UI_TOOL_DEF as d,buildA2UIEnvelope as f,prepareA2UIRequest as p,resolveA2UIToolParams as m,runA2UIGenerationWithRecovery as h,wrapErrorEnvelope as g}from"@ag-ui/a2ui-toolkit";let _=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}({}),v=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const y=[`messages`,`tools`];function b(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function x({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=b(r,[...y,...n.input])),r}const S=new Set([`image`,`audio`,`video`,`document`]);function C(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function w(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 T(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(S.has(n.type)){let e=C(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 E(e){return typeof e==`object`&&!!e&&e.type===`reasoning`}function D(e){if(Array.isArray(e.summary)){let t=e.summary.map(e=>e?.text).filter(e=>!!e);if(t.length)return t.join(`
|
|
2
|
+
`)}return e.reasoning??e.text??``}function O(e,t,n=0){let r=D(e),i=e.encrypted_content;if(!e.id&&!r&&!i)return null;let a={id:String(e.id??`${t}-reasoning-${n}`),role:`reasoning`,content:r};return i&&(a.encryptedValue=i),a}function k(e){let t={type:`reasoning`,id:e.id,summary:e.content?[{type:`summary_text`,text:e.content}]:[]};return e.encryptedValue&&(t.encrypted_content=e.encryptedValue),t}function A(e){let t=[];for(let n of e)switch(n.type){case`human`:{let e;e=Array.isArray(n.content)?w(n.content):M(F(n.content)),t.push({id:n.id,role:`user`,content:e});break}case`generic`:case`ai`:{Array.isArray(n.content)&&n.content.forEach((e,r)=>{if(E(e)){let i=O(e,n.id,r);i&&t.push(i)}});let e=F(n.content);t.push({id:n.id,role:`assistant`,content:e?M(e):``,toolCalls:n.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args??{})}}))});break}case`system`:t.push({id:n.id,role:`system`,content:M(F(n.content))});break;case`tool`:t.push({id:n.id,role:`tool`,content:M(F(n.content)),toolCallId:n.tool_call_id});break;default:throw Error(`message type returned from LangGraph is not supported.`)}return t}function j(e){let t=[],n=[];for(let r of e)switch(r.role){case`reasoning`:n.push(k(r));continue;case`developer`:continue;case`user`:{n=[];let e;e=typeof r.content==`string`?r.content:Array.isArray(r.content)?T(r.content):String(r.content),t.push({id:r.id,role:r.role,content:e,type:`human`});break}case`assistant`:{let e;if(n.length){let t=[...n];r.content&&t.push({type:`text`,text:r.content}),e=t,n=[]}else e=r.content??``;t.push({id:r.id,type:`ai`,role:r.role,content:e,tool_calls:(r.toolCalls??[]).map(e=>({id:e.id,name:e.function.name,args:e.function.arguments?JSON.parse(e.function.arguments):{},type:`tool_call`}))});break}case`system`:n=[],t.push({id:r.id,role:r.role,content:r.content,type:`system`});break;case`tool`:n=[],t.push({content:r.content,role:r.role,type:r.role,tool_call_id:r.toolCallId,id:r.id});break;default:throw console.error(`Message role ${r.role} is not implemented`),Error(`message role is not supported.`)}return t}function M(e){return typeof e==`string`?e:JSON.stringify(e)}function N(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`&&Array.isArray(e.summary)){if(e.summary.length===0&&e.id)return{type:`text`,text:``,index:e.index??0,id:String(e.id)};let t=e.summary[0];if(t&&typeof t==`object`&&(t.text||e.id)){let n={type:`text`,text:t.text??``,index:t.index??0};return e.id&&(t.index??0)===0&&(n.id=String(e.id)),n}}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 P(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 F(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const I=`root`;var L=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=I,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=y,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:I});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.pendingReasoningId=void 0,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:o,tools:s,context:c,forwardedProps:l}=e;this.activeRun.manuallyEmittedState=null;let u=l?.nodeName,d=i??r();this.assistant||=await this.getAssistant();let f=await this.getOrCreateThread(d,l?.threadMetadata);this.activeRun.threadId=f.thread_id;let p=await this.client.threads.getState(f.thread_id)??{values:{}},m=p.values.messages??[],h=j(o),g=this.langGraphDefaultMergeState({...a,messages:m},h,e),v={...p,values:{...g,messages:[...m,...g.messages??[]]}},y=v.values;this.activeRun.schemaKeys=await this.getSchemaKeys();let b=m.filter(e=>e.type!==`system`).length,S=o.filter(e=>e.role!==`system`).length;if(!l?.command?.resume&&b>S){let t=new Set(m.map(e=>e.id).filter(e=>!!e)),r=o.filter(e=>e.role!==`tool`&&!!e.id).map(e=>e.id);if(!(r.length>0&&r.every(e=>t.has(e)))){let r=null,i;for(let e=o.length-1;e>=0;e--)if(o[e].role===`user`){i=o[e].id,r=j([o[e]])[0];break}if(r&&i&&t.has(i))return this.prepareRegenerateStream({...e,messageCheckpoint:r},n)}}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let C=!l?.command?.resume&&d&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(C===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(d,{values:a,asNode:e?.source})}let w=x({mode:C,state:y,schemaKeys:this.activeRun.schemaKeys}),T,E=[this.assistantConfig,l?.config].filter(Boolean);E.length&&(T=await this.mergeConfigs({configs:E,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:D,...O}=l??{};if(D?.resume&&typeof D.resume==`string`)try{D.resume=JSON.parse(D.resume)}catch{}let k=new Set(this.activeRun.schemaKeys?.context??[]),A=T?.configurable??{},M={},N={};for(let[e,t]of Object.entries(A))k.has(e)?M[e]=t:N[e]=t;let P={...M},F=T?{...T,configurable:Object.keys(N).length>0?N:void 0}:void 0,I=Object.keys(P).length>0,L=F?.configurable!=null&&Object.keys(F.configurable).length>0;if(I&&L){let e=Object.keys(N);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let R=(()=>{if(!F)return;if(L&&!I)return F;let{configurable:e,...t}=F;return Object.keys(t).length>0?t:void 0})(),z=Object.fromEntries(Object.entries(this.headers??{}).filter(([e])=>e.toLowerCase().startsWith(`x-`))),B=Object.keys(z).length>0?{...R??{},configurable:{...R?.configurable??{},copilotkit_forwarded_headers:z}}:R,V={...O,command:D,streamMode:n,input:w,config:B,...I?{context:P}:{}},H=(p.tasks??[]).flatMap(e=>e.interrupts??[]);return H?.length&&!l?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:d,runId:e.runId}),this.handleNodeChange(u),H.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:_.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:d,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(d,this.assistant.assistant_id,V),state:v}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:o}=i,s=o?.nodeName;this.subscriber=r;let c=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:l,state:u}=e;this.activeRun.prevNodeName=null;let d={},f=u;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(s);for await(let e of l){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 l?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,o=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),s=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!o&&!s&&e.event!==`error`)continue;let p=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`){d={...d,...p.data};continue}else if(r&&p.event.startsWith(`values|`)){d={...d,...p.data};continue}let m=p.data,h=m.metadata??{},g=h.langgraph_node,y=m.event,b=h.langgraph_checkpoint_ns??``,x=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&x&&this.subgraphs.add(x);let S=x&&this.subgraphs.has(x)?x:I;if(S!==this.currentSubgraph&&(this.currentSubgraph=S,await this.getStateAndMessagesSnapshots(n)),h.run_id&&(this.activeRun.id=h.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(g&&g!==this.activeRun.nodeName&&this.handleNodeChange(g),c||=y===_.OnCustomEvent&&m.name===v.Exit,y===_.OnChainEnd&&m.data?.output!=null){let e=m.data.output;if(typeof e==`object`&&!Array.isArray(e))d={...d,...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`&&(d={...d,...t.update})}if(y===_.OnChainEnd&&this.activeRun.nodeName===g&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(d={...d,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===g)&&this.handleNodeChange(g),f.values=this.activeRun.manuallyEmittedState??d,!this.activeRun.nodeName)continue;let C=JSON.stringify(f)!==JSON.stringify(u);!this.activeRun.modelMadeToolCall&&(C||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(u=f,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(u),rawEvent:p})),this.dispatchEvent({type:t.RAW,event:m}),this.handleSingleEvent(m)}u=await this.client.threads.getState(n);let e=(u.tasks??[]).flatMap(e=>e.interrupts??[]),o=u.next.length===0,p=u.metadata?.writes??{},m=this.activeRun.nodeName;return e?.length||(m=o?`__end__`:u.next[0]??Object.keys(p)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:_.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(m),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:A(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===_.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case _.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),o=!!a?.id,s=e.data.chunk.tool_call_chunks?.[0],c=e.metadata.predict_state?.some(e=>e.tool===s?.name),l=!o&&s?.name,u=o&&a?.toolCallId&&s?.args,d=o&&a?.toolCallId&&!s;(d||u||l)&&(this.activeRun.hasFunctionStreaming=!0);let f=N(e.data),p=P(e.data),m=F(e.data.chunk.content),h=!!(!s&&m),g=o&&!a?.toolCallId&&!h;if(f){this.handleReasoningEvent(f);break}if(p&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:p});break}if(!f&&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),c&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),d){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(g){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(l&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:s.id,toolCallName:s.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(s.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:s.id,toolCallName:s.name}));break}if(u&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:s.args,rawEvent:e});break}if(h&&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:m,rawEvent:e});break}break;case _.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 _.OnCustomEvent:if(e.name===v.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===v.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===v.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 _.OnToolEnd:let y=e.data?.output;if(y&&!y.tool_call_id&&y.update?.messages?.find(e=>e.type===`tool`)&&(y=y.update?.messages?.find(e=>e.type===`tool`)),y&&y.update?.messages?.length){y.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(y.tool_call_id)||(this.emittedToolCallStartIds.add(y.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:y.tool_call_id,toolCallName:y.name,parentMessageId:y.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:y.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:y.tool_call_id,rawEvent:e}));let b=Array.isArray(y.content)?y.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):y.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:y.tool_call_id,content:b,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case _.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)return;if(!e.text){e.id&&(this.pendingReasoningId=e.id);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 i=e.id??this.pendingReasoningId??r();this.pendingReasoningId=void 0,this.dispatchEvent({type:t.REASONING_START,messageId:i}),this.reasoningProcess={index:n,messageId:i}}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=b(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?b(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
3
|
No agent found with graph ID ${this.graphId} found..\n
|
|
3
4
|
|
|
4
5
|
These are the available agents: [${e.map(e=>`${e.graph_id} (ID: ${e.assistant_id})`).join(`, `)}]
|
|
5
|
-
`;throw console.error(t),Error(t)}return t}catch(e){let n=Error(`Failed to retrieve assistant: ${e.message}`);throw this.dispatchEvent({type:t.RUN_ERROR,message:n.message}),this.subscriber.error(),n}}async getSchemaKeys(){try{let e=await this.client.assistants.getSchemas(this.assistant.assistant_id),t=null,n=[];if(`context_schema`in e&&e.context_schema?.properties&&(n=Object.keys(e.context_schema.properties)),e.config_schema?.properties&&(t=Object.keys(e.config_schema.properties)),!e.input_schema?.properties||!e.output_schema?.properties)return{config:[],input:null,output:null,context:n};let r=Object.keys(e.input_schema.properties),i=Object.keys(e.output_schema.properties);return{input:r&&r.length?[...r,...this.constantSchemaKeys]:null,output:i&&i.length?[...i,...this.constantSchemaKeys]:null,context:n,config:t}}catch{return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(e,t,n){t.length>0&&`role`in t[0]&&t[0].role===`system`&&(t=t.slice(1));let r=e.messages||[],i=new Set(r.map(e=>e.id)),a=t.filter(e=>!i.has(e.id)),o=[...n.tools??[],...e.tools??[]].reduce((e,t)=>{let n=t;return t.type||(n={type:`function`,name:t.name,function:{name:t.name,description:t.description,parameters:t.parameters}}),e.find(e=>e.name===n.name||e.function.name===n.function.name)?e:[...e,n]},[]),s=n.forwardedProps?.injectA2UITool,c={tools:o,context:n.context};return s!==void 0&&(c.inject_a2ui_tool=s),{...e,messages:a,tools:o,"ag-ui":c,copilotkit:{...e.copilotkit,actions:o}}}handleNodeChange(e){e===`__end__`&&(e=void 0),e!==this.activeRun?.nodeName&&(this.activeRun?.nodeName&&this.endStep(),e&&this.startStep(e)),this.activeRun.nodeName=e}startStep(e){this.dispatchEvent({type:t.STEP_STARTED,stepName:e})}endStep(){this.dispatchEvent({type:t.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(e,t,n){let r=n?.checkpoint_id?{checkpoint:{checkpoint_id:n.checkpoint_id}}:void 0,i=[...await this.client.threads.getHistory(t,r)].reverse(),a=i.find(t=>t.values.messages?.some(t=>t.id===e));if(!a)throw Error(`Message not found`);let o=a.values.messages??[],s=o.findIndex(t=>t.id===e);if(o.slice(s+1).length)return this.getCheckpointByMessage(e,t,a.parent_checkpoint);let c=i.indexOf(a),{messages:l,...u}=a.values,d=i[c-1]??{...a,values:{}};return{...d,values:{...d.values,...u}}}};function
|
|
6
|
+
`;throw console.error(t),Error(t)}return t}catch(e){let n=Error(`Failed to retrieve assistant: ${e.message}`);throw this.dispatchEvent({type:t.RUN_ERROR,message:n.message}),this.subscriber.error(),n}}async getSchemaKeys(){try{let e=await this.client.assistants.getSchemas(this.assistant.assistant_id),t=null,n=[];if(`context_schema`in e&&e.context_schema?.properties&&(n=Object.keys(e.context_schema.properties)),e.config_schema?.properties&&(t=Object.keys(e.config_schema.properties)),!e.input_schema?.properties||!e.output_schema?.properties)return{config:[],input:null,output:null,context:n};let r=Object.keys(e.input_schema.properties),i=Object.keys(e.output_schema.properties);return{input:r&&r.length?[...r,...this.constantSchemaKeys]:null,output:i&&i.length?[...i,...this.constantSchemaKeys]:null,context:n,config:t}}catch{return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(e,t,n){t.length>0&&`role`in t[0]&&t[0].role===`system`&&(t=t.slice(1));let r=e.messages||[],i=new Set(r.map(e=>e.id)),a=t.filter(e=>!i.has(e.id)),o=[...n.tools??[],...e.tools??[]].reduce((e,t)=>{let n=t;return t.type||(n={type:`function`,name:t.name,function:{name:t.name,description:t.description,parameters:t.parameters}}),e.find(e=>e.name===n.name||e.function.name===n.function.name)?e:[...e,n]},[]),s=n.forwardedProps?.injectA2UITool,c={tools:o,context:n.context};return s!==void 0&&(c.inject_a2ui_tool=s),{...e,messages:a,tools:o,"ag-ui":c,copilotkit:{...e.copilotkit,actions:o}}}handleNodeChange(e){e===`__end__`&&(e=void 0),e!==this.activeRun?.nodeName&&(this.activeRun?.nodeName&&this.endStep(),e&&this.startStep(e)),this.activeRun.nodeName=e}startStep(e){this.dispatchEvent({type:t.STEP_STARTED,stepName:e})}endStep(){this.dispatchEvent({type:t.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(e,t,n){let r=n?.checkpoint_id?{checkpoint:{checkpoint_id:n.checkpoint_id}}:void 0,i=[...await this.client.threads.getHistory(t,r)].reverse(),a=i.find(t=>t.values.messages?.some(t=>t.id===e));if(!a)throw Error(`Message not found`);let o=a.values.messages??[],s=o.findIndex(t=>t.id===e);if(o.slice(s+1).length)return this.getCheckpointByMessage(e,t,a.parent_checkpoint);let c=i.indexOf(a),{messages:l,...u}=a.values,d=i[c-1]??{...a,values:{}};return{...d,values:{...d.values,...u}}}};const R=d.function.name;async function z(e,t,n){let r=null,i=await e.stream([new s(t),...n]);for await(let e of i)r=r===null?e:r.concat(e);let a=r?.tool_calls??[];for(let e of a)if(e.name==null||e.name===R)return e.args??{};return null}function B(e){let{model:t,guidelines:n,defaultSurfaceId:r,defaultCatalogId:i,toolName:a,toolDescription:s,catalog:c,recovery:l,onA2UIAttempt:_}=m(e),v=t;return o(async(e,t)=>{let a=t.state??{},o=(a.messages??[]).slice(0,-1),s=p({intent:e.intent,targetSurfaceId:e.target_surface_id,changes:e.changes,messages:o,state:a,guidelines:n});if(s.error)return g(s.error);if(!v.bindTools)return g(`Provided model does not support bindTools`);let u=v.bindTools([d],{tool_choice:{type:`function`,function:{name:`render_a2ui`}}}),{envelope:m}=await h({basePrompt:s.prompt,catalog:c,config:l,onAttempt:_,invokeSubagent:e=>z(u,e,o),buildEnvelope:t=>f({args:t,isUpdate:s.isUpdate,targetSurfaceId:e.target_surface_id,prior:s.prior,defaultSurfaceId:r,defaultCatalogId:i})});return m},{name:a,description:s,schema:{type:`object`,properties:{intent:{type:`string`,enum:[`create`,`update`],description:u.intent},target_surface_id:{type:`string`,description:u.target_surface_id},changes:{type:`string`,description:u.changes}}}})}var V=class extends n{};export{c as A2UI_OPERATIONS_KEY,l as BASIC_CATALOG_ID,v as CustomEventNames,L as LangGraphAgent,_ as LangGraphEventTypes,V as LangGraphHttpAgent,B as getA2UITools};
|
|
6
7
|
//# sourceMappingURL=index.mjs.map
|