Spaces:
Running
Running
Sync tool execution semantics
Browse filesFiles changed (4)
1v0.0.351v0.0.36
91 unmodified lines92939495969791 unmodified lines- ask the human user for essential missing information -> `AskUser`- persistent interactive shell state -> `Terminal*`- Search results and scholar results are discovery aids. They are not page-verification evidence by themselves.- Prefer `Bash` over `Terminal*` unless persistent interactive shell state is genuinely required.## Human Clarification Workflow91 unmodified lines9293949596979891 unmodified lines- ask the human user for essential missing information -> `AskUser`- persistent interactive shell state -> `Terminal*`- Search results and scholar results are discovery aids. They are not page-verification evidence by themselves.- Each tool call should express one clear request. For independent read-only work, such as multiple searches, multiple page fetches, or multiple file reads, issue multiple tool calls in the same assistant turn rather than packing several requests into one tool argument.- Prefer `Bash` over `Terminal*` unless persistent interactive shell state is genuinely required.## Human Clarification Workflow
123474 unmodified lines798081828384528 unmodified lines613614615616617618597 unmodified lines12161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253import argparsefrom contextlib import contextmanagerimport jsonimport os74 unmodified linesDEFAULT_TOP_P = 0.95DEFAULT_PRESENCE_PENALTY = 1.1DEFAULT_LLM_TIMEOUT_SECONDS = 600.0def default_model_name() -> str:528 unmodified linesreturn tool.call(tool_args, **kwargs)class MultiTurnReactAgent(BaseAgent):def __init__(self,597 unmodified linestool_turn_message_start = len(messages)messages.append(assistant_message)deferred_image_contexts: list[tuple[str, str, Any, Any, dict[str, Any]]] = []for tool_call, tool_arguments in zip(assistant_tool_calls, assistant_tool_arguments):if remaining_runtime_seconds(runtime_deadline) is not None and remaining_runtime_seconds(runtime_deadline) <= 0:result_text = "No result found before the maximum agent runtime limit."termination = f"agent runtime limit reached: {agent_runtime_limit}s"return finalize(result_text, termination, error=termination)tool_call_id = str(tool_call.get("id", ""))function_block = tool_call.get("function", {}) if isinstance(tool_call, dict) else {}tool_name = str(function_block.get("name", ""))try:result = self.custom_call_tool(tool_name,tool_arguments,workspace_root=resolved_workspace_root,runtime_deadline=runtime_deadline,model_name=self.model,)except KeyboardInterrupt:messages = messages[:tool_turn_message_start]return finalize_interrupted()tool_result_text = tool_result_message_content(result)messages.append(api_tool_message(tool_call_id, result))trace_writer.append(role="tool",text=tool_result_text,turn_index=round_index,tool_call_ids=[tool_call_id],tool_names=[tool_name],tool_arguments=[tool_arguments],)extra_image_context = image_context_message(result, self.model)if extra_image_context is not None:deferred_image_contexts.append((tool_call_id, tool_name, tool_arguments, result, extra_image_context))for tool_call_id, tool_name, tool_arguments, result, extra_image_context in deferred_image_contexts:messages.append(extra_image_context)trace_writer.append(1234574 unmodified lines808182838485868788899091929394959697528 unmodified lines626627628629630631632633634635636637638639640641642643644645646647648649650651597 unmodified lines1249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312import argparsefrom concurrent.futures import ThreadPoolExecutorfrom contextlib import contextmanagerimport jsonimport os74 unmodified linesDEFAULT_TOP_P = 0.95DEFAULT_PRESENCE_PENALTY = 1.1DEFAULT_LLM_TIMEOUT_SECONDS = 600.0MAX_PARALLEL_READ_TOOL_CALLS = 3PARALLEL_READ_TOOL_NAMES = frozenset({"Glob","Grep","Read","ReadImage","WebSearch","ScholarSearch","WebFetch",})def default_model_name() -> str:528 unmodified linesreturn tool.call(tool_args, **kwargs)def can_parallelize_tool_name(tool_name: str) -> bool:return tool_name in PARALLEL_READ_TOOL_NAMESdef tool_execution_batches(tool_names: Sequence[str]) -> list[list[int]]:batches: list[list[int]] = []read_batch: list[int] = []for index, tool_name in enumerate(tool_names):if can_parallelize_tool_name(tool_name):read_batch.append(index)continueif read_batch:batches.append(read_batch)read_batch = []batches.append([index])if read_batch:batches.append(read_batch)return batchesclass MultiTurnReactAgent(BaseAgent):def __init__(self,597 unmodified linestool_turn_message_start = len(messages)messages.append(assistant_message)deferred_image_contexts: list[tuple[str, str, Any, Any, dict[str, Any]]] = []tool_call_items: list[dict[str, Any]] = []for tool_call, tool_arguments in zip(assistant_tool_calls, assistant_tool_arguments):function_block = tool_call.get("function", {}) if isinstance(tool_call, dict) else {}tool_call_items.append({"tool_call_id": str(tool_call.get("id", "")),"tool_name": str(function_block.get("name", "")),"tool_arguments": tool_arguments,})def execute_tool_item(item: dict[str, Any]) -> tuple[dict[str, Any], Any]:result = self.custom_call_tool(str(item["tool_name"]),item["tool_arguments"],workspace_root=resolved_workspace_root,runtime_deadline=runtime_deadline,model_name=self.model,)return item, resultfor batch_indexes in tool_execution_batches([str(item["tool_name"]) for item in tool_call_items]):if remaining_runtime_seconds(runtime_deadline) is not None and remaining_runtime_seconds(runtime_deadline) <= 0:result_text = "No result found before the maximum agent runtime limit."termination = f"agent runtime limit reached: {agent_runtime_limit}s"return finalize(result_text, termination, error=termination)batch_items = [tool_call_items[index] for index in batch_indexes]try:should_run_parallel = len(batch_items) > 1 and all(can_parallelize_tool_name(str(item["tool_name"])) for item in batch_items)if should_run_parallel:max_workers = min(MAX_PARALLEL_READ_TOOL_CALLS, len(batch_items))with ThreadPoolExecutor(max_workers=max_workers) as executor:batch_results = list(executor.map(execute_tool_item, batch_items))else:batch_results = [execute_tool_item(item) for item in batch_items]except KeyboardInterrupt:messages = messages[:tool_turn_message_start]return finalize_interrupted()for item, result in batch_results:tool_call_id = str(item["tool_call_id"])tool_name = str(item["tool_name"])tool_arguments = item["tool_arguments"]tool_result_text = tool_result_message_content(result)messages.append(api_tool_message(tool_call_id, result))trace_writer.append(role="tool",text=tool_result_text,turn_index=round_index,tool_call_ids=[tool_call_id],tool_names=[tool_name],tool_arguments=[tool_arguments],)extra_image_context = image_context_message(result, self.model)if extra_image_context is not None:deferred_image_contexts.append((tool_call_id, tool_name, tool_arguments, result, extra_image_context))for tool_call_id, tool_name, tool_arguments, result, extra_image_context in deferred_image_contexts:messages.append(extra_image_context)trace_writer.append(
3 unmodified lines4567891050 unmodified lines616263646566676869707172737475767788 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119271 unmodified lines264265266267268269270271272273274275276198 unmodified lines4754764774784794804814824833 unmodified linesimport reimport sysimport timefrom concurrent.futures import ThreadPoolExecutorfrom typing import Optional, Unionimport requests50 unmodified linesclass WebSearch(ToolBase):name = "WebSearch"description = "Perform Google web searches and return the top results. Accepts multiple complementary queries."parameters = {"type": "object","properties": {"query": {"type": "array","items": {"type": "string",},"minItems": 1,"description": "Array of query strings. Include multiple complementary search queries in a single call.",},},"required": ["query"],88 unmodified linesexcept ValueError as exc:return f"[WebSearch] {exc}"if isinstance(query, list):with ThreadPoolExecutor(max_workers=3) as executor:responses = list(executor.map(self.search_with_serp, query))response = "\n=======\n".join(responses)else:return "[WebSearch] 'query' must be a list of strings."return responseclass ScholarSearch(ToolBase):name = "ScholarSearch"description = "Search academic sources through Google Scholar and return relevant publication results."parameters = {"type": "object","properties": {"query": {"type": "array","items": {"type": "string", "description": "The search query."},"minItems": 1,"description": "The list of search queries for Google Scholar.",},},"required": ["query"],71 unmodified linesexcept ValueError as exc:return f"[ScholarSearch] {exc}"if isinstance(query, list):with ThreadPoolExecutor(max_workers=3) as executor:response = list(executor.map(self.google_scholar_with_serp, query))response = "\n=======\n".join(response)else:return "[ScholarSearch] 'query' must be a list of strings."return responseclass WebFetch(ToolBase):198 unmodified linesload_dotenv(PROJECT_ROOT / ".env")if args.tool == "search":result = WebSearch().call({"query": [" ".join(args.query)]})elif args.tool == "scholar":result = ScholarSearch().call({"query": [" ".join(args.query)]})else:result = WebFetch().call({3 unmodified lines45678950 unmodified lines6061626364656667686970717288 unmodified lines16116216316416516616716816917017117217317417517617717817918018171 unmodified lines253254255256257258259260261198 unmodified lines4604614624634644654664674683 unmodified linesimport reimport sysimport timefrom typing import Optional, Unionimport requests50 unmodified linesclass WebSearch(ToolBase):name = "WebSearch"description = "Perform one Google web search and return the top results. Call WebSearch multiple times for multiple queries."parameters = {"type": "object","properties": {"query": {"type": "string","description": "The search query.",},},"required": ["query"],88 unmodified linesexcept ValueError as exc:return f"[WebSearch] {exc}"if not isinstance(query, str) or not query.strip():return "[WebSearch] 'query' must be a non-empty string."return self.search_with_serp(query.strip())class ScholarSearch(ToolBase):name = "ScholarSearch"description = "Run one academic search through Google Scholar and return relevant publication results. Call ScholarSearch multiple times for multiple queries."parameters = {"type": "object","properties": {"query": {"type": "string","description": "The search query for Google Scholar.",},},"required": ["query"],71 unmodified linesexcept ValueError as exc:return f"[ScholarSearch] {exc}"if not isinstance(query, str) or not query.strip():return "[ScholarSearch] 'query' must be a non-empty string."return self.google_scholar_with_serp(query.strip())class WebFetch(ToolBase):198 unmodified linesload_dotenv(PROJECT_ROOT / ".env")if args.tool == "search":result = WebSearch().call({"query": " ".join(args.query)})elif args.tool == "scholar":result = ScholarSearch().call({"query": " ".join(args.query)})else:result = WebFetch().call({
VERSION+1-1
agent_base/prompts/system_base.md+1
agent_base/react_agent.py+81-22
agent_base/tools/tool_web.py+14-29