要么手写个迭代器自定义event,要摸使用langchain自带的事件
initial_state = {
"messages": chat_history or [] + [_HumanMessage(content=message)],
"user_input": message,
"session_id": session_id,
"iteration": 0,
}
config = {"configurable": {"thread_id": session_id}}
async for event in self.graph.astream_events(
initial_state, config=config, version="v2"
):
你的业务
from langchain_core.runnables import RunnableConfig as _RunnableConfig
from datetime import datetime
from ..state import searchState as _searchState
from ...schemas.agents.base_dsl import BaseDSL as _BaseDSL
from ...agents.search_node_agent import search_node_agent as _search_node_agent
async def search_nodes_node(
state: _searchState,
config: _RunnableConfig,
) -> _searchState:
"""Search nodes in the workflow graph."""
callbacks = config.get("callbacks")
if callbacks:
cpdd_start_event = {
"event": "cpdd",
"cpdd": "开始搜索可用节点",
"node_type": "search_nodes",
"status": "start",
"timestamp": datetime.now().isoformat(),
"data": {"query": state["messages"][-1].content}
}
await callbacks.on_chain_start(
serialized={"name": "cpdd_event", "event_type": "cpdd"},
inputs=cpdd_start_event
)
query = state["messages"][-1].content
response = _search_node_agent.invoke(
{"messages": [{"role": "user", "content": query}]}
)["structured_response"]
if callbacks:
cpdd_end_event = {
"event": "cpdd",
"cpdd": "节点搜索完成",
"node_type": "search_nodes",
"status": "end",
"timestamp": datetime.now().isoformat(),
"data": {
"nodes_found": len(response.nodes_list),
"edges_found": len(response.edges_list)
}
}
await callbacks.on_chain_end(outputs=cpdd_end_event)
state["nodes_list"] = response.nodes_list
state["edges_list"] = response.edges_list
state["dsl"] = _BaseDSL(nodes=[], edges=[])
state['dsl_json'] = state['dsl'].model_dump_json(indent=2, exclude_none=True, ensure_ascii=False)
return state