A programming framework for agentic AI
Catch json decode error in file surfer (#352)
gagb698a8f374b62
diff --git a/python/teams/team-one/src/team_one/agents/file_surfer/_tools.py b/python/teams/team-one/src/team_one/agents/file_surfer/_tools.pyindex d2dafe5cb..f62d08eb0 100644--- a/python/teams/team-one/src/team_one/agents/file_surfer/_tools.py+++ b/python/teams/team-one/src/team_one/agents/file_surfer/_tools.py@@ -48,67 +48,3 @@ TOOL_FIND_NEXT = ToolSchema(name="find_next",description="Scroll the viewport to next occurrence of the search string.",)--# TOOL_OPEN_LOCAL_FILE = {-# "type": "function",-# "function": {-# "name": "open_local_file",-# "description": "Open a local file at a path in the text-based browser and return current viewport content.",-# "parameters": {-# "type": "object",-# "properties": {-# "path": {-# "type": "string",-# "description": "The relative or absolute path of a local file to visit.",-# },-# },-# "required": ["path"],-# },-# },-# }---# TOOL_PAGE_UP = {-# "type": "function",-# "function": {-# "name": "page_up",-# "description": "Scroll the viewport UP one page-length in the current file and return the new viewport content.",-# },-# }---# TOOL_PAGE_DOWN = {-# "type": "function",-# "function": {-# "name": "page_down",-# "description": "Scroll the viewport DOWN one page-length in the current file and return the new viewport content.",-# },-# }---# TOOL_FIND_ON_PAGE_CTRL_F = {-# "type": "function",-# "function": {-# "name": "find_on_page_ctrl_f",-# "description": "Scroll the viewport to the first occurrence of the search string. This is equivalent to Ctrl+F.",-# "parameters": {-# "type": "object",-# "properties": {-# "search_string": {-# "type": "string",-# "description": "The string to search for on the page. This search string supports wildcards like '*'",-# },-# },-# "required": ["search_string"],-# },-# },-# }---# TOOL_FIND_NEXT = {-# "type": "function",-# "function": {-# "name": "find_next",-# "description": "Scroll the viewport to next occurrence of the search string.",-# },-# }diff --git a/python/teams/team-one/src/team_one/agents/file_surfer/file_surfer.py b/python/teams/team-one/src/team_one/agents/file_surfer/file_surfer.pyindex 622893466..bd85cf7a6 100644--- a/python/teams/team-one/src/team_one/agents/file_surfer/file_surfer.py+++ b/python/teams/team-one/src/team_one/agents/file_surfer/file_surfer.py@@ -8,8 +8,6 @@ from agnext.components.models import (SystemMessage,UserMessage,)--# from agnext.components.tools import FunctionToolfrom agnext.core import CancellationTokenfrom ...markdown_browser import RequestsMarkdownBrowser@@ -18,36 +16,6 @@ from ..base_worker import BaseWorker# from typing_extensions import Annotatedfrom ._tools import TOOL_FIND_NEXT, TOOL_FIND_ON_PAGE_CTRL_F, TOOL_OPEN_LOCAL_FILE, TOOL_PAGE_DOWN, TOOL_PAGE_UP-# async def read_local_file(file_path: Annotated[str, "relative or absolute path of file to read"]) -> str:-# """Read contents of a file."""-# try:-# async with aiofiles.open(file_path, mode="r") as file:-# file_contents = str(await file.read())-# return f"""-# Here are the contents of the file at path: {file_path}-# ```-# {file_contents}-# ```-# """--# except FileNotFoundError:-# return f"File not found: {file_path}"---# def list_files_and_dirs_like_tree(dir_path: str) -> str:-# """List files and directories in a directory in a format similar to 'tree' command with level 1."""-# path = Path(dir_path)-# if not path.is_dir():-# return f"{dir_path} is not a valid directory."--# items = [f"{dir_path}"]-# for item in path.iterdir():-# if item.is_dir():-# items.append(f"├── {item.name}/") # Indicate directories with a trailing slash-# else:-# items.append(f"├── {item.name}") # List files as is-# return "\n".join(items)-class FileSurfer(BaseWorker):"""An agent that uses tools to read and navigate local files."""@@ -72,18 +40,6 @@ class FileSurfer(BaseWorker):self._system_messages = system_messagesself._browser = browserself._tools = [TOOL_OPEN_LOCAL_FILE, TOOL_PAGE_UP, TOOL_PAGE_DOWN, TOOL_FIND_ON_PAGE_CTRL_F, TOOL_FIND_NEXT]- # self._tools = [- # FunctionTool(- # read_local_file,- # description="Use this function to read the contents of a local file whose relative or absolute path is given.",- # name="read_local_file",- # ),- # FunctionTool(- # list_files_and_dirs_like_tree,- # description="List files and directories in a directory in a format similar to 'tree' command with level 1",- # name="list_files_and_dirs_like_tree",- # ),- # ]def _get_browser_state(self) -> Tuple[str, str]:"""@@ -110,49 +66,6 @@ class FileSurfer(BaseWorker):return (header, self._browser.viewport)- # async def _generate_reply(self, cancellation_token: CancellationToken) -> Tuple[bool, UserContent]:-- # if self._browser is None:- # self._browse = RequestsMarkdownBrowser(viewport_size=1024 * 5, downloads_folder="coding")-- # response = await self._model_client.create(self._system_messages + self._chat_history, tools=self._tools)-- # if isinstance(response.content, str):- # final_result = response.content-- # elif isinstance(response.content, list) and all(isinstance(item, FunctionCall) for item in response.content):- # results = await asyncio.gather(*[self.send_message(call, self.id) for call in response.content])- # for result in results:- # assert isinstance(result, FunctionExecutionResult)- # final_result = "\n".join(result.content for result in results)- # else:- # raise ValueError(f"Unexpected response type: {response.content}")-- # assert isinstance(final_result, str)-- # return "TERMINATE" in final_result, final_result-- # @message_handler- # async def handle_tool_call(- # self, message: FunctionCall, cancellation_token: CancellationToken- # ) -> FunctionExecutionResult:- # """Handle a tool execution task. This method executes the tool and publishes the result."""- # function_call = message- # # Find the tool- # tool = next((tool for tool in self._tools if tool.name == function_call.name), None)- # if tool is None:- # result_as_str = f"Error: Tool not found: {function_call.name}"- # else:- # try:- # arguments = json.loads(function_call.arguments)- # result = await tool.run_json(args=arguments, cancellation_token=cancellation_token)- # result_as_str = tool.return_value_as_string(result)- # except json.JSONDecodeError:- # result_as_str = f"Error: Invalid arguments: {function_call.arguments}"- # except Exception as e:- # result_as_str = f"Error: {e}"- # return FunctionExecutionResult(content=result_as_str, call_id=function_call.id)-async def _generate_reply(self, cancellation_token: CancellationToken) -> Tuple[bool, str]:if self._browser is None:self._browser = RequestsMarkdownBrowser(viewport_size=1024 * 5, downloads_folder="coding")@@ -164,7 +77,6 @@ class FileSurfer(BaseWorker):task_content = last_message.content # the last message from the sender is the taskassert self._browser is not None- # assert self._browser.page_title is not Nonecontext_message = UserMessage(source="user",@@ -189,7 +101,12 @@ class FileSurfer(BaseWorker):function_calls = responsefor function_call in function_calls:tool_name = function_call.name- arguments = json.loads(function_call.arguments)++ try:+ arguments = json.loads(function_call.arguments)+ except json.JSONDecodeError as e:+ error_str = f"File surfer encountered an error decoding JSON arguments: {e}"+ return False, error_strif tool_name == "open_local_file":path = arguments["path"]