forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
1571 lines (1341 loc) · 61.5 KB
/
Copy pathagent.py
File metadata and controls
1571 lines (1341 loc) · 61.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Strands agent with sales pipeline state, weather tool, and HITL support.
Adapted from examples/integrations/strands-python/agent/main.py
All module-level side effects (agent construction, model init,
``_agents_by_thread`` patching) are deferred to ``build_showcase_agent()``
so import failures are localized and testable.
"""
# @region[supervisor-delegation-tools]
# @region[subagent-setup]
# @region[backend-render-operations]
# @region[weather-tool-backend]
import json
import logging
import os
import threading
import uuid
from collections.abc import AsyncIterator, Mapping
from typing import Any, Optional, TypedDict
from ag_ui.core.events import (
EventType,
MessagesSnapshotEvent,
RunStartedEvent,
StateSnapshotEvent,
TextMessageContentEvent,
TextMessageEndEvent,
TextMessageStartEvent,
ToolCallArgsEvent,
ToolCallEndEvent,
ToolCallResultEvent,
ToolCallStartEvent,
)
from ag_ui.core.types import (
AssistantMessage,
FunctionCall,
ToolCall,
ToolMessage,
UserMessage,
)
from ag_ui_strands import (
StrandsAgent,
StrandsAgentConfig,
ToolBehavior,
)
from strands import Agent, tool
from strands.hooks import (
AfterToolCallEvent,
BeforeInvocationEvent,
BeforeToolCallEvent,
HookProvider,
HookRegistry,
)
from strands.models.openai import OpenAIModel
# Import shared tool implementations (symlinked at project root → ../../shared/python/tools)
from tools import (
get_weather_impl,
query_data_impl,
manage_sales_todos_impl,
schedule_meeting_impl,
search_flights_impl,
build_a2ui_operations_from_tool_call,
)
# gen-ui-agent specialization (set_steps tool + state hook + prompt addendum).
# The shared Strands backend serves every demo; this module lives in its own
# file so the gen-ui-agent surface area is reviewable in isolation, matching
# the wave-2 BYOC pattern (byoc_hashbrown.py / byoc_json_render.py).
from agents.gen_ui_agent import (
GEN_UI_AGENT_PROMPT,
set_steps,
steps_state_from_args,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# MessagesSnapshot-injecting wrapper
# ---------------------------------------------------------------------------
#
# ag_ui_strands (through at least v0.1.7) does NOT emit
# ``MessagesSnapshotEvent`` events. The CopilotKit frontend requires
# these events to build its internal message tree — without them,
# responses that include tool calls never render as assistant messages
# in the DOM (the tool-call events are received but no visible message
# element is created).
#
# ``_MessagesSnapshotWrapper`` sits between StrandsAgent.run() and the
# SSE transport: it intercepts the event stream and injects
# ``MessagesSnapshotEvent`` at the points where LangGraph Python's
# adapter would emit them:
#
# 1. After the initial ``RunStartedEvent`` — snapshot contains the
# user message that started this turn.
# 2. After each ``ToolCallEndEvent`` — snapshot contains the assistant
# message with its ``tool_calls[]`` list so the frontend's message
# tree can create the assistant bubble before the tool result
# arrives.
# 3. After each ``ToolCallResultEvent`` — snapshot contains the
# ``ToolMessage`` so the frontend pairs the result with the call.
# 4. After each ``TextMessageEndEvent`` — snapshot contains the
# assistant's text response so the frontend renders the final
# bubble.
# ---------------------------------------------------------------------------
class _MessagesSnapshotWrapper:
"""Wraps a ``StrandsAgent`` and injects ``MessagesSnapshotEvent``."""
def __init__(self, delegate: StrandsAgent) -> None:
self._delegate = delegate
# Proxy attribute access to the real StrandsAgent so
# ``create_strands_app`` and any other consumer sees the same
# interface (name, description, config, etc.).
def __getattr__(self, name: str) -> Any:
return getattr(self._delegate, name)
async def run(self, input_data: Any) -> AsyncIterator[Any]:
"""Wrap ``delegate.run()`` and inject ``MessagesSnapshotEvent``."""
# Seed the snapshot message list from the full conversation
# history that CopilotKit sends with every request. This way
# each MESSAGES_SNAPSHOT contains the *complete* thread state
# (prior turns + whatever this turn adds), matching the
# contract the CopilotKit frontend expects.
messages: list[Any] = []
if input_data.messages:
for msg in input_data.messages:
msg_id = getattr(msg, "id", None) or str(uuid.uuid4())
if msg.role == "user":
content = (
msg.content
if isinstance(msg.content, str)
else str(msg.content)
)
messages.append(
UserMessage(id=msg_id, role="user", content=content)
)
elif msg.role == "assistant":
tool_calls_list = None
if hasattr(msg, "tool_calls") and msg.tool_calls:
tool_calls_list = []
for tc in msg.tool_calls:
fn = tc.function if hasattr(tc, "function") else {}
fn_name = (
fn.get("name")
if isinstance(fn, dict)
else getattr(fn, "name", "unknown")
)
fn_args = (
fn.get("arguments")
if isinstance(fn, dict)
else getattr(fn, "arguments", "{}")
)
tool_calls_list.append(
ToolCall(
id=tc.id,
type="function",
function=FunctionCall(
name=fn_name or "unknown",
arguments=fn_args or "{}",
),
)
)
content = (
msg.content
if isinstance(msg.content, str)
else (str(msg.content) if msg.content else "")
)
messages.append(
AssistantMessage(
id=msg_id,
role="assistant",
content=content,
tool_calls=tool_calls_list,
)
)
elif msg.role == "tool":
content = (
msg.content
if isinstance(msg.content, str)
else str(msg.content)
)
messages.append(
ToolMessage(
id=msg_id,
role="tool",
content=content,
tool_call_id=getattr(msg, "tool_call_id", ""),
)
)
# Track state as events flow through.
run_started = False
initial_snapshot_emitted = False
current_tool_call_id: Optional[str] = None
current_tool_call_name: Optional[str] = None
current_tool_call_args: str = "{}"
current_text_id: Optional[str] = None
accumulated_text: str = ""
async for event in self._delegate.run(input_data):
yield event
# Detect event types by checking the ``type`` attribute
# (which is an ``EventType`` enum member on all AG-UI events).
etype = getattr(event, "type", None)
# 1. After RunStartedEvent — emit initial snapshot with user msg.
if etype == EventType.RUN_STARTED and not run_started:
run_started = True
continue # snapshot after first StateSnapshot
# Emit the initial snapshot right after the first
# StateSnapshotEvent (which always follows RunStartedEvent).
if (
etype == EventType.STATE_SNAPSHOT
and run_started
and not initial_snapshot_emitted
):
initial_snapshot_emitted = True
if messages:
yield MessagesSnapshotEvent(
type=EventType.MESSAGES_SNAPSHOT,
messages=list(messages),
)
continue
# 2. Track tool call events.
if etype == EventType.TOOL_CALL_START:
current_tool_call_id = getattr(event, "tool_call_id", None)
current_tool_call_name = getattr(event, "tool_call_name", None)
current_text_id = getattr(event, "parent_message_id", None)
current_tool_call_args = ""
continue
if etype == EventType.TOOL_CALL_ARGS:
current_tool_call_args += getattr(event, "delta", "")
continue
if etype == EventType.TOOL_CALL_END and current_tool_call_id:
# Build an AssistantMessage with the tool call.
tc = ToolCall(
id=current_tool_call_id,
type="function",
function=FunctionCall(
name=current_tool_call_name or "unknown",
arguments=current_tool_call_args or "{}",
),
)
assistant_msg = AssistantMessage(
id=current_text_id or str(uuid.uuid4()),
role="assistant",
content="",
tool_calls=[tc],
)
messages.append(assistant_msg)
yield MessagesSnapshotEvent(
type=EventType.MESSAGES_SNAPSHOT,
messages=list(messages),
)
continue
# 3. After tool result — add ToolMessage and snapshot.
if etype == EventType.TOOL_CALL_RESULT:
tool_call_id = getattr(event, "tool_call_id", None)
content = getattr(event, "content", "")
if tool_call_id:
tool_msg = ToolMessage(
id=getattr(event, "message_id", str(uuid.uuid4())),
role="tool",
content=content or "",
tool_call_id=tool_call_id,
)
messages.append(tool_msg)
yield MessagesSnapshotEvent(
type=EventType.MESSAGES_SNAPSHOT,
messages=list(messages),
)
# Reset tool tracking.
current_tool_call_id = None
current_tool_call_name = None
current_tool_call_args = "{}"
continue
# 4. Track text message streaming.
if etype == EventType.TEXT_MESSAGE_START:
current_text_id = getattr(event, "message_id", None)
accumulated_text = ""
continue
if etype == EventType.TEXT_MESSAGE_CONTENT:
accumulated_text += getattr(event, "delta", "")
continue
if etype == EventType.TEXT_MESSAGE_END and current_text_id:
assistant_msg = AssistantMessage(
id=current_text_id,
role="assistant",
content=accumulated_text,
)
messages.append(assistant_msg)
yield MessagesSnapshotEvent(
type=EventType.MESSAGES_SNAPSHOT,
messages=list(messages),
)
current_text_id = None
accumulated_text = ""
continue
class _A2uiError(TypedDict):
"""Shape of the structured error dict returned by generate_a2ui branches.
Mirrors the google-adk and langroid sibling agents' error shape — keep
all three in sync. Every error branch MUST populate all three keys so
callers (and the LLM summarizing the tool result) see a consistent
surface.
"""
error: str
message: str
remediation: str
# ---- Tools --------------------------------------------------------------
@tool
def get_weather(location: str):
"""Get current weather for a location.
Args:
location: The location to get weather for
Returns:
Weather information as JSON string
"""
return json.dumps(get_weather_impl(location))
# @endregion[weather-tool-backend]
@tool
def query_data(query: str):
"""Query financial database for chart data.
Always call before showing a chart or graph.
Args:
query: Natural language query for financial data
Returns:
Financial data as JSON string
"""
return json.dumps(query_data_impl(query))
@tool
def manage_sales_todos(todos: list[dict]):
"""Manage the sales pipeline by replacing the entire list of todos.
IMPORTANT: Always provide the entire list, not just new items.
Args:
todos: The complete updated list of sales todos
Returns:
Success message
"""
result = manage_sales_todos_impl(todos)
return f"Sales todos updated. Tracking {len(result)} item(s)."
@tool
def get_sales_todos():
"""Get the current sales pipeline todos.
Returns:
Instruction to check the sales pipeline in context
"""
return "Check the sales pipeline provided in the context."
# @region[backend-interrupt-tool]
# @region[backend-tool-call]
# Strands has no native interrupt primitive, so the gen-ui-interrupt and
# interrupt-headless demos register `schedule_meeting` as a frontend tool
# via `useFrontendTool`. Its async handler returns a Promise that only
# resolves once the user picks a slot or cancels in the in-chat picker
# (the Strands shim for LangGraph's `interrupt()` / `resolve()` pair).
#
# This `@tool` declaration is the backend's contract with the LLM: the
# docstring and signature are what the model sees when deciding to call
# `schedule_meeting`. CopilotKit's runtime routes the call to the frontend
# handler registered with `useFrontendTool` (same name), so the local
# `schedule_meeting_impl` body acts as a fallback for non-UI invocations.
@tool
def schedule_meeting(reason: str):
"""Schedule a meeting with user approval.
Duration is intentionally defaulted in this showcase to keep the
demo HITL flow minimal; callers only supply a reason.
Args:
reason: Reason for the meeting
Returns:
Meeting scheduling result as JSON string
"""
return json.dumps(schedule_meeting_impl(reason))
# @endregion[backend-tool-call]
# @endregion[backend-interrupt-tool]
@tool
def search_flights(flights: list[dict]):
"""Search for flights and display the results as rich cards. Return exactly 2 flights.
Each flight must have: airline, airlineLogo, flightNumber, origin, destination,
date (short readable format like "Tue, Mar 18" -- use near-future dates),
departureTime, arrivalTime, duration (e.g. "4h 25m"),
status (e.g. "On Time" or "Delayed"),
statusColor (hex color for status dot),
price (e.g. "$289"), and currency (e.g. "USD").
For airlineLogo use Google favicon API:
https://www.google.com/s2/favicons?domain={airline_domain}&sz=128
Args:
flights: List of flight objects
Returns:
Flight search results as JSON string
"""
result = search_flights_impl(flights)
return json.dumps(result)
# The `generate_a2ui` tool runs a secondary LLM call with a forced
# `render_a2ui` tool, then converts that tool call's args into the
# A2UI `a2ui_operations` container via
# `build_a2ui_operations_from_tool_call`. The ag_ui_strands middleware
# detects the container in the tool result and forwards the ops to
# the frontend, which resolves component names through the registered
# catalog (`copilotkit://generative-catalog`).
@tool
def generate_a2ui(context: str) -> str:
"""Generate dynamic A2UI components based on the conversation.
A secondary LLM designs the UI schema and data. The result is
returned as an a2ui_operations container for the middleware to detect.
Error branches return a JSON-serialized ``_A2uiError`` dict rather
than raising, so OpenAI transport / quota / auth failures surface to
the LLM as a structured tool result (not an uncaught exception in the
strands tool machinery). See ``_A2uiError`` above.
Args:
context: Conversation context to generate UI from
Returns:
A2UI operations (or ``_A2uiError``) as JSON string
"""
tool_schema = {
"type": "function",
"function": {
"name": "render_a2ui",
"description": "Render a dynamic A2UI v0.9 surface.",
"parameters": {
"type": "object",
"properties": {
"surfaceId": {"type": "string"},
"catalogId": {"type": "string"},
"components": {"type": "array", "items": {"type": "object"}},
"data": {"type": "object"},
},
"required": ["surfaceId", "catalogId", "components"],
},
},
}
# Wrap the OpenAI call so raw SDK / transport failures do NOT bubble up
# through the strands tool machinery as uncaught exceptions. Return a
# structured error with remediation instead — the LLM can surface this
# to the user. Mirrors the google-adk and langroid sibling agents'
# error-handling shape — keep all three in sync.
#
# Exception scope is broad on the SDK side but still bounded:
# * ``openai.OpenAIError`` covers config-time failures (e.g. from
# ``OpenAI()`` constructor when ``OPENAI_API_KEY`` is unset).
# ``APIError`` subclasses (RateLimitError, APIConnectionError,
# AuthenticationError, BadRequestError, etc.) are also caught via
# the broader ``except`` tuple. Verified against ``openai>=1.0`` —
# re-check hierarchy on major version bumps.
# * ``httpx.HTTPError`` covers transport failures (ConnectError,
# ReadTimeout, RemoteProtocolError) that can escape below the SDK's
# wrap layer in rare cases.
# Programmer errors (AttributeError, NameError, TypeError from bad
# kwargs, etc.) still propagate so bugs are not silently swallowed as
# "LLM error". Note the client construction itself is inside the try
# block for the same reason.
import openai as _openai_mod
import httpx as _httpx_mod
try:
client = _openai_mod.OpenAI()
response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{
"role": "system",
"content": context or "Generate a useful dashboard UI.",
},
{
"role": "user",
"content": "Generate a dynamic A2UI dashboard based on the conversation.",
},
],
tools=[tool_schema],
tool_choice={"type": "function", "function": {"name": "render_a2ui"}},
)
except (_openai_mod.OpenAIError, _httpx_mod.HTTPError) as exc:
logger.exception("generate_a2ui: OpenAI API call failed")
return json.dumps(
_A2uiError(
error="a2ui_llm_error",
message=f"Secondary A2UI LLM call failed: {exc.__class__.__name__}",
remediation=(
"Verify OPENAI_API_KEY is set and the OpenAI service is reachable. "
"See server logs for the full traceback."
),
)
)
if not response.choices:
logger.warning("generate_a2ui: OpenAI response contained no choices")
return json.dumps(
_A2uiError(
error="a2ui_empty_response",
message="Secondary A2UI LLM returned no choices.",
remediation="Retry; if this persists, check OpenAI status.",
)
)
tool_calls = response.choices[0].message.tool_calls
if not tool_calls:
logger.warning(
"generate_a2ui: OpenAI response had no tool_calls despite forced tool_choice"
)
return json.dumps(
_A2uiError(
error="a2ui_no_tool_call",
message="Secondary A2UI LLM did not call render_a2ui.",
remediation=(
"Retry the request. If this persists, verify the tool_choice "
"schema matches the OpenAI API contract."
),
)
)
tool_call = tool_calls[0]
try:
args = json.loads(tool_call.function.arguments)
except (ValueError, TypeError) as exc:
logger.exception(
"generate_a2ui: failed to parse render_a2ui tool arguments as JSON"
)
return json.dumps(
_A2uiError(
error="a2ui_invalid_arguments",
message=f"Could not parse render_a2ui arguments: {exc}",
remediation="Retry the request; the secondary LLM emitted malformed JSON.",
)
)
result = build_a2ui_operations_from_tool_call(args)
return json.dumps(result)
# @endregion[backend-render-operations]
@tool
def set_theme_color(theme_color: str):
"""Change the theme color of the UI.
This is a frontend tool - it returns None as the actual
execution happens on the frontend via useFrontendTool.
Args:
theme_color: The color to set as theme
"""
return None
# ---- Shared State (Read + Write) demo ----------------------------------
#
# The frontend's `shared-state-read-write` page writes a `preferences`
# object into agent state via `agent.setState()`. ``build_state_prompt``
# reads it from ``input_data.state`` and prepends a system-style line so
# the LLM sees the user's preferred name / tone / language / interests on
# every turn. The agent in turn uses ``set_notes`` to mutate
# ``state["notes"]``; ``notes_state_from_args`` emits a ``StateSnapshotEvent``
# so the UI re-renders the notes panel as soon as the tool fires.
@tool
def set_notes(notes: list[str]):
"""Replace the notes array in shared state with the full updated list.
Use this whenever the user asks you to remember something, or when
you have an observation about the user worth surfacing in the UI's
notes panel. ALWAYS pass the FULL notes list (existing notes + any
new ones), not a diff. Keep each note short (< 120 chars).
Args:
notes: The complete updated list of short note strings.
Returns:
Confirmation string for the LLM to summarise back to the user.
"""
return f"Notes updated. Tracking {len(notes)} note(s)."
async def notes_state_from_args(context):
"""Emit a StateSnapshotEvent for the ``notes`` slot when ``set_notes`` fires.
Mirrors ``sales_state_from_args`` shape — accept str-or-dict tool
input, validate, return a snapshot dict for ag_ui_strands to publish.
"""
raw_input = getattr(context, "tool_input", None)
if raw_input is None:
logger.warning("notes_state_from_args: context has no tool_input")
return None
tool_input = raw_input
if isinstance(tool_input, str):
try:
tool_input = json.loads(tool_input)
except json.JSONDecodeError as exc:
logger.warning(
"notes_state_from_args: malformed JSON tool input (%s); input excerpt: %s",
exc,
repr(raw_input)[:200],
)
return None
if isinstance(tool_input, dict):
notes_data = tool_input.get("notes")
elif isinstance(tool_input, list):
notes_data = tool_input
else:
logger.warning(
"notes_state_from_args: unsupported tool_input type %s",
type(tool_input).__name__,
)
return None
if not isinstance(notes_data, list):
return None
cleaned: list[str] = []
for n in notes_data:
if isinstance(n, str):
cleaned.append(n)
else:
cleaned.append(str(n))
return {"notes": cleaned}
# ---- Sub-Agents demo ----------------------------------------------------
#
# A supervisor LLM (this top-level Strands Agent) delegates to three
# specialised sub-agents — research / writing / critique — exposed as
# ordinary @tool functions. Each sub-agent is a single-shot OpenAI call
# with its own system prompt; this mirrors the ``google-adk`` reference
# implementation (``subagents_agent.py``) rather than spinning up a full
# secondary Strands ``Agent`` per delegation, which is heavier than the
# demo needs.
#
# Every delegation appends a ``Delegation`` record to the per-thread
# scratchpad below, then ``subagent_state_from_result`` emits a
# ``StateSnapshotEvent`` so the UI's <DelegationLog/> reflects the new
# entry the moment the tool returns.
# Each sub-agent is a single-shot OpenAI completion driven by its own
# system prompt. They don't share memory or tools with the supervisor —
# the supervisor only sees the returned text. We keep the prompts in a
# dict (rather than spinning up a full secondary Strands ``Agent`` per
# delegation) because the demo only needs one round-trip per call.
_SUBAGENT_SYSTEM_PROMPTS: dict[str, str] = {
"research_agent": (
"You are a research sub-agent. Given a topic, produce a concise "
"bulleted list of 3-5 key facts. No preamble, no closing."
),
"writing_agent": (
"You are a writing sub-agent. Given a brief and optional source "
"facts, produce a polished 1-paragraph draft. Be clear and "
"concrete. No preamble."
),
"critique_agent": (
"You are an editorial critique sub-agent. Given a draft, give "
"2-3 crisp, actionable critiques. No preamble."
),
}
# @endregion[subagent-setup]
# Per-thread scratchpad of delegations. Keyed by ``thread_id``; the entry
# is the FULL ordered list of Delegation dicts the supervisor has produced
# so far in this run. ``state_from_result`` reads/writes this so it can
# return the full updated list to the UI on every delegation.
#
# Concurrency: ag_ui_strands runs one request per thread_id at a time, so
# no within-thread races. We still hold a lock so cross-thread access
# (which Python's GIL makes safe but PyPy / future GIL-removed CPython
# would not) is explicit.
_delegations_by_thread: dict[str, list[dict]] = {}
_delegations_lock = threading.Lock()
def _seed_delegations_from_state(thread_id: str, state) -> list[dict]:
"""Initialise the per-thread scratchpad from the inbound state.
Called lazily from each delegation tool. The frontend persists
``state["delegations"]`` across runs via ``useAgent``, so a multi-turn
conversation should APPEND to the prior list rather than overwriting
it.
"""
with _delegations_lock:
if thread_id in _delegations_by_thread:
return _delegations_by_thread[thread_id]
seeded: list[dict] = []
if isinstance(state, dict):
existing = state.get("delegations")
if isinstance(existing, list):
seeded = [dict(d) for d in existing if isinstance(d, dict)]
_delegations_by_thread[thread_id] = seeded
return seeded
# Internal marker prepended to a sub-agent tool result when the underlying
# call failed. ``_make_subagent_state_from_result`` detects this prefix and
# records the Delegation entry with ``status: "failed"`` instead of
# "completed".
#
# Why a sentinel rather than `result_text.startswith("Error:")`?
# - Strands wraps tool exceptions into a result whose first content item
# text *does* start with "Error: " (see strands/tools/decorator.py and
# strands/tools/executors/_executor.py), but ag_ui_strands' result
# extraction (agent.py around line 654) only forwards the inner text /
# parsed-JSON to ``state_from_result`` — the canonical
# ``tool_result["status"] == "error"`` signal is dropped before our hook
# sees it. That makes a string-prefix check fragile (e.g. cancellation
# text "Tool cancelled by user", "Unknown tool: ..." don't start with
# "Error:") and couples our success/failure classification to Strands'
# error-text formatting, which is internal API.
# - Catching the failure inside ``_run_subagent`` lets us classify before
# Strands' wrapper ever runs, so the surface is fully under our control.
# - Class-name-only message avoids leaking ``repr(exc)`` (which can
# contain provider-specific error bodies, request IDs, etc.) into the UI.
_SUBAGENT_FAILURE_MARKER = "__SUBAGENT_FAILED__:"
# Sentinel for the legitimately-empty completion case. The sub-agent
# returned successfully but produced no content; we still want a
# "completed" Delegation entry rather than a confusing failure row, so we
# substitute a human-readable placeholder instead of raising.
_SUBAGENT_EMPTY_RESULT_TEXT = "(sub-agent returned no content)"
def _invoke_subagent_llm(system_prompt: str, task: str) -> str:
"""Run a single-shot OpenAI completion as a sub-agent.
Raises ``RuntimeError`` only on transport / API failures. A successful
call that legitimately returns empty content is logged at INFO and
surfaced as a placeholder string rather than an exception, so the
Delegation entry shows as "completed" with a clear message instead of
the misleading "failed" status the previous "empty text" raise produced.
"""
import openai as _openai_mod
import httpx as _httpx_mod
try:
client = _openai_mod.OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": task},
],
)
except (_openai_mod.OpenAIError, _httpx_mod.HTTPError) as exc:
logger.exception("sub-agent: OpenAI call failed")
raise RuntimeError(f"sub-agent call failed: {exc.__class__.__name__}") from exc
if not response.choices:
raise RuntimeError("sub-agent returned no choices")
content = response.choices[0].message.content or ""
text = content.strip()
if not text:
logger.info(
"sub-agent: OpenAI completion returned empty content; "
"surfacing placeholder rather than failure"
)
return _SUBAGENT_EMPTY_RESULT_TEXT
return text
def _run_subagent(name: str, task: str) -> str:
"""Tool body shared by all three subagent tools.
Catches ``RuntimeError`` from ``_invoke_subagent_llm`` and converts the
failure into a sentinel-prefixed string carrying only the exception
class name. ``_make_subagent_state_from_result`` recognizes the
sentinel and records ``status: "failed"`` on the Delegation entry.
This intercepts the exception *before* Strands' tool-decorator wraps
it into a generic ``status: "error"`` ToolResult — that wrapper format
is internal API and is flattened by ag_ui_strands before reaching our
state hook, so we cannot reliably read it from ``result_data`` alone.
Doing the classification here keeps the failure signal end-to-end
explicit.
"""
system_prompt = _SUBAGENT_SYSTEM_PROMPTS[name]
try:
return _invoke_subagent_llm(system_prompt, task)
except RuntimeError as exc:
# Class-name only — never the message — to avoid leaking provider
# error bodies, request IDs, or stack traces into the UI.
return f"{_SUBAGENT_FAILURE_MARKER}{exc.__class__.__name__}"
# Each @tool wraps a sub-agent invocation. The supervisor LLM "calls"
# these tools to delegate work; ``_run_subagent`` synchronously runs the
# matching sub-agent (a single-shot OpenAI completion), and the result
# string is returned to the supervisor as the tool result. The matching
# ``ToolBehavior(state_from_result=...)`` hook on each tool (registered
# in ``build_showcase_agent``) appends a Delegation entry to shared
# state so the UI's <DelegationLog/> reflects the call in real time.
@tool
def research_agent(task: str) -> str:
"""Delegate a research task to the research sub-agent.
Use for: gathering facts, background, definitions, statistics.
Returns a bulleted list of key facts as plain text.
Args:
task: The research brief to hand off.
"""
return _run_subagent("research_agent", task)
@tool
def writing_agent(task: str) -> str:
"""Delegate a drafting task to the writing sub-agent.
Use for: producing a polished paragraph, draft, or summary. Pass
relevant facts from prior research inside ``task``.
Args:
task: The writing brief to hand off.
"""
return _run_subagent("writing_agent", task)
@tool
def critique_agent(task: str) -> str:
"""Delegate a critique task to the critique sub-agent.
Use for: reviewing a draft and suggesting concrete improvements.
Args:
task: The draft to critique.
"""
return _run_subagent("critique_agent", task)
# @endregion[supervisor-delegation-tools]
def _make_subagent_state_from_result(sub_agent_name: str):
"""Factory for a ``state_from_result`` hook bound to a sub-agent name.
Returns a coroutine function suitable for ``ToolBehavior.state_from_result``.
On every successful delegation it appends a completed ``Delegation``
entry to the per-thread scratchpad and returns the full updated list
so ag_ui_strands emits a ``StateSnapshotEvent`` to the UI.
"""
async def _hook(context):
thread_id = (
getattr(getattr(context, "input_data", None), "thread_id", None)
or "default"
)
existing = _seed_delegations_from_state(
thread_id, getattr(context.input_data, "state", None)
)
# Pull the task argument out of tool_input.
raw_input = getattr(context, "tool_input", None)
tool_input = raw_input
if isinstance(tool_input, str):
try:
tool_input = json.loads(tool_input)
except json.JSONDecodeError:
tool_input = {}
task = ""
if isinstance(tool_input, dict):
task = str(tool_input.get("task") or "")
# Result body — strands wraps the @tool return value as the result.
# ``result_data`` is whatever Strands gave us; flatten common shapes.
result_data = getattr(context, "result_data", None)
result_text = _flatten_tool_result(result_data)
# Failure detection: ``_run_subagent`` catches ``RuntimeError`` and
# returns ``_SUBAGENT_FAILURE_MARKER`` + class name as the tool
# result string. Any other path (success, empty-content placeholder)
# is "completed". We deliberately do NOT fall back to a string-
# prefix check on Strands' own error wrapping ("Error: ...") because
# ag_ui_strands strips the canonical ``status`` field before our
# hook sees the result, making any prefix check brittle. See the
# ``_SUBAGENT_FAILURE_MARKER`` block above for the full rationale.
if result_text.startswith(_SUBAGENT_FAILURE_MARKER):
status = "failed"
failure_class = (
result_text[len(_SUBAGENT_FAILURE_MARKER) :].strip() or "RuntimeError"
)
display_result = f"Sub-agent call failed ({failure_class})."
else:
status = "completed"
display_result = result_text
entry = {
"id": str(uuid.uuid4()),
"sub_agent": sub_agent_name,
"task": task,
"status": status,
"result": display_result,
}
with _delegations_lock:
updated = list(existing) + [entry]
_delegations_by_thread[thread_id] = updated
# Return a defensive copy so downstream merges can't mutate scratch.
return {"delegations": [dict(d) for d in updated]}
return _hook
def _flatten_tool_result(result_data) -> str:
"""Best-effort coercion of a Strands tool result to plain text."""
if result_data is None:
return ""
if isinstance(result_data, str):
return result_data
if isinstance(result_data, list):
# Strands often wraps results as ``[{"text": "..."}]``.
parts: list[str] = []
for item in result_data:
if isinstance(item, dict):
if "text" in item and isinstance(item["text"], str):
parts.append(item["text"])
elif isinstance(item, str):
parts.append(item)
if parts:
return "\n".join(parts)
if isinstance(result_data, dict):
if "text" in result_data and isinstance(result_data["text"], str):
return result_data["text"]
return json.dumps(result_data)
return str(result_data)
# ---- State management ---------------------------------------------------
def _format_preferences_block(prefs: dict) -> Optional[str]:
"""Render the UI-supplied preferences as a system-style block.
Returns ``None`` when the dict is empty so the caller can skip
injection entirely. Mirrors ``langgraph-python``'s
``PreferencesInjectorMiddleware._build_prefs_message`` shape.
"""
if not isinstance(prefs, dict) or not prefs:
return None
lines: list[str] = []
if prefs.get("name"):
lines.append(f"- Name: {prefs['name']}")
if prefs.get("tone"):
lines.append(f"- Preferred tone: {prefs['tone']}")