universal-mcp-agents 0.1.19__py3-none-any.whl → 0.1.20rc1__py3-none-any.whl
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.
Potentially problematic release.
This version of universal-mcp-agents might be problematic. Click here for more details.
- universal_mcp/agents/__init__.py +2 -5
- universal_mcp/agents/base.py +2 -2
- universal_mcp/agents/codeact0/__init__.py +2 -3
- universal_mcp/agents/codeact0/__main__.py +2 -2
- universal_mcp/agents/codeact0/agent.py +231 -83
- universal_mcp/agents/codeact0/langgraph_agent.py +1 -1
- universal_mcp/agents/codeact0/prompts.py +37 -7
- universal_mcp/agents/codeact0/sandbox.py +31 -1
- universal_mcp/agents/codeact0/state.py +3 -1
- universal_mcp/agents/codeact0/tools.py +200 -95
- {universal_mcp_agents-0.1.19.dist-info → universal_mcp_agents-0.1.20rc1.dist-info}/METADATA +1 -1
- {universal_mcp_agents-0.1.19.dist-info → universal_mcp_agents-0.1.20rc1.dist-info}/RECORD +13 -22
- universal_mcp/agents/codeact/__init__.py +0 -3
- universal_mcp/agents/codeact/__main__.py +0 -33
- universal_mcp/agents/codeact/agent.py +0 -240
- universal_mcp/agents/codeact/models.py +0 -11
- universal_mcp/agents/codeact/prompts.py +0 -82
- universal_mcp/agents/codeact/sandbox.py +0 -85
- universal_mcp/agents/codeact/state.py +0 -11
- universal_mcp/agents/codeact/utils.py +0 -68
- universal_mcp/agents/codeact0/playbook_agent.py +0 -360
- {universal_mcp_agents-0.1.19.dist-info → universal_mcp_agents-0.1.20rc1.dist-info}/WHEEL +0 -0
universal_mcp/agents/__init__.py
CHANGED
|
@@ -3,8 +3,7 @@ from typing import Literal
|
|
|
3
3
|
from universal_mcp.agents.base import BaseAgent
|
|
4
4
|
from universal_mcp.agents.bigtool import BigToolAgent
|
|
5
5
|
from universal_mcp.agents.builder.builder import BuilderAgent
|
|
6
|
-
from universal_mcp.agents.
|
|
7
|
-
from universal_mcp.agents.codeact0 import CodeActPlaybookAgent as CodeActRepl
|
|
6
|
+
from universal_mcp.agents.codeact0 import CodeActPlaybookAgent
|
|
8
7
|
from universal_mcp.agents.react import ReactAgent
|
|
9
8
|
from universal_mcp.agents.simple import SimpleAgent
|
|
10
9
|
|
|
@@ -20,10 +19,8 @@ def get_agent(
|
|
|
20
19
|
return BuilderAgent
|
|
21
20
|
elif agent_name == "bigtool":
|
|
22
21
|
return BigToolAgent
|
|
23
|
-
elif agent_name == "codeact-script":
|
|
24
|
-
return CodeActScript
|
|
25
22
|
elif agent_name == "codeact-repl":
|
|
26
|
-
return
|
|
23
|
+
return CodeActPlaybookAgent
|
|
27
24
|
else:
|
|
28
25
|
raise ValueError(
|
|
29
26
|
f"Unknown agent: {agent_name}. Possible values: react, simple, builder, bigtool, codeact-script, codeact-repl"
|
universal_mcp/agents/base.py
CHANGED
|
@@ -49,7 +49,7 @@ class BaseAgent:
|
|
|
49
49
|
run_metadata.update(metadata)
|
|
50
50
|
|
|
51
51
|
run_config = {
|
|
52
|
-
"recursion_limit":
|
|
52
|
+
"recursion_limit": 50,
|
|
53
53
|
"configurable": {"thread_id": thread_id},
|
|
54
54
|
"metadata": run_metadata,
|
|
55
55
|
"run_id": thread_id,
|
|
@@ -116,7 +116,7 @@ class BaseAgent:
|
|
|
116
116
|
run_metadata.update(metadata)
|
|
117
117
|
|
|
118
118
|
run_config = {
|
|
119
|
-
"recursion_limit":
|
|
119
|
+
"recursion_limit": 50,
|
|
120
120
|
"configurable": {"thread_id": thread_id},
|
|
121
121
|
"metadata": run_metadata,
|
|
122
122
|
"run_id": thread_id,
|
|
@@ -4,13 +4,13 @@ from langgraph.checkpoint.memory import MemorySaver
|
|
|
4
4
|
from rich import print
|
|
5
5
|
from universal_mcp.agentr.registry import AgentrRegistry
|
|
6
6
|
|
|
7
|
-
from universal_mcp.agents.codeact0.agent import
|
|
7
|
+
from universal_mcp.agents.codeact0.agent import CodeActPlaybookAgent
|
|
8
8
|
from universal_mcp.agents.utils import messages_to_list
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
async def main():
|
|
12
12
|
memory = MemorySaver()
|
|
13
|
-
agent =
|
|
13
|
+
agent = CodeActPlaybookAgent(
|
|
14
14
|
name="CodeAct Agent",
|
|
15
15
|
instructions="Be very concise in your answers.",
|
|
16
16
|
model="anthropic:claude-4-sonnet-20250514",
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
2
3
|
from collections.abc import Callable
|
|
3
4
|
from typing import Literal, cast
|
|
4
5
|
|
|
5
6
|
from langchain_core.messages import AIMessage, ToolMessage
|
|
6
7
|
from langchain_core.tools import StructuredTool
|
|
7
|
-
from langchain_core.tools import tool as create_tool
|
|
8
8
|
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
9
9
|
from langgraph.graph import START, StateGraph
|
|
10
10
|
from langgraph.types import Command, RetryPolicy
|
|
@@ -14,16 +14,23 @@ from universal_mcp.types import ToolConfig, ToolFormat
|
|
|
14
14
|
from universal_mcp.agents.base import BaseAgent
|
|
15
15
|
from universal_mcp.agents.codeact0.llm_tool import ai_classify, call_llm, data_extractor, smart_print
|
|
16
16
|
from universal_mcp.agents.codeact0.prompts import (
|
|
17
|
+
PLAYBOOK_CONFIRMING_PROMPT,
|
|
18
|
+
PLAYBOOK_GENERATING_PROMPT,
|
|
19
|
+
PLAYBOOK_PLANNING_PROMPT,
|
|
17
20
|
create_default_prompt,
|
|
18
21
|
)
|
|
19
|
-
from universal_mcp.agents.codeact0.sandbox import eval_unsafe, execute_ipython_cell
|
|
22
|
+
from universal_mcp.agents.codeact0.sandbox import eval_unsafe, execute_ipython_cell, handle_execute_ipython_cell
|
|
20
23
|
from universal_mcp.agents.codeact0.state import CodeActState
|
|
21
|
-
from universal_mcp.agents.codeact0.
|
|
24
|
+
from universal_mcp.agents.codeact0.tools import (
|
|
25
|
+
create_meta_tools,
|
|
26
|
+
enter_playbook_mode,
|
|
27
|
+
get_valid_tools,
|
|
28
|
+
)
|
|
22
29
|
from universal_mcp.agents.llm import load_chat_model
|
|
23
|
-
from universal_mcp.agents.utils import filter_retry_on
|
|
30
|
+
from universal_mcp.agents.utils import convert_tool_ids_to_dict, filter_retry_on, get_message_text
|
|
24
31
|
|
|
25
32
|
|
|
26
|
-
class
|
|
33
|
+
class CodeActPlaybookAgent(BaseAgent):
|
|
27
34
|
def __init__(
|
|
28
35
|
self,
|
|
29
36
|
name: str,
|
|
@@ -32,6 +39,7 @@ class CodeActAgent(BaseAgent):
|
|
|
32
39
|
memory: BaseCheckpointSaver | None = None,
|
|
33
40
|
tools: ToolConfig | None = None,
|
|
34
41
|
registry: ToolRegistry | None = None,
|
|
42
|
+
playbook_registry: object | None = None,
|
|
35
43
|
sandbox_timeout: int = 20,
|
|
36
44
|
**kwargs,
|
|
37
45
|
):
|
|
@@ -42,103 +50,243 @@ class CodeActAgent(BaseAgent):
|
|
|
42
50
|
memory=memory,
|
|
43
51
|
**kwargs,
|
|
44
52
|
)
|
|
45
|
-
self.model_instance = load_chat_model(model
|
|
46
|
-
self.tools_config = tools or
|
|
53
|
+
self.model_instance = load_chat_model(model)
|
|
54
|
+
self.tools_config = tools or []
|
|
47
55
|
self.registry = registry
|
|
56
|
+
self.playbook_registry = playbook_registry
|
|
48
57
|
self.eval_fn = eval_unsafe
|
|
49
58
|
self.sandbox_timeout = sandbox_timeout
|
|
50
59
|
self.processed_tools: list[StructuredTool | Callable] = []
|
|
51
60
|
|
|
52
|
-
# TODO(manoj): Use toolformat native instead of langchain
|
|
53
|
-
# TODO(manoj, later): Add better sandboxing
|
|
54
|
-
# Old Nishant TODO s:
|
|
55
|
-
# - Make codeact faster by calling upto API call (this done but should be tested)
|
|
56
|
-
# - Add support for async eval_fn
|
|
57
|
-
# - Throw Error if code snippet is too long (> 1000 characters) and suggest to split it into smaller parts
|
|
58
|
-
# - Multiple models from config
|
|
59
|
-
|
|
60
61
|
async def _build_graph(self):
|
|
61
|
-
|
|
62
|
+
meta_tools = create_meta_tools(self.registry)
|
|
63
|
+
additional_tools = [smart_print, data_extractor, ai_classify, call_llm, meta_tools["web_search"]]
|
|
64
|
+
self.additional_tools = [
|
|
65
|
+
t if isinstance(t, StructuredTool) else StructuredTool.from_function(t) for t in additional_tools
|
|
66
|
+
]
|
|
62
67
|
if self.tools_config:
|
|
68
|
+
# Convert dict format to list format if needed
|
|
69
|
+
if isinstance(self.tools_config, dict):
|
|
70
|
+
self.tools_config = [
|
|
71
|
+
f"{provider}__{tool}" for provider, tools in self.tools_config.items() for tool in tools
|
|
72
|
+
]
|
|
63
73
|
if not self.registry:
|
|
64
74
|
raise ValueError("Tools are configured but no registry is provided")
|
|
65
|
-
# Langchain tools are fine
|
|
66
|
-
exported_tools = await self.registry.export_tools(self.tools_config, ToolFormat.LANGCHAIN)
|
|
67
|
-
additional_tools = [smart_print, data_extractor, ai_classify, call_llm]
|
|
68
|
-
additional_tools = [t if isinstance(t, StructuredTool) else create_tool(t) for t in additional_tools]
|
|
69
|
-
self.instructions, self.tools_context = create_default_prompt(
|
|
70
|
-
exported_tools, additional_tools, self.instructions
|
|
71
|
-
)
|
|
72
75
|
|
|
73
|
-
def call_model(state: CodeActState) -> Command[Literal["
|
|
74
|
-
messages = [{"role": "system", "content": self.
|
|
76
|
+
async def call_model(state: CodeActState) -> Command[Literal["execute_tools"]]:
|
|
77
|
+
messages = [{"role": "system", "content": self.final_instructions}] + state["messages"]
|
|
75
78
|
|
|
76
79
|
# Run the model and potentially loop for reflection
|
|
77
|
-
model_with_tools = self.model_instance.bind_tools(
|
|
80
|
+
model_with_tools = self.model_instance.bind_tools(
|
|
81
|
+
tools=[
|
|
82
|
+
execute_ipython_cell,
|
|
83
|
+
enter_playbook_mode,
|
|
84
|
+
meta_tools["search_functions"],
|
|
85
|
+
meta_tools["load_functions"],
|
|
86
|
+
],
|
|
87
|
+
tool_choice="auto",
|
|
88
|
+
)
|
|
78
89
|
response = cast(AIMessage, model_with_tools.invoke(messages))
|
|
79
|
-
|
|
80
90
|
if response.tool_calls:
|
|
81
|
-
|
|
82
|
-
raise Exception("Not possible in Claude with llm.bind_tools(tools=tools, tool_choice='auto')")
|
|
83
|
-
if response.tool_calls[0]["name"] != "execute_ipython_cell":
|
|
84
|
-
raise Exception(
|
|
85
|
-
f"Unexpected tool call: {response.tool_calls[0]['name']}. Expected 'execute_ipython_cell'."
|
|
86
|
-
)
|
|
87
|
-
if (
|
|
88
|
-
response.tool_calls[0]["args"].get("snippet") is None
|
|
89
|
-
or not response.tool_calls[0]["args"]["snippet"].strip()
|
|
90
|
-
):
|
|
91
|
-
raise Exception("Tool call 'execute_ipython_cell' requires a non-empty 'snippet' argument.")
|
|
92
|
-
return Command(goto="sandbox", update={"messages": [response]})
|
|
91
|
+
return Command(goto="execute_tools", update={"messages": [response]})
|
|
93
92
|
else:
|
|
94
|
-
return Command(update={"messages": [response]})
|
|
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
|
-
|
|
93
|
+
return Command(update={"messages": [response], "model_with_tools": model_with_tools})
|
|
94
|
+
|
|
95
|
+
async def execute_tools(state: CodeActState) -> Command[Literal["call_model", "playbook"]]:
|
|
96
|
+
"""Execute tool calls"""
|
|
97
|
+
last_message = state["messages"][-1]
|
|
98
|
+
tool_calls = last_message.tool_calls if isinstance(last_message, AIMessage) else []
|
|
99
|
+
|
|
100
|
+
tool_messages = []
|
|
101
|
+
new_tool_ids = []
|
|
102
|
+
ask_user = False
|
|
103
|
+
ai_msg = ""
|
|
104
|
+
tool_result = ""
|
|
105
|
+
effective_previous_add_context = state.get("add_context", {})
|
|
106
|
+
effective_existing_context = state.get("context", {})
|
|
107
|
+
|
|
108
|
+
for tool_call in tool_calls:
|
|
109
|
+
try:
|
|
110
|
+
if tool_call["name"] == "enter_playbook_mode":
|
|
111
|
+
tool_message = ToolMessage(
|
|
112
|
+
content=json.dumps("Entered Playbook Mode."),
|
|
113
|
+
name=tool_call["name"],
|
|
114
|
+
tool_call_id=tool_call["id"],
|
|
115
|
+
)
|
|
116
|
+
return Command(
|
|
117
|
+
goto="playbook",
|
|
118
|
+
update={"playbook_mode": "planning", "messages": [tool_message]}, # Entered Playbook mode
|
|
119
|
+
)
|
|
120
|
+
elif tool_call["name"] == "execute_ipython_cell":
|
|
121
|
+
code = tool_call["args"]["snippet"]
|
|
122
|
+
output, new_context, new_add_context = await handle_execute_ipython_cell(
|
|
123
|
+
code,
|
|
124
|
+
self.tools_context,
|
|
125
|
+
self.eval_fn,
|
|
126
|
+
effective_previous_add_context,
|
|
127
|
+
effective_existing_context,
|
|
128
|
+
)
|
|
129
|
+
effective_existing_context = new_context
|
|
130
|
+
effective_previous_add_context = new_add_context
|
|
131
|
+
tool_result = output
|
|
132
|
+
elif tool_call["name"] == "load_functions": # Handle load_functions separately
|
|
133
|
+
valid_tools, unconnected_links = await get_valid_tools(
|
|
134
|
+
tool_ids=tool_call["args"]["tool_ids"], registry=self.registry
|
|
135
|
+
)
|
|
136
|
+
new_tool_ids.extend(valid_tools)
|
|
137
|
+
# Create tool message response
|
|
138
|
+
tool_result = f"Successfully loaded {len(valid_tools)} tools: {valid_tools}"
|
|
139
|
+
links = "\n".join(unconnected_links)
|
|
140
|
+
if links:
|
|
141
|
+
ask_user = True
|
|
142
|
+
ai_msg = f"Please login to the following app(s) using the following links and let me know in order to proceed:\n {links} "
|
|
143
|
+
elif tool_call["name"] == "search_functions":
|
|
144
|
+
tool_result = await meta_tools["search_functions"].ainvoke(tool_call["args"])
|
|
145
|
+
else:
|
|
146
|
+
raise Exception(
|
|
147
|
+
f"Unexpected tool call: {tool_call['name']}. "
|
|
148
|
+
"tool calls must be one of 'enter_playbook_mode', 'execute_ipython_cell', 'load_functions', or 'search_functions'"
|
|
149
|
+
)
|
|
150
|
+
except Exception as e:
|
|
151
|
+
tool_result = str(e)
|
|
124
152
|
|
|
153
|
+
tool_message = ToolMessage(
|
|
154
|
+
content=json.dumps(tool_result),
|
|
155
|
+
name=tool_call["name"],
|
|
156
|
+
tool_call_id=tool_call["id"],
|
|
157
|
+
)
|
|
158
|
+
tool_messages.append(tool_message)
|
|
159
|
+
|
|
160
|
+
if new_tool_ids:
|
|
161
|
+
self.tools_config.extend(new_tool_ids)
|
|
162
|
+
self.exported_tools = await self.registry.export_tools(new_tool_ids, ToolFormat.LANGCHAIN)
|
|
163
|
+
self.final_instructions, self.tools_context = create_default_prompt(
|
|
164
|
+
self.exported_tools, self.additional_tools, self.instructions
|
|
165
|
+
)
|
|
166
|
+
if ask_user:
|
|
167
|
+
tool_messages.append(AIMessage(content=ai_msg))
|
|
125
168
|
return Command(
|
|
126
|
-
goto="call_model",
|
|
127
169
|
update={
|
|
128
|
-
"messages":
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
)
|
|
134
|
-
],
|
|
135
|
-
"context": new_context,
|
|
136
|
-
"add_context": new_add_context,
|
|
137
|
-
},
|
|
170
|
+
"messages": tool_messages,
|
|
171
|
+
"selected_tool_ids": new_tool_ids,
|
|
172
|
+
"context": effective_existing_context,
|
|
173
|
+
"add_context": effective_previous_add_context,
|
|
174
|
+
}
|
|
138
175
|
)
|
|
139
176
|
|
|
177
|
+
return Command(
|
|
178
|
+
goto="call_model",
|
|
179
|
+
update={
|
|
180
|
+
"messages": tool_messages,
|
|
181
|
+
"selected_tool_ids": new_tool_ids,
|
|
182
|
+
"context": effective_existing_context,
|
|
183
|
+
"add_context": effective_previous_add_context,
|
|
184
|
+
},
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def playbook(state: CodeActState) -> Command[Literal["call_model"]]:
|
|
188
|
+
playbook_mode = state.get("playbook_mode")
|
|
189
|
+
if playbook_mode == "planning":
|
|
190
|
+
planning_instructions = self.instructions + PLAYBOOK_PLANNING_PROMPT
|
|
191
|
+
messages = [{"role": "system", "content": planning_instructions}] + state["messages"]
|
|
192
|
+
|
|
193
|
+
response = self.model_instance.invoke(messages)
|
|
194
|
+
response = cast(AIMessage, response)
|
|
195
|
+
response_text = get_message_text(response)
|
|
196
|
+
# Extract plan from response text between triple backticks
|
|
197
|
+
plan_match = re.search(r"```(.*?)```", response_text, re.DOTALL)
|
|
198
|
+
if plan_match:
|
|
199
|
+
plan = plan_match.group(1).strip()
|
|
200
|
+
else:
|
|
201
|
+
plan = response_text.strip()
|
|
202
|
+
return Command(update={"messages": [response], "playbook_mode": "confirming", "plan": plan})
|
|
203
|
+
|
|
204
|
+
elif playbook_mode == "confirming":
|
|
205
|
+
confirmation_instructions = self.instructions + PLAYBOOK_CONFIRMING_PROMPT
|
|
206
|
+
messages = [{"role": "system", "content": confirmation_instructions}] + state["messages"]
|
|
207
|
+
response = self.model_instance.invoke(messages, stream=False)
|
|
208
|
+
response = get_message_text(response)
|
|
209
|
+
if "true" in response.lower():
|
|
210
|
+
return Command(goto="playbook", update={"playbook_mode": "generating"})
|
|
211
|
+
else:
|
|
212
|
+
return Command(goto="playbook", update={"playbook_mode": "planning"})
|
|
213
|
+
|
|
214
|
+
elif playbook_mode == "generating":
|
|
215
|
+
generating_instructions = self.instructions + PLAYBOOK_GENERATING_PROMPT
|
|
216
|
+
messages = [{"role": "system", "content": generating_instructions}] + state["messages"]
|
|
217
|
+
response = cast(AIMessage, self.model_instance.invoke(messages))
|
|
218
|
+
raw_content = get_message_text(response)
|
|
219
|
+
func_code = raw_content.strip()
|
|
220
|
+
func_code = func_code.replace("```python", "").replace("```", "")
|
|
221
|
+
func_code = func_code.strip()
|
|
222
|
+
|
|
223
|
+
# Extract function name (handle both regular and async functions)
|
|
224
|
+
match = re.search(r"^\s*(?:async\s+)?def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(", func_code, re.MULTILINE)
|
|
225
|
+
if match:
|
|
226
|
+
function_name = match.group(1)
|
|
227
|
+
else:
|
|
228
|
+
function_name = "generated_playbook"
|
|
229
|
+
|
|
230
|
+
# Save or update an Agent using the helper registry
|
|
231
|
+
saved_note = ""
|
|
232
|
+
try:
|
|
233
|
+
if not self.playbook_registry:
|
|
234
|
+
raise ValueError("Playbook registry is not configured")
|
|
235
|
+
|
|
236
|
+
# Build instructions payload embedding the plan and function code
|
|
237
|
+
instructions_payload = {
|
|
238
|
+
"playbookPlan": state["plan"],
|
|
239
|
+
"playbookScript": {
|
|
240
|
+
"name": function_name,
|
|
241
|
+
"code": func_code,
|
|
242
|
+
},
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
# Convert tool ids list to dict
|
|
246
|
+
tool_dict = convert_tool_ids_to_dict(state["selected_tool_ids"])
|
|
247
|
+
|
|
248
|
+
res = self.playbook_registry.create_agent(
|
|
249
|
+
name=function_name,
|
|
250
|
+
description=f"Generated playbook: {function_name}",
|
|
251
|
+
instructions=instructions_payload,
|
|
252
|
+
tools=tool_dict,
|
|
253
|
+
visibility="private",
|
|
254
|
+
)
|
|
255
|
+
saved_note = f"Successfully created your playbook! Check it out here: [View Playbook](https://wingmen.info/agents/{res.id})"
|
|
256
|
+
except Exception as e:
|
|
257
|
+
saved_note = f"Failed to save generated playbook as Agent '{function_name}': {e}"
|
|
258
|
+
|
|
259
|
+
# Mock tool call for exit_playbook_mode (for testing/demonstration)
|
|
260
|
+
mock_exit_tool_call = {"name": "exit_playbook_mode", "args": {}, "id": "mock_exit_playbook_123"}
|
|
261
|
+
mock_assistant_message = AIMessage(content=saved_note, tool_calls=[mock_exit_tool_call])
|
|
262
|
+
|
|
263
|
+
# Mock tool response for exit_playbook_mode
|
|
264
|
+
mock_exit_tool_response = ToolMessage(
|
|
265
|
+
content=json.dumps(f"Exited Playbook Mode.{saved_note}"),
|
|
266
|
+
name="exit_playbook_mode",
|
|
267
|
+
tool_call_id="mock_exit_playbook_123",
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
return Command(
|
|
271
|
+
update={"messages": [mock_assistant_message, mock_exit_tool_response], "playbook_mode": "normal"}
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
async def route_entry(state: CodeActState) -> Literal["call_model", "playbook"]:
|
|
275
|
+
"""Route to either normal mode or playbook creation"""
|
|
276
|
+
self.exported_tools = []
|
|
277
|
+
self.tools_config.extend(state.get("selected_tool_ids", []))
|
|
278
|
+
self.exported_tools = await self.registry.export_tools(self.tools_config, ToolFormat.LANGCHAIN)
|
|
279
|
+
self.final_instructions, self.tools_context = create_default_prompt(
|
|
280
|
+
self.exported_tools, self.additional_tools, self.instructions
|
|
281
|
+
)
|
|
282
|
+
if state.get("playbook_mode") in ["planning", "confirming", "generating"]:
|
|
283
|
+
return "playbook"
|
|
284
|
+
return "call_model"
|
|
285
|
+
|
|
140
286
|
agent = StateGraph(state_schema=CodeActState)
|
|
141
287
|
agent.add_node(call_model, retry_policy=RetryPolicy(max_attempts=3, retry_on=filter_retry_on))
|
|
142
|
-
agent.add_node(
|
|
143
|
-
agent.
|
|
288
|
+
agent.add_node(playbook)
|
|
289
|
+
agent.add_node(execute_tools)
|
|
290
|
+
agent.add_conditional_edges(START, route_entry)
|
|
291
|
+
# agent.add_edge(START, "call_model")
|
|
144
292
|
return agent.compile(checkpointer=self.memory)
|
|
@@ -10,16 +10,15 @@ uneditable_prompt = """
|
|
|
10
10
|
You are **Wingmen**, an AI Assistant created by AgentR — a creative, straight-forward, and direct principal software engineer with access to tools.
|
|
11
11
|
|
|
12
12
|
Your job is to answer the user's question or perform the task they ask for.
|
|
13
|
-
- Answer simple questions (which do not require you to write any code or access any external resources) directly. Note that any operation that involves using ONLY print functions should be answered directly.
|
|
13
|
+
- Answer simple questions (which do not require you to write any code or access any external resources) directly. Note that any operation that involves using ONLY print functions should be answered directly in the chat. NEVER write a string yourself and print it.
|
|
14
14
|
- For task requiring operations or access to external resources, you should achieve the task by executing Python code snippets.
|
|
15
15
|
- You have access to `execute_ipython_cell` tool that allows you to execute Python code in an IPython notebook cell.
|
|
16
|
-
- You also have access to two tools for finding and loading more python functions- `search_functions` and `load_functions`, which you must use for finding functions for using different external applications.
|
|
17
|
-
- Prefer pre-loaded or functions already available when possible.
|
|
16
|
+
- You also have access to two tools for finding and loading more python functions- `search_functions` and `load_functions`, which you must use for finding functions for using different external applications or additional functionality.
|
|
18
17
|
- Prioritize connected applications over unconnected ones from the output of `search_functions`.
|
|
19
|
-
- When multiple apps are connected, or none of the apps are connected, ask the user to choose the application(s).
|
|
20
|
-
- In writing or natural language processing tasks DO NOT answer directly. Instead use `execute_ipython_cell` tool with the AI functions provided to you for tasks like summarizing, text generation, classification, data extraction from text or unstructured data, etc. Avoid hardcoded approaches to classification, data extraction.
|
|
18
|
+
- When multiple apps are connected, or none of the apps are connected, YOU MUST ask the user to choose the application(s). The search results will inform you when such a case occurs, and you must stop and ask the user if multiple apps are relevant.
|
|
19
|
+
- In writing or natural language processing tasks DO NOT answer directly. Instead use `execute_ipython_cell` tool with the AI functions provided to you for tasks like summarizing, text generation, classification, data extraction from text or unstructured data, etc. Avoid hardcoded approaches to classification, data extraction, or creative writing.
|
|
21
20
|
- The code you write will be executed in a sandbox environment, and you can use the output of previous executions in your code. variables, functions, imports are retained.
|
|
22
|
-
- Read and understand the output of the previous code snippet and use it to answer the user's request. Note that the code output is NOT visible to the user, so after the task is complete, you have to give the output to the user in a markdown format.
|
|
21
|
+
- Read and understand the output of the previous code snippet and use it to answer the user's request. Note that the code output is NOT visible to the user, so after the task is complete, you have to give the output to the user in a markdown format. Similarly, you should only use print/smart_print for your own analysis, the user does not get the output.
|
|
23
22
|
- If needed, feel free to ask for more information from the user (without using the `execute_ipython_cell` tool) to clarify the task.
|
|
24
23
|
|
|
25
24
|
GUIDELINES for writing code:
|
|
@@ -27,7 +26,7 @@ GUIDELINES for writing code:
|
|
|
27
26
|
- External functions which return a dict or list[dict] are ambiguous. Therefore, you MUST explore the structure of the returned data using `smart_print()` statements before using it, printing keys and values. `smart_print` truncates long strings from data, preventing huge output logs.
|
|
28
27
|
- When an operation involves running a fixed set of steps on a list of items, run one run correctly and then use a for loop to run the steps on each item in the list.
|
|
29
28
|
- In a single code snippet, try to achieve as much as possible.
|
|
30
|
-
- You can only import libraries that come pre-installed with Python.
|
|
29
|
+
- You can only import libraries that come pre-installed with Python. However, do consider searching for external functions first, using the search and load tools to access them in the code.
|
|
31
30
|
- For displaying final results to the user, you must present your output in markdown format, including image links, so that they are rendered and displayed to the user. The code output is NOT visible to the user.
|
|
32
31
|
- Call all functions using keyword arguments only, never positional arguments.
|
|
33
32
|
- Async Functions (Critical): Use them only as follows-
|
|
@@ -46,6 +45,37 @@ Rules:
|
|
|
46
45
|
- Never nest asyncio.run() calls
|
|
47
46
|
"""
|
|
48
47
|
|
|
48
|
+
PLAYBOOK_PLANNING_PROMPT = """Now, you are tasked with creating a reusable playbook from the user's previous workflow.
|
|
49
|
+
|
|
50
|
+
TASK: Analyze the conversation history and code execution to create a step-by-step plan for a reusable function. Do not include the searching and loading of tools. Assume that the tools have already been loaded.
|
|
51
|
+
|
|
52
|
+
Your plan should:
|
|
53
|
+
1. Identify the key steps in the workflow
|
|
54
|
+
2. Mark user-specific variables that should become the main playbook function parameters using `variable_name` syntax. Intermediate variables should not be highlighted using ``
|
|
55
|
+
3. Keep the logic generic and reusable
|
|
56
|
+
4. Be clear and concise
|
|
57
|
+
|
|
58
|
+
Example:
|
|
59
|
+
```
|
|
60
|
+
1. Connect to database using `db_connection_string`
|
|
61
|
+
2. Query user data for `user_id`
|
|
62
|
+
3. Process results and calculate `metric_name`
|
|
63
|
+
4. Send notification to `email_address`
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Now create a plan based on the conversation history. Enclose it between ``` and ```. Ask the user if the plan is okay."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
PLAYBOOK_CONFIRMING_PROMPT = """Now, you are tasked with confirming the playbook plan. Return True if the user is happy with the plan, False otherwise. Do not say anything else in your response. The user response will be the last message in the chain.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
PLAYBOOK_GENERATING_PROMPT = """Now, you are tasked with generating the playbook function. Return the function in Python code.
|
|
73
|
+
Do not include any other text in your response.
|
|
74
|
+
The function should be a single, complete piece of code that can be executed independently, based on previously executed code snippets that executed correctly.
|
|
75
|
+
The parameters of the function should be the same as the final confirmed playbook plan.
|
|
76
|
+
Do not include anything other than python code in your response
|
|
77
|
+
"""
|
|
78
|
+
|
|
49
79
|
|
|
50
80
|
def make_safe_function_name(name: str) -> str:
|
|
51
81
|
"""Convert a tool name to a valid Python function name."""
|
|
@@ -10,7 +10,7 @@ from typing import Any
|
|
|
10
10
|
|
|
11
11
|
from langchain_core.tools import tool
|
|
12
12
|
|
|
13
|
-
from universal_mcp.agents.codeact0.utils import derive_context
|
|
13
|
+
from universal_mcp.agents.codeact0.utils import derive_context, inject_context, smart_truncate
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
def eval_unsafe(
|
|
@@ -53,6 +53,14 @@ def eval_unsafe(
|
|
|
53
53
|
if thread.is_alive():
|
|
54
54
|
result_container["output"] = f"Code timeout: code execution exceeded {timeout} seconds."
|
|
55
55
|
|
|
56
|
+
# If NameError for provider__tool occurred, append guidance (no retry)
|
|
57
|
+
try:
|
|
58
|
+
m = re.search(r"NameError:\s*name\s*'([^']+)'\s*is\s*not\s*defined", result_container["output"])
|
|
59
|
+
if m and "__" in m.group(1):
|
|
60
|
+
result_container["output"] += "\nHint: If it is a valid tool, load it before running this snippet."
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
|
|
56
64
|
# Filter locals for picklable/storable variables
|
|
57
65
|
all_vars = {}
|
|
58
66
|
for key, value in _locals.items():
|
|
@@ -99,3 +107,25 @@ def execute_ipython_cell(snippet: str) -> str:
|
|
|
99
107
|
|
|
100
108
|
# Your actual execution logic would go here
|
|
101
109
|
return f"Successfully executed {len(snippet)} characters of Python code"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def handle_execute_ipython_cell(
|
|
113
|
+
code: str,
|
|
114
|
+
tools_context: dict[str, Any],
|
|
115
|
+
eval_fn,
|
|
116
|
+
effective_previous_add_context: dict[str, Any],
|
|
117
|
+
effective_existing_context: dict[str, Any],
|
|
118
|
+
) -> tuple[str, dict[str, Any], dict[str, Any]]:
|
|
119
|
+
"""
|
|
120
|
+
Execute a code cell with shared state, supporting both sync and async eval functions.
|
|
121
|
+
|
|
122
|
+
Returns (output, new_context, new_add_context).
|
|
123
|
+
"""
|
|
124
|
+
add_context = inject_context(effective_previous_add_context, tools_context)
|
|
125
|
+
context = {**effective_existing_context, **add_context}
|
|
126
|
+
if inspect.iscoroutinefunction(eval_fn):
|
|
127
|
+
output, new_context, new_add_context = await eval_fn(code, context, effective_previous_add_context, 180)
|
|
128
|
+
else:
|
|
129
|
+
output, new_context, new_add_context = eval_fn(code, context, effective_previous_add_context, 180)
|
|
130
|
+
output = smart_truncate(output)
|
|
131
|
+
return output, new_context, new_add_context
|
|
@@ -6,6 +6,8 @@ from langgraph.prebuilt.chat_agent_executor import AgentState
|
|
|
6
6
|
def _enqueue(left: list, right: list) -> list:
|
|
7
7
|
"""Treat left as a FIFO queue, append new items from right (preserve order),
|
|
8
8
|
keep items unique, and cap total size to 20 (drop oldest items)."""
|
|
9
|
+
|
|
10
|
+
# Tool ifd are unique
|
|
9
11
|
max_size = 30
|
|
10
12
|
preferred_size = 20
|
|
11
13
|
if len(right) > preferred_size:
|
|
@@ -20,7 +22,7 @@ def _enqueue(left: list, right: list) -> list:
|
|
|
20
22
|
if len(queue) > preferred_size:
|
|
21
23
|
queue = queue[-preferred_size:]
|
|
22
24
|
|
|
23
|
-
return queue
|
|
25
|
+
return list(set(queue))
|
|
24
26
|
|
|
25
27
|
|
|
26
28
|
class CodeActState(AgentState):
|