|
| 1 | +"""ACP handler for sync harness LangGraph agent. |
| 2 | +
|
| 3 | +Uses the unified harness surface: ``LangGraphTurn`` wraps the LangGraph |
| 4 | +``astream()`` generator, and ``UnifiedEmitter.yield_turn`` converts it into |
| 5 | +the AgentEx ``TaskMessageUpdate`` event stream expected by the sync ACP. |
| 6 | +
|
| 7 | +Differences from ``030_langgraph`` (bespoke path): |
| 8 | +- No ``create_langgraph_tracing_handler`` boilerplate. |
| 9 | +- No manual text-delta accumulation for the span output. |
| 10 | +- Tool calls are emitted as ``StreamTaskMessageFull`` (not Start+Delta+Done) |
| 11 | + via the same code path as the async/temporal channels. |
| 12 | +- Usage data (token counts) is captured on the ``LangGraphTurn`` object and |
| 13 | + can be read after the turn completes. |
| 14 | +
|
| 15 | +AGX1-377 note: LangGraph emits tool requests as ``StreamTaskMessageFull`` |
| 16 | +events (from "updates"). The ``SpanDeriver`` does not open tool spans from |
| 17 | +Full events today; that gap is tracked in AGX1-373. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import os |
| 23 | +from typing import AsyncGenerator |
| 24 | + |
| 25 | +from dotenv import load_dotenv |
| 26 | + |
| 27 | +load_dotenv() |
| 28 | + |
| 29 | +import agentex.lib.adk as adk |
| 30 | +from project.graph import create_graph |
| 31 | +from agentex.lib.types.acp import SendMessageParams |
| 32 | +from agentex.lib.types.tracing import SGPTracingProcessorConfig |
| 33 | +from agentex.lib.utils.logging import make_logger |
| 34 | +from agentex.lib.sdk.fastacp.fastacp import FastACP |
| 35 | +from agentex.lib.core.harness.emitter import UnifiedEmitter |
| 36 | +from agentex.types.task_message_delta import TextDelta |
| 37 | +from agentex.types.task_message_update import TaskMessageUpdate |
| 38 | +from agentex.types.task_message_content import TaskMessageContent |
| 39 | +from agentex.lib.adk._modules._langgraph_turn import LangGraphTurn |
| 40 | +from agentex.lib.core.tracing.tracing_processor_manager import add_tracing_processor_config |
| 41 | + |
| 42 | +logger = make_logger(__name__) |
| 43 | + |
| 44 | +add_tracing_processor_config( |
| 45 | + SGPTracingProcessorConfig( |
| 46 | + sgp_api_key=os.environ.get("SGP_API_KEY", ""), |
| 47 | + sgp_account_id=os.environ.get("SGP_ACCOUNT_ID", ""), |
| 48 | + sgp_base_url=os.environ.get("SGP_CLIENT_BASE_URL", ""), |
| 49 | + ) |
| 50 | +) |
| 51 | + |
| 52 | +acp = FastACP.create(acp_type="sync") |
| 53 | + |
| 54 | +_graph = None |
| 55 | + |
| 56 | + |
| 57 | +async def get_graph(): |
| 58 | + """Get or create the compiled graph instance.""" |
| 59 | + global _graph |
| 60 | + if _graph is None: |
| 61 | + _graph = await create_graph() |
| 62 | + return _graph |
| 63 | + |
| 64 | + |
| 65 | +@acp.on_message_send |
| 66 | +async def handle_message_send( |
| 67 | + params: SendMessageParams, |
| 68 | +) -> TaskMessageContent | list[TaskMessageContent] | AsyncGenerator[TaskMessageUpdate, None]: |
| 69 | + """Handle incoming messages, streaming tokens and tool calls via unified harness.""" |
| 70 | + graph = await get_graph() |
| 71 | + |
| 72 | + task_id = params.task.id |
| 73 | + user_message = params.content.content |
| 74 | + |
| 75 | + logger.info(f"Processing message for task {task_id}") |
| 76 | + |
| 77 | + async with adk.tracing.span( |
| 78 | + trace_id=task_id, |
| 79 | + task_id=task_id, |
| 80 | + name="message", |
| 81 | + input={"message": user_message}, |
| 82 | + data={"__span_type__": "AGENT_WORKFLOW"}, |
| 83 | + ) as turn_span: |
| 84 | + stream = graph.astream( |
| 85 | + {"messages": [{"role": "user", "content": user_message}]}, |
| 86 | + config={"configurable": {"thread_id": task_id}}, |
| 87 | + stream_mode=["messages", "updates"], |
| 88 | + ) |
| 89 | + |
| 90 | + turn = LangGraphTurn(stream, model=None) |
| 91 | + emitter = UnifiedEmitter( |
| 92 | + task_id=task_id, |
| 93 | + trace_id=task_id, |
| 94 | + parent_span_id=turn_span.id if turn_span else None, |
| 95 | + ) |
| 96 | + |
| 97 | + final_text = "" |
| 98 | + async for event in emitter.yield_turn(turn): |
| 99 | + # Accumulate text deltas so the span's final_output is the assistant |
| 100 | + # text (matching the async tutorial), not the usage metrics. |
| 101 | + delta = getattr(event, "delta", None) |
| 102 | + if isinstance(delta, TextDelta) and delta.text_delta: |
| 103 | + final_text += delta.text_delta |
| 104 | + yield event |
| 105 | + |
| 106 | + if turn_span: |
| 107 | + turn_span.output = {"final_output": final_text, "usage": turn.usage().model_dump()} |
0 commit comments