@brandon_9527/tcode 1.0.2 → 1.0.3
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/python-src/.autodev/skills/teams/scripts/README.md +29 -0
- package/dist/python-src/.autodev/skills/teams/scripts/cursor_dispatch.sh +88 -0
- package/dist/python-src/.autodev/skills/teams/scripts/dispatch.sh +112 -0
- package/dist/python-src/.autodev/skills/teams/scripts/label.sh +62 -0
- package/dist/python-src/.autodev/skills/teams/scripts/layout.sh +181 -0
- package/dist/python-src/.autodev/skills/teams/scripts/old_dispatch.sh +42 -0
- package/dist/python-src/.autodev/skills/teams/scripts/pipe.sh +19 -0
- package/dist/python-src/.autodev/skills/teams/scripts/pipe_dispatch.sh +59 -0
- package/dist/python-src/.autodev/skills/teams/scripts/run.sh +18 -0
- package/dist/python-src/.autodev/skills/teams/scripts/stop.sh +26 -0
- package/dist/python-src/.autodev/skills/teams/scripts/tmux-layout.sh +43 -0
- package/dist/python-src/entry.py +28 -1
- package/dist/python-src/main.py +382 -3
- package/dist/python-src/pyproject.toml +1 -1
- package/dist/python-src/src/ai_tcode.egg-info/PKG-INFO +30 -0
- package/dist/python-src/src/ai_tcode.egg-info/SOURCES.txt +48 -0
- package/dist/python-src/src/ai_tcode.egg-info/dependency_links.txt +1 -0
- package/dist/python-src/src/ai_tcode.egg-info/requires.txt +26 -0
- package/dist/python-src/src/ai_tcode.egg-info/top_level.txt +9 -0
- package/dist/python-src/src/managers/manager_agent.py +200 -0
- package/dist/python-src/src/managers/manager_context.py +49 -0
- package/dist/python-src/src/managers/manager_instruction.py +192 -0
- package/dist/python-src/src/managers/sandbox.py +3 -3
- package/dist/python-src/src/middlewares/dynamic_content.py +63 -0
- package/dist/python-src/src/middlewares/hitl.py +3 -3
- package/dist/python-src/src/middlewares/memory.py +44 -0
- package/dist/python-src/src/middlewares/subagents.py +25 -25
- package/dist/python-src/src/middlewares/summary.py +35 -35
- package/dist/python-src/src/middlewares/utils.py +5 -0
- package/dist/python-src/src/prompts/prompts.py +1 -0
- package/dist/python-src/src/stream/formatter.py +17 -17
- package/dist/python-src/src/stream/handler.py +109 -81
- package/dist/python-src/src/stream/handler_with_tracker.py +10 -10
- package/dist/python-src/src/tools/web.py +10 -9
- package/dist/python-src/src/tui/chatui.py +67 -51
- package/dist/python-src/src/tui/components/tlist.py +6 -6
- package/dist/python-src/src/tui/components/tscroll_panel.py +8 -8
- package/dist/python-src/src/tui/utils/trender.py +27 -27
- package/dist/python-src/src/utils/prompt.py +15 -4
- package/dist/python-src/uv.lock +1980 -2094
- package/package.json +1 -1
- package/dist/python-src/src/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/managers/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/managers/__pycache__/sandbox.cpython-311.pyc +0 -0
- package/dist/python-src/src/middlewares/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/middlewares/__pycache__/hitl.cpython-311.pyc +0 -0
- package/dist/python-src/src/middlewares/dynamic_prompt.py +0 -15
- package/dist/python-src/src/stream/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/emitter.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/file_write_parser.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/formatter.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/handler.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/tracker.cpython-311.pyc +0 -0
- package/dist/python-src/src/stream/__pycache__/utils.cpython-311.pyc +0 -0
- package/dist/python-src/src/tools/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/tools/__pycache__/skill_loader.cpython-311.pyc +0 -0
- package/dist/python-src/src/tools/__pycache__/tools.cpython-311.pyc +0 -0
- package/dist/python-src/src/tools/__pycache__/web.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/__pycache__/chatui.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/__pycache__/config.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/live_spinner.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/tdiff.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/tdisplay.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/tlist.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/components/__pycache__/tscroll_panel.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/utils/__pycache__/render.cpython-311.pyc +0 -0
- package/dist/python-src/src/tui/utils/__pycache__/trender.cpython-311.pyc +0 -0
- package/dist/python-src/src/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- package/dist/python-src/src/utils/__pycache__/utils.cpython-311.pyc +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
_O='success'
|
|
2
2
|
_N='pending'
|
|
3
|
-
_M=
|
|
4
|
-
_L=
|
|
3
|
+
_M='tool_call'
|
|
4
|
+
_L=False
|
|
5
5
|
_K='status'
|
|
6
6
|
_J='result'
|
|
7
7
|
_I='interrupt_id'
|
|
@@ -29,12 +29,12 @@ from langgraph.config import get_stream_writer
|
|
|
29
29
|
from src.middlewares.hitl import HumanInTheLoopMiddleware
|
|
30
30
|
class SubAgent(TypedDict):name:str;description:str;system_prompt:str;tools:Sequence[BaseTool|Callable|dict[str,Any]];model:NotRequired[str|BaseChatModel];middleware:NotRequired[list[AgentMiddleware]];interrupt_on:NotRequired[dict[str,bool|InterruptOnConfig]]
|
|
31
31
|
class CompiledSubAgent(TypedDict):name:str;description:str;runnable:Runnable
|
|
32
|
-
DEFAULT_SUBAGENT_PROMPT='
|
|
32
|
+
DEFAULT_SUBAGENT_PROMPT='You may use a variety of standard tools to complete tasks that you believe will take a long time to process, as proposed by users, or tasks explicitly requested by users.'
|
|
33
33
|
_EXCLUDED_STATE_KEYS=_B,'todos'
|
|
34
34
|
TASK_TOOL_DESCRIPTION='Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n{available_agents}\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent\'s outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user\'s intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n<example_agent_descriptions>\n"general-purpose": use this agent for general purpose tasks, it has access to all tools as the main agent.\n</example_agent_descriptions>\n\n<example>\nUser: "I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them."\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n<commentary>\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n</commentary>\n</example>\n\n<example>\nUser: "Analyze a single large code repository for security vulnerabilities and generate a report."\nAssistant: *Launches a single `task` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n<commentary>\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n</commentary>\n</example>\n\n<example>\nUser: "Schedule two meetings for me and prepare agendas for each."\nAssistant: *Calls the task tool in parallel to launch two `task` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n<commentary>\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n</commentary>\n</example>\n\n<example>\nUser: "I want to order a pizza from Dominos, order a burger from McDonald\'s, and order a salad from Subway."\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald\'s, and a salad from Subway*\n<commentary>\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the `task`tool.\n</commentary>\n</example>\n\n### Example usage with custom agents:\n\n<example_agent_descriptions>\n"content-reviewer": use this agent after you are done creating significant content or documents\n"greeting-responder": use this agent when to respond to user greetings with a friendly joke\n"research-analyst": use this agent to conduct thorough research on complex topics\n</example_agent_description>\n\n<example>\nuser: "Please write a function that checks if a number is prime"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I\'m going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {{\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {{\n if (n % i === 0) return false\n }}\n return true\n}}\n</code>\n<commentary>\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n</commentary>\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n</example>\n\n<example>\nuser: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?"\n<commentary>\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n</commentary>\nassistant: I\'ll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.\nassistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take\n</example>\n\n<example>\nuser: "Hello"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: "I\'m going to use the Task tool to launch with the greeting-responder agent"\n</example>'
|
|
35
|
-
TASK_SYSTEM_PROMPT='## `task` (subagent spawner)\n\nYou have access to a `task` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the `task` tool to silo independent tasks within a multi-part objective.\n- You should use the `task` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.'
|
|
35
|
+
TASK_SYSTEM_PROMPT='## `task` (subagent spawner)\n\nYou have access to a `task` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n- 用户仅仅时普通寒暄时,不应该使用任务工具。\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the `task` tool to silo independent tasks within a multi-part objective.\n- You should use the `task` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.'
|
|
36
36
|
DEFAULT_GENERAL_PURPOSE_DESCRIPTION='General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.'
|
|
37
|
-
def
|
|
37
|
+
def cb(*,default_model,default_tools,default_middleware,default_interrupt_on,subagents,general_purpose_agent):
|
|
38
38
|
M='middleware';L='runnable';F=default_tools;E=default_model;C=default_interrupt_on;D=default_middleware or[];B={};G=[]
|
|
39
39
|
if general_purpose_agent:
|
|
40
40
|
H=[*D]
|
|
@@ -59,28 +59,28 @@ def stream_handler(stream,runtime):
|
|
|
59
59
|
if isinstance(B[_B],list)and len(B[_B])>0:
|
|
60
60
|
for A in B[_B]:
|
|
61
61
|
if isinstance(A,AIMessage)and len(A.tool_calls)>0:
|
|
62
|
-
for F in A.tool_calls:G=F[_C];M=F[_D];H=F['id'];I={_E:
|
|
63
|
-
if isinstance(A,AIMessage)and len(A.tool_calls)==0:
|
|
64
|
-
if isinstance(A,ToolMessage):G=A.name;N=A.content;H=A.tool_call_id;I={_E:
|
|
62
|
+
for F in A.tool_calls:G=F[_C];M=F[_D];H=F['id'];I={_E:_M,_G:D.tool_call_id,_H:H,_I:'',_C:G,_D:M,_J:'',_K:_N};J(json.dumps(I,indent=2,ensure_ascii=_L))
|
|
63
|
+
if isinstance(A,AIMessage)and len(A.tool_calls)==0:C=A
|
|
64
|
+
if isinstance(A,ToolMessage):G=A.name;N=A.content;H=A.tool_call_id;I={_E:_M,_G:D.tool_call_id,_H:H,_I:'',_C:G,_D:{},_J:N,_K:_O};J(json.dumps(I,indent=2,ensure_ascii=_L))
|
|
65
65
|
O={_B:[C]if C and isinstance(C,AIMessage)else[]};return O
|
|
66
66
|
async def astream_handler(stream,runtime):
|
|
67
|
-
|
|
68
|
-
async for
|
|
69
|
-
if not isinstance(
|
|
70
|
-
|
|
71
|
-
if
|
|
67
|
+
D=runtime;J=D.stream_writer;C=_A
|
|
68
|
+
async for E in stream:
|
|
69
|
+
if not isinstance(E,tuple)or len(E)!=2:continue
|
|
70
|
+
L,K=E
|
|
71
|
+
if L==_F:
|
|
72
72
|
if not isinstance(K,dict):continue
|
|
73
73
|
for(P,B)in K.items():
|
|
74
74
|
if B is _A or isinstance(B,tuple):continue
|
|
75
75
|
if isinstance(B[_B],list)and len(B[_B])>0:
|
|
76
76
|
for A in B[_B]:
|
|
77
77
|
if isinstance(A,AIMessage)and len(A.tool_calls)>0:
|
|
78
|
-
for
|
|
79
|
-
if isinstance(A,AIMessage)and len(A.tool_calls)==0:
|
|
80
|
-
if isinstance(A,ToolMessage):
|
|
81
|
-
O={_B:[
|
|
82
|
-
def
|
|
83
|
-
G='Tool call ID is required for subagent invocation';F='custom';A=task_description;B,H=
|
|
78
|
+
for F in A.tool_calls:G=F[_C];M=F[_D];H=F['id'];I={_E:_M,_G:D.tool_call_id,_H:H,_I:'',_C:G,_D:M,_J:'',_K:_N};J(json.dumps(I,indent=2,ensure_ascii=_L))
|
|
79
|
+
if isinstance(A,AIMessage)and len(A.tool_calls)==0:C=A
|
|
80
|
+
if isinstance(A,ToolMessage):G=A.name;N=A.content;H=A.tool_call_id;I={_E:'tool_result',_G:D.tool_call_id,_H:H,_I:'',_C:G,_D:{},_J:N,_K:_O};J(json.dumps(I,indent=2,ensure_ascii=_L))
|
|
81
|
+
O={_B:[C]if C and isinstance(C,AIMessage)else[]};return O
|
|
82
|
+
def by(*,default_model,default_tools,default_middleware,default_interrupt_on,subagents,general_purpose_agent,task_description=_A):
|
|
83
|
+
G='Tool call ID is required for subagent invocation';F='custom';A=task_description;B,H=cb(default_model=default_model,default_tools=default_tools,default_middleware=default_middleware,default_interrupt_on=default_interrupt_on,subagents=subagents,general_purpose_agent=general_purpose_agent);C='\n'.join(H)
|
|
84
84
|
def D(result,tool_call_id):A=result;B={A:B for(A,B)in A.items()if A not in _EXCLUDED_STATE_KEYS};C=A[_B][-1];D=I(C);return Command(update={**B,_B:[ToolMessage(D,tool_call_id=tool_call_id)]})
|
|
85
85
|
def I(msg):
|
|
86
86
|
D='text';B=msg.content
|
|
@@ -97,11 +97,11 @@ def bt(*,default_model,default_tools,default_middleware,default_interrupt_on,sub
|
|
|
97
97
|
if A is _A:A=TASK_TOOL_DESCRIPTION.format(available_agents=C)
|
|
98
98
|
elif'{available_agents}'in A:A=A.format(available_agents=C)
|
|
99
99
|
def J(description,subagent_type,runtime):
|
|
100
|
-
|
|
101
|
-
if C not in B:
|
|
102
|
-
J
|
|
103
|
-
if not A.tool_call_id:
|
|
104
|
-
return D(
|
|
100
|
+
C=subagent_type;A=runtime
|
|
101
|
+
if C not in B:H=', '.join([f"`{A}`"for A in B]);return f"We cannot invoke subagent {C} because it does not exist, the only allowed types are {H}"
|
|
102
|
+
I,J=E(C,description,A);K=I.stream(J,config={**A.config},stream_mode=[_F,F],context=A.context);L=stream_handler(K,A)
|
|
103
|
+
if not A.tool_call_id:M=G;raise ValueError(M)
|
|
104
|
+
return D(L,A.tool_call_id)
|
|
105
105
|
async def K(description,subagent_type,runtime):
|
|
106
106
|
C=subagent_type;A=runtime
|
|
107
107
|
if C not in B:H=', '.join([f"`{A}`"for A in B]);return f"We cannot invoke subagent {C} because it does not exist, the only allowed types are {H}"
|
|
@@ -110,7 +110,7 @@ def bt(*,default_model,default_tools,default_middleware,default_interrupt_on,sub
|
|
|
110
110
|
return D(L,A.tool_call_id)
|
|
111
111
|
return StructuredTool.from_function(name='task',func=J,coroutine=K,description=A)
|
|
112
112
|
class SubAgentMiddleware(AgentMiddleware):
|
|
113
|
-
def __init__(A,*,default_model,default_tools=_A,default_middleware=_A,default_interrupt_on=_A,subagents=_A,system_prompt=TASK_SYSTEM_PROMPT,general_purpose_agent=True,task_description=_A):super().__init__();A.system_prompt=system_prompt;B=
|
|
113
|
+
def __init__(A,*,default_model,default_tools=_A,default_middleware=_A,default_interrupt_on=_A,subagents=_A,system_prompt=TASK_SYSTEM_PROMPT,general_purpose_agent=True,task_description=_A):super().__init__();A.system_prompt=system_prompt;B=by(default_model=default_model,default_tools=default_tools or[],default_middleware=default_middleware,default_interrupt_on=default_interrupt_on,subagents=subagents or[],general_purpose_agent=general_purpose_agent,task_description=task_description);A.tools=[B]
|
|
114
114
|
def wrap_model_call(B,request,handler):
|
|
115
115
|
C=handler;A=request
|
|
116
116
|
if B.system_prompt is not _A:D=A.system_prompt+'\n\n'+B.system_prompt if A.system_prompt else B.system_prompt;return C(A.override(system_prompt=D))
|
|
@@ -44,61 +44,61 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
44
44
|
if isinstance(C,str):C=init_chat_model(C)
|
|
45
45
|
A.model=C
|
|
46
46
|
if B is _A:A.trigger=_A;G=[]
|
|
47
|
-
elif isinstance(B,list):I=[A.
|
|
48
|
-
else:J=A.
|
|
49
|
-
A._trigger_conditions=G;A.keep=A.
|
|
47
|
+
elif isinstance(B,list):I=[A.cl(B,N)for B in B];A.trigger=I;G=I
|
|
48
|
+
else:J=A.cl(B,N);A.trigger=J;G=[J]
|
|
49
|
+
A._trigger_conditions=G;A.keep=A.cl(F,'keep')
|
|
50
50
|
if H is count_tokens_approximately:A.token_counter=cm(A.model)
|
|
51
51
|
else:A.token_counter=H
|
|
52
52
|
A.summary_prompt=summary_prompt;A.trim_tokens_to_summarize=trim_tokens_to_summarize;K=any(A[0]==_D for A in A._trigger_conditions)
|
|
53
53
|
if A.keep[0]==_D:K=_C
|
|
54
|
-
if K and A.
|
|
55
|
-
def
|
|
54
|
+
if K and A.cn()is _A:O='Model profile information is required to use fractional token limits, and is unavailable for the specified model. Please use absolute token counts instead, or pass `\n\nChatModel(..., profile={"max_input_tokens": ...})`.\n\nwith a desired integer value of the model\'s maximum input tokens.';raise ValueError(O)
|
|
55
|
+
def ck(B,state):A=state.get(_G,_F);return bool(A)
|
|
56
56
|
@override
|
|
57
57
|
def before_model(self,state,runtime):
|
|
58
|
-
C=state;A=self;B=C[_B];A.
|
|
58
|
+
C=state;A=self;B=C[_B];A.cp(B);E=A.token_counter(B);F=A.ck(C);G=A.co(B,E)
|
|
59
59
|
if not G and not F:return
|
|
60
|
-
D=A.
|
|
60
|
+
D=A.cg(B)
|
|
61
61
|
if D<=0:return
|
|
62
|
-
H,I=A.
|
|
62
|
+
H,I=A.cf(B,D);J=A.cj(H);K=A.ch(J);return{_B:[RemoveMessage(id=REMOVE_ALL_MESSAGES),*K,*I],_G:_F}
|
|
63
63
|
@override
|
|
64
64
|
async def abefore_model(self,state,runtime):
|
|
65
|
-
C=state;A=self;B=C[_B];A.
|
|
65
|
+
C=state;A=self;B=C[_B];A.cp(B);E=A.token_counter(B);F=A.ck(C);G=A.co(B,E)
|
|
66
66
|
if not G and not F:return
|
|
67
|
-
D=A.
|
|
67
|
+
D=A.cg(B)
|
|
68
68
|
if D<=0:return
|
|
69
|
-
H,I=A.
|
|
70
|
-
def
|
|
69
|
+
H,I=A.cf(B,D);J=await A._acreate_summary(H);K=A.ch(J);return{_B:[RemoveMessage(id=REMOVE_ALL_MESSAGES),*K,*I],_G:_F}
|
|
70
|
+
def cr(B,messages,threshold):
|
|
71
71
|
A=next((A for A in reversed(messages)if isinstance(A,AIMessage)),_A)
|
|
72
72
|
if isinstance(A,AIMessage)and A.usage_metadata is not _A and(C:=A.usage_metadata.get('total_tokens',-1))and C>=threshold and(D:=A.response_metadata.get('model_provider'))and D==B.model._get_ls_params().get('ls_provider'):return _C
|
|
73
73
|
return _F
|
|
74
|
-
def
|
|
74
|
+
def co(A,messages,total_tokens):
|
|
75
75
|
F=total_tokens;E=messages
|
|
76
76
|
if not A._trigger_conditions:return _F
|
|
77
77
|
for(B,C)in A._trigger_conditions:
|
|
78
78
|
if B==_B and len(E)>=C:return _C
|
|
79
79
|
if B==_E and F>=C:return _C
|
|
80
|
-
if B==_E and A.
|
|
80
|
+
if B==_E and A.cr(E,C):return _C
|
|
81
81
|
if B==_D:
|
|
82
|
-
G=A.
|
|
82
|
+
G=A.cn()
|
|
83
83
|
if G is _A:continue
|
|
84
84
|
D=int(G*C)
|
|
85
85
|
if D<=0:D=1
|
|
86
86
|
if F>=D:return _C
|
|
87
|
-
if A.
|
|
87
|
+
if A.cr(E,D):return _C
|
|
88
88
|
return _F
|
|
89
|
-
def
|
|
89
|
+
def cg(A,messages):
|
|
90
90
|
B=messages;D,E=A.keep
|
|
91
91
|
if D in{_E,_D}:
|
|
92
|
-
C=A.
|
|
92
|
+
C=A.cs(B)
|
|
93
93
|
if C is not _A:return C
|
|
94
|
-
return A.
|
|
95
|
-
return A.
|
|
96
|
-
def
|
|
94
|
+
return A.ci(B,_DEFAULT_MESSAGES_TO_KEEP)
|
|
95
|
+
return A.ci(B,cast('int',E))
|
|
96
|
+
def cs(C,messages):
|
|
97
97
|
A=messages
|
|
98
98
|
if not A:return 0
|
|
99
99
|
H,I=C.keep
|
|
100
100
|
if H==_D:
|
|
101
|
-
J=C.
|
|
101
|
+
J=C.cn()
|
|
102
102
|
if J is _A:return
|
|
103
103
|
F=int(J*I)
|
|
104
104
|
elif H==_E:F=int(I)
|
|
@@ -114,8 +114,8 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
114
114
|
if B>=len(A):
|
|
115
115
|
if len(A)==1:return 0
|
|
116
116
|
B=len(A)-1
|
|
117
|
-
return C.
|
|
118
|
-
def
|
|
117
|
+
return C.cq(A,B)
|
|
118
|
+
def cn(C):
|
|
119
119
|
try:A=C.model.profile
|
|
120
120
|
except AttributeError:return
|
|
121
121
|
if not isinstance(A,Mapping):return
|
|
@@ -123,7 +123,7 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
123
123
|
if not isinstance(B,int):return
|
|
124
124
|
return B
|
|
125
125
|
@staticmethod
|
|
126
|
-
def
|
|
126
|
+
def cl(context,parameter_name):
|
|
127
127
|
E=context;C=parameter_name;D,B=E
|
|
128
128
|
if D==_D:
|
|
129
129
|
if not 0<B<=1:A=f"Fractional {C} values must be between 0 and 1, got {B}.";raise ValueError(A)
|
|
@@ -132,19 +132,19 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
132
132
|
else:A=f"Unsupported context size type {D} for {C}.";raise ValueError(A)
|
|
133
133
|
return E
|
|
134
134
|
@staticmethod
|
|
135
|
-
def
|
|
135
|
+
def ch(summary):return[HumanMessage(content=f"Here is a summary of the conversation to date:\n\n{summary}",additional_kwargs={'lc_source':'summarization'})]
|
|
136
136
|
@staticmethod
|
|
137
|
-
def
|
|
137
|
+
def cp(messages):
|
|
138
138
|
for A in messages:
|
|
139
139
|
if A.id is _A:A.id=str(uuid.uuid4())
|
|
140
140
|
@staticmethod
|
|
141
|
-
def
|
|
142
|
-
def
|
|
141
|
+
def cf(conversation_messages,cutoff_index):B=cutoff_index;A=conversation_messages;C=A[:B];D=A[B:];return C,D
|
|
142
|
+
def ci(C,messages,messages_to_keep):
|
|
143
143
|
B=messages_to_keep;A=messages
|
|
144
144
|
if len(A)<=B:return 0
|
|
145
|
-
D=len(A)-B;return C.
|
|
145
|
+
D=len(A)-B;return C.cq(A,D)
|
|
146
146
|
@staticmethod
|
|
147
|
-
def
|
|
147
|
+
def cq(messages,cutoff_index):
|
|
148
148
|
B=cutoff_index;A=messages
|
|
149
149
|
if B>=len(A)or not isinstance(A[B],ToolMessage):return B
|
|
150
150
|
E=set();C=B
|
|
@@ -158,10 +158,10 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
158
158
|
H={A.get('id')for A in D.tool_calls if A.get('id')}
|
|
159
159
|
if E&H:return G
|
|
160
160
|
return C
|
|
161
|
-
def
|
|
161
|
+
def cj(A,messages_to_sumarize):
|
|
162
162
|
B=messages_to_sumarize
|
|
163
163
|
if not B:return _H
|
|
164
|
-
C=A.
|
|
164
|
+
C=A.ct(B)
|
|
165
165
|
if not C:return'Previous conversation was too long to summarize'
|
|
166
166
|
D=get_buffer_string(C)
|
|
167
167
|
try:E=A.model.invoke(A.summary_prompt.format(messages=D));return E.text.strip()
|
|
@@ -169,12 +169,12 @@ class SummarizationMiddleware(AgentMiddleware):
|
|
|
169
169
|
async def _acreate_summary(A,messages_to_summarize):
|
|
170
170
|
B=messages_to_summarize
|
|
171
171
|
if not B:return _H
|
|
172
|
-
C=A.
|
|
172
|
+
C=A.ct(B)
|
|
173
173
|
if not C:return'Previous conversation was too long to summarize.'
|
|
174
174
|
D=get_buffer_string(C)
|
|
175
175
|
try:E=await A.model.ainvoke(A.summary_prompt.format(messages=D));return E.text.strip()
|
|
176
176
|
except Exception as F:return f"Error generating sumamry: {F!s}"
|
|
177
|
-
def
|
|
177
|
+
def ct(A,messages):
|
|
178
178
|
B=messages
|
|
179
179
|
try:
|
|
180
180
|
if A.trim_tokens_to_summarize is _A:return B
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from langchain_core.messages import ContentBlock,SystemMessage
|
|
2
|
+
def append_to_system_message(system_message,text):
|
|
3
|
+
D='text';C=system_message;A=text;B=list(C.content_blocks)if C else[]
|
|
4
|
+
if B:A=f"\n\n{A}"
|
|
5
|
+
B.append({'type':D,D:A});return SystemMessage(content_blocks=B)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
leader=' \n## 工作环境\n\nCURRENT_TIME: {CURRENT_TIME}\nWORKSPACE: {WORKSPACE}\n\n## 角色定位\n你的名字是 David。\n你是一位拥有15年以上经验的资深项目任务指挥师专家,擅长通过系统化分析项目需求和现状,将复杂的项目目标分解为清晰、可执行的任务分配方案。\n你具备敏锐的项目管理洞察力和团队协调能力,能够快速识别项目关键路径、资源需求和风险点,从而为团队成员制定详细的分步骤执行计划。\n你专注于任务分解、资源配置和团队协作,将宏观的项目目标转化为微观的可执行任务。\n\n\n注意: 严禁你代替成员完成任务,只能协调和分配任务,不能直接执行任务。\n\n## 工作空间说明\n 你的工作空间(WORKSPACE)位置为: {WORKSPACE}, 你的项目文件夹可以放在 {{WORKSPACE}} 下。\n\n## 核心能力 \n 1. **项目需求分析**:\n 深入理解项目目标、范围、约束条件和成功标准,识别关键需求和优先级。\n \n\n 2. **任务分解与规划**:\n 2.1 根据需求分析的结果判断项目的规模和复杂度。\n 2.2 如果是简单任务则按照其涉及到的工作内容直接分配给对应的团队成员执行。\n 2.3 如果不能明确判断任务和哪个团队成员相匹配,则优先分配给 通用代理 general agent 进行处理。\n 2.4 如果任务需要协调多个团队成员合作完成,则将项目目标分解为可管理的工作包,并明确任务间的依赖关系和执行顺序。\n 3. **团队角色分配**:根据任务特性和团队成员能力,合理分配团队成员的工作职责。\n 4. **协作流程设计**:设计高效的团队协作流程,明确沟通机制和决策流程。\n 5. **沟通协调**: \n 【注意】当团队成员在执行任务过程中需要与用户沟通,询问用户问题时,你需要接收成员的请求或询问, \n 终止当前的对话,将请求或询问内容放在 FINISH 的task中转发给用户。此时严禁自行回复成员或者分发任务。\n\n\n\n\n## 工作方式\n 你在指挥团队完成任务时需要严格遵循以下INSTRUCTION指令,不要执行超出指令范围之外的工作。\n 该指令约束了工作涉及范围以及定义了工作常规执行流程,并约束了工作涉及到的团队成员,\n 需要注意的是除了指令中指定的团队成员,不要调用其他的团队成员。\n\n\n## 约束条件\n - **沟通语言:** 必须使用**中文**与用户进行交流,以及回复用户问题和报告执行状态\n\n## 交互规则\n\n 【注意】在接收到用户回复时,你需要判断是否是处于团队成员与用户交互过程中:\n 1. 如果是,你直接将用户的回复转发给团队成员,无需额外处理和任务分解。\n 2. 如果不是,你需要根据用户的问题进行任务分解和分配。\n\n 【注意】如果团队成员回复内容为询问,提问的形式,你如果不能给出答案,则向用户询问。\n\n'
|
|
@@ -16,18 +16,18 @@ class ToolResultFormatter:
|
|
|
16
16
|
def detect_type(B,content):
|
|
17
17
|
A=content;A=A.strip()
|
|
18
18
|
if A.statswith(SUCCESS_PREFIX):
|
|
19
|
-
C=B.
|
|
20
|
-
if B.
|
|
19
|
+
C=B.ba(A)
|
|
20
|
+
if B.bi(C):return ContentType.JSON
|
|
21
21
|
return ContentType.SUCCESS
|
|
22
22
|
if A.startswith(FAILURE_PREFIX):return ContentType.ERROR
|
|
23
|
-
if B.
|
|
23
|
+
if B.bi(A):return ContentType.JSON
|
|
24
24
|
if B.bh(A):return ContentType.ERROR
|
|
25
|
-
if B.
|
|
25
|
+
if B.bd(A):return ContentType.MARKDOWN
|
|
26
26
|
return ContentType.TEXT
|
|
27
27
|
def is_success(A,content):return _is_success(content)
|
|
28
|
-
def format(A,name,content,max_length=800):B=content;C=A.detect_type(B);D=A.is_success(B);E={ContentType.SUCCESS:A.
|
|
29
|
-
def
|
|
30
|
-
def
|
|
28
|
+
def format(A,name,content,max_length=800):B=content;C=A.detect_type(B);D=A.is_success(B);E={ContentType.SUCCESS:A.bb,ContentType.ERROR:A.bj,ContentType.JSON:A.be,ContentType.MARKDOWN:A.bf,ContentType.TEXT:A.bc};F=E.get(C,A.bc);G=F(name,B,max_length);return FormattedResult(content_type=C,elements=G,success=D)
|
|
29
|
+
def ba(B,content):A=content.split('\n',2);return A[2].strip()if len(A)>2 else''
|
|
30
|
+
def bi(B,content):
|
|
31
31
|
A=content;A=A.strip()
|
|
32
32
|
if not A:return _A
|
|
33
33
|
if A.startswith('{')and A.endswith('}')or A.startswith('[')and A.endswith(']'):
|
|
@@ -35,14 +35,14 @@ class ToolResultFormatter:
|
|
|
35
35
|
except(json.JSONDecodeError,ValueError):pass
|
|
36
36
|
return _A
|
|
37
37
|
def bh(B,content):A=['Traceback (most recent call last)','Exception:','Error:'];return any(A in content for A in A)
|
|
38
|
-
def
|
|
39
|
-
def
|
|
40
|
-
def
|
|
41
|
-
def
|
|
38
|
+
def bd(C,content):A=content;B=['```','**','##','- **'];return A.startswith('#')or any(B in A for B in B)
|
|
39
|
+
def bb(B,name,content,max_length):A='green';C=B.bg(content,max_length);return[Panel(Text(C,style=A),title=f"📤 {name} ✓",border_style=A)]
|
|
40
|
+
def bj(B,name,content,max_length):A='red';C=B.bg(content,max_length);return[Panel(Text(C,style=A),title=f"📤 {name} ✗",border_style=A)]
|
|
41
|
+
def be(B,name,content,max_length):
|
|
42
42
|
D=max_length;A=content;E=A
|
|
43
|
-
if A.startswith(SUCCESS_PREFIX):E=B.
|
|
44
|
-
try:F=json.loads(E);C=json.dumps(F,indent=2,ensure_ascii=_A);C=B.
|
|
45
|
-
except(json.JSONDecodeError,ValueError):return B.
|
|
46
|
-
def
|
|
47
|
-
def
|
|
48
|
-
def
|
|
43
|
+
if A.startswith(SUCCESS_PREFIX):E=B.ba(A)
|
|
44
|
+
try:F=json.loads(E);C=json.dumps(F,indent=2,ensure_ascii=_A);C=B.bg(C,D);return[Text(f"📤 {name} ✓",style=_B),Syntax(C,'json',theme='monokai',line_numbers=_A)]
|
|
45
|
+
except(json.JSONDecodeError,ValueError):return B.bc(name,A,D)
|
|
46
|
+
def bf(A,name,content,max_length):B=A.bg(content,max_length);return[Panel(Markdown(B),title=f"📤 {name}",border_style='cyan dim')]
|
|
47
|
+
def bc(A,name,content,max_length):B=A.bg(content,max_length);return[Text(f"📤 {name}:",style=_B),Text(f" {B}",style='dim')]
|
|
48
|
+
def bg(A,content,max_length):return truncate(content,max_length)
|
|
@@ -1,120 +1,148 @@
|
|
|
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
|
-
|
|
1
|
+
_b='[DEBUG] Stream completed normally'
|
|
2
|
+
_a='INTERRUPT'
|
|
3
|
+
_Z='total_tokens'
|
|
4
|
+
_Y='output_tokens'
|
|
5
|
+
_X='input_tokens'
|
|
6
|
+
_W='success'
|
|
7
|
+
_V='interrupt_id'
|
|
8
|
+
_U='tool_result'
|
|
9
|
+
_T='tool_call'
|
|
10
|
+
_S='pending'
|
|
11
|
+
_R='result'
|
|
12
|
+
_Q='tool_id'
|
|
13
|
+
_P='parent_id'
|
|
14
|
+
_O='custom'
|
|
15
|
+
_N=False
|
|
16
|
+
_M='text'
|
|
17
|
+
_L='value'
|
|
18
|
+
_K='__interrupt__'
|
|
19
|
+
_J='auto'
|
|
20
|
+
_I='status'
|
|
21
|
+
_H='updates'
|
|
22
|
+
_G='type'
|
|
23
|
+
_F='id'
|
|
24
|
+
_E='content'
|
|
25
|
+
_D='args'
|
|
26
|
+
_C=None
|
|
27
|
+
_B='name'
|
|
27
28
|
_A='messages'
|
|
28
|
-
import json
|
|
29
|
+
import json,asyncio
|
|
29
30
|
from langchain_core.messages import AIMessage,AIMessageChunk,ToolMessage
|
|
30
31
|
from langgraph.types import Command,Interrupt
|
|
31
32
|
from src.stream.utils import DisplayLimits,is_success
|
|
32
33
|
from src.stream.emitter import StreamEventEmitter as emitter
|
|
33
34
|
from src.stream.tracker import ToolCallTracker
|
|
34
35
|
from src.stream.file_write_parser import StreamParser
|
|
35
|
-
async def
|
|
36
|
-
|
|
36
|
+
async def ainput(prompt=''):return await asyncio.to_thread(input,prompt)
|
|
37
|
+
async def anormal_handler(stream,detail=_N):
|
|
38
|
+
E=detail
|
|
39
|
+
async for H in stream:
|
|
40
|
+
if not isinstance(H,tuple)or len(H)!=2:continue
|
|
41
|
+
F,G=H
|
|
42
|
+
if F!=_H:print(f"[STREAM_MODE]: {F} {G}")
|
|
43
|
+
if F==_H:
|
|
44
|
+
if not isinstance(G,dict):continue
|
|
45
|
+
for(M,C)in G.items():
|
|
46
|
+
if C is _C or isinstance(C,tuple):continue
|
|
47
|
+
if _A in C and isinstance(C[_A],list)and len(C[_A])>0:
|
|
48
|
+
for A in C[_A]:
|
|
49
|
+
if isinstance(A,AIMessage)and len(A.tool_calls)>0:
|
|
50
|
+
for B in A.tool_calls:
|
|
51
|
+
D=B[_B];I=B[_D];K=B[_F]
|
|
52
|
+
if E:print(f"[TOOL_CALL]: {D} \nargs: ({I}) ")
|
|
53
|
+
if isinstance(A,AIMessage)and A.content and A.content!='':print(f"[AIMESSAGE]: {A.content}")
|
|
54
|
+
if isinstance(A,ToolMessage):
|
|
55
|
+
D=A.name;J=A.content;K=A.tool_call_id
|
|
56
|
+
if E:print(f"[TOOL_RESULT]: {D} \nresult: {J}")
|
|
57
|
+
elif F==_O:
|
|
58
|
+
B=json.loads(G);L=getattr(B,_G,'');N=getattr(B,_P,'');K=getattr(B,_Q,'');D=getattr(B,_B,'');I=getattr(B,_D,'');J=getattr(B,_R,'');O=getattr(B,_I,_S)
|
|
59
|
+
if L==_T:
|
|
60
|
+
if E:print(f"[SUB TOOL_CALL]: {D} \nargs: ({I}) ")
|
|
61
|
+
elif L==_U:
|
|
62
|
+
if E:print(f"[SUB TOOL_RESULT]: {D} \nresult: {J}")
|
|
63
|
+
async def astream_handler(stream,debug=_N,interrupt_tools=[],tool_mode=_J):
|
|
64
|
+
P=interrupt_tools;J=debug;K=[];S='';T=StreamParser(top_fields=['path',_E])
|
|
37
65
|
async for F in stream:
|
|
38
66
|
if not isinstance(F,tuple)or len(F)!=2:continue
|
|
39
|
-
L,
|
|
40
|
-
if L==
|
|
41
|
-
if not isinstance(
|
|
42
|
-
for(
|
|
43
|
-
if H is
|
|
67
|
+
L,D=F
|
|
68
|
+
if L==_H:
|
|
69
|
+
if not isinstance(D,dict):continue
|
|
70
|
+
for(d,H)in D.items():
|
|
71
|
+
if H is _C or isinstance(H,tuple):continue
|
|
44
72
|
if _A in H and isinstance(H[_A],list)and len(H[_A])>0:
|
|
45
|
-
for
|
|
46
|
-
if isinstance(
|
|
47
|
-
for B in
|
|
48
|
-
E=B[
|
|
49
|
-
if tool_mode!=
|
|
73
|
+
for C in H[_A]:
|
|
74
|
+
if isinstance(C,AIMessage)and len(C.tool_calls)>0:
|
|
75
|
+
for B in C.tool_calls:
|
|
76
|
+
E=B[_B];I=B[_D];G=B[_F]
|
|
77
|
+
if len(P)>0 and tool_mode!=_J and E.strip().lower()in P:continue
|
|
50
78
|
A=emitter.tool_call(E,I,G);yield A.data
|
|
51
|
-
if isinstance(
|
|
52
|
-
if isinstance(
|
|
53
|
-
if
|
|
54
|
-
K=
|
|
79
|
+
if isinstance(C,ToolMessage):E=C.name;M=C.content;G=C.tool_call_id;A=emitter.tool_result(E,M,_W,G);yield A.data
|
|
80
|
+
if isinstance(C,AIMessage)and C.usage_metadata:N=C.usage_metadata;U=N.get(_X,_C);V=N.get(_Y);W=N.get(_Z,_C);A=emitter.token_usage(U,V,W);yield A.data
|
|
81
|
+
if _K in D:
|
|
82
|
+
K=D[_K]
|
|
55
83
|
if K:
|
|
56
|
-
|
|
57
|
-
for O in
|
|
84
|
+
e=_a;X=list(map(lambda interrupt:{_V:interrupt.id,_L:interrupt.value},K))
|
|
85
|
+
for O in X:Y='hitl';Z=O[_V];a=O[_L];B=a['action_requests'][0];E=B[_B];G=B[_F];I=B[_D];A=emitter.tool_call(E,I,G);yield A.data;A=emitter.interrupt(interrupt_type=Y,interrupt_id=Z,value=O);yield A.data
|
|
58
86
|
elif L==_A:
|
|
59
|
-
if isinstance(
|
|
60
|
-
else:F=
|
|
61
|
-
if J:
|
|
87
|
+
if isinstance(D,tuple)and len(D)>=2:F=D[0]
|
|
88
|
+
else:F=D
|
|
89
|
+
if J:b=type(F).__name__;print(f"[DEBUG] Event: {b}")
|
|
62
90
|
if isinstance(F,(AIMessageChunk,AIMessage)):
|
|
63
|
-
for A in bk(F,
|
|
64
|
-
if A.type==
|
|
91
|
+
for A in bk(F,T):
|
|
92
|
+
if A.type==_M:S+=A.data.get(_E,'')
|
|
65
93
|
if J:print(f"[DEBUG] Yielding: {A.type}")
|
|
66
94
|
yield A.data
|
|
67
|
-
elif L==
|
|
68
|
-
|
|
69
|
-
if
|
|
70
|
-
elif
|
|
71
|
-
if J:print(
|
|
72
|
-
def stream_handler(stream,debug=
|
|
73
|
-
R='role';J=debug;G=interrupts;G=[];S='';T=StreamParser(top_fields=['path',
|
|
95
|
+
elif L==_O:
|
|
96
|
+
B=json.loads(D);Q=B.get(_G,'');R=B.get(_P,'');G=B.get(_Q,'');E=B.get(_B,'');I=B.get(_D,'');M=B.get(_R,'');c=B.get(_I,_S)
|
|
97
|
+
if Q==_T:A=emitter.tool_call(E,I,G,R);yield A.data
|
|
98
|
+
elif Q==_U:A=emitter.tool_result(E,M,c,G,R);yield A.data
|
|
99
|
+
if J:print(_b)
|
|
100
|
+
def stream_handler(stream,debug=_N,interrupts=[],tool_mode=_J):
|
|
101
|
+
R='role';J=debug;G=interrupts;G=[];S='';T=StreamParser(top_fields=['path',_E])
|
|
74
102
|
for E in stream:
|
|
75
103
|
if not isinstance(E,tuple)or len(E)!=2:continue
|
|
76
104
|
K,C=E
|
|
77
|
-
if K==
|
|
105
|
+
if K==_H:
|
|
78
106
|
if not isinstance(C,dict):continue
|
|
79
107
|
for(Y,I)in C.items():
|
|
80
|
-
if I is
|
|
108
|
+
if I is _C or isinstance(I,tuple):continue
|
|
81
109
|
if isinstance(I[_A],list)and len(I[_A])>0:
|
|
82
110
|
for D in I[_A]:
|
|
83
111
|
if isinstance(D,AIMessage)and len(D.tool_calls)>0:
|
|
84
112
|
for B in D.tool_calls:
|
|
85
|
-
F=B[
|
|
86
|
-
if tool_mode!=
|
|
113
|
+
F=B[_B];L=B[_D];H=B[_F]
|
|
114
|
+
if tool_mode!=_J and F.strip().lower()in G:continue
|
|
87
115
|
A=emitter.tool_call(F,L,H);yield A.data
|
|
88
116
|
if isinstance(D,ToolMessage):F=D.name;M=D.content;H=D.tool_call_id;A=emitter.tool_result(F,M,True,H);yield A.data
|
|
89
|
-
if isinstance(D,AIMessage)and D.response_metadata['finish_reason']=='stop':N=D.response_metadata.get('token_usage',{});Z=N.get(
|
|
90
|
-
if
|
|
91
|
-
G=C[
|
|
117
|
+
if isinstance(D,AIMessage)and D.response_metadata['finish_reason']=='stop':N=D.response_metadata.get('token_usage',{});Z=N.get(_X,0);a=N.get(_Y,0);b=N.get(_Z,0)
|
|
118
|
+
if _K in C:
|
|
119
|
+
G=C[_K]
|
|
92
120
|
if G:
|
|
93
|
-
print('--'*30);print(f"[INTERRUPT EVENT]: {G}");c=
|
|
94
|
-
for O in U:d=O[R];V=O[
|
|
121
|
+
print('--'*30);print(f"[INTERRUPT EVENT]: {G}");c=_a;U=list(map(lambda interrupt:{_V:interrupt.id,_L:interrupt.value,R:'ask_human'},G))
|
|
122
|
+
for O in U:d=O[R];V=O[_L][_G];emitter.interrupt(event_name='interrupt',event_type=V,event_data=O);break
|
|
95
123
|
elif K==_A:
|
|
96
124
|
if isinstance(C,tuple)and len(C)>=2:E=C[0]
|
|
97
125
|
else:E=C
|
|
98
126
|
if J:W=type(E).__name__;print(f"[DEBUG] Event: {W}")
|
|
99
127
|
if isinstance(E,(AIMessageChunk,AIMessage)):
|
|
100
128
|
for A in bk(E,T):
|
|
101
|
-
if A.type==
|
|
129
|
+
if A.type==_M:S+=A.data.get(_E,'')
|
|
102
130
|
if J:print(f"[DEBUG] Yielding: {A.type}")
|
|
103
131
|
yield A.data
|
|
104
|
-
elif K==
|
|
105
|
-
print(f"[CUSTOM]: {C}");B=json.loads(C);P=getattr(B,
|
|
106
|
-
if P==
|
|
107
|
-
elif P==
|
|
108
|
-
if J:print(
|
|
132
|
+
elif K==_O:
|
|
133
|
+
print(f"[CUSTOM]: {C}");B=json.loads(C);P=getattr(B,_G,'');Q=getattr(B,_P,'');H=getattr(B,_Q,'');F=getattr(B,_B,'');L=getattr(B,_D,'');M=getattr(B,_R,'');X=getattr(B,_I,_S)
|
|
134
|
+
if P==_T:A=emitter.tool_call(F,L,H,Q);yield A.data
|
|
135
|
+
elif P==_U:A=emitter.tool_result(F,M,X,H,Q);yield A.data
|
|
136
|
+
if J:print(_b)
|
|
109
137
|
def bk(chunk,stream_parser):
|
|
110
138
|
M='reasoning';L='thinking';I='write_file';F=stream_parser;E=chunk;B=E.content
|
|
111
139
|
if isinstance(B,str):
|
|
112
140
|
if B:yield emitter.text(B);return
|
|
113
|
-
C=
|
|
141
|
+
C=_C
|
|
114
142
|
if hasattr(E,'content_blocks'):
|
|
115
143
|
try:C=E.content_blocks
|
|
116
|
-
except Exception:C=
|
|
117
|
-
if C is
|
|
144
|
+
except Exception:C=_C
|
|
145
|
+
if C is _C:
|
|
118
146
|
if isinstance(B,dict):C=[B]
|
|
119
147
|
elif isinstance(B,list):C=B
|
|
120
148
|
else:return
|
|
@@ -124,22 +152,22 @@ def bk(chunk,stream_parser):
|
|
|
124
152
|
if hasattr(A,'model_dump'):A=A.model_dump()
|
|
125
153
|
elif hasattr(A,'dict'):A=A.dict()
|
|
126
154
|
else:continue
|
|
127
|
-
G=A.get(
|
|
155
|
+
G=A.get(_G)
|
|
128
156
|
if G in(L,M):
|
|
129
157
|
J=A.get(L)or A.get(M)or''
|
|
130
158
|
if J:yield emitter.thinking(J)
|
|
131
|
-
elif G==
|
|
132
|
-
K=A.get(
|
|
159
|
+
elif G==_M:
|
|
160
|
+
K=A.get(_M)or A.get(_E)or''
|
|
133
161
|
if K:yield emitter.text(K)
|
|
134
162
|
elif G=='tool_call_chunk':
|
|
135
|
-
O=A.get(
|
|
163
|
+
O=A.get(_F,'');H=A.get(_B,'')
|
|
136
164
|
if O:
|
|
137
165
|
if H==I:F.reset()
|
|
138
|
-
D=A.get(
|
|
166
|
+
D=A.get(_D,'')
|
|
139
167
|
if isinstance(D,str)and D:
|
|
140
168
|
if H==I:F.feed(D)
|
|
141
169
|
if H==I and D=='':F.reset()
|
|
142
170
|
def bl(chunk):
|
|
143
|
-
A=chunk;D=getattr(A,
|
|
171
|
+
A=chunk;D=getattr(A,_B,'unknown');B=str(getattr(A,_E,''));E=getattr(A,'tool_call_id','');F=getattr(A,_I,_W);C=B[:DisplayLimits.TOOL_RESULT_MAX]
|
|
144
172
|
if len(B)>DisplayLimits.TOOL_RESULT_MAX:C+='\n... (truncated)'
|
|
145
173
|
yield emitter.tool_result(D,C,F,E)
|