SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Update tests for function_calling
carlosejimenez6cc305c8a057
diff --cc config/function_calling.yamlindex e05e130e,00000000..4344f698mode 100644,000000..100644--- a/config/function_calling.yaml+++ b/config/function_calling.yaml@@@ -1,97 -1,0 +1,97 @@@+agent:+ templates:+ system_template: |-+ SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.++ The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.+ In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.++ Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.+ If you'd like to add the line ' print(x)' you must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run.++ RESPONSE FORMAT:+ Your shell prompt is formatted as follows:+ (Open file: <path>) <cwd> $++ First, you should _always_ include a general thought about what you're going to do next.+ Then, for every response, you must include exactly _ONE_ command to execute.+ All of the tools you need to use are listed for your reference.++ Remember, you should only include a _SINGLE_ command in the command section and then wait for a response from the shell before continuing with more discussion and commands. Everything you include in the DISCUSSION section will be saved for future reference.+ If you'd like to issue two commands at once, PLEASE DO NOT DO THAT! Please instead first submit just the first command, and then after receiving a response you'll be able to issue the second command.+ You're free to use any other bash commands you want (e.g. find, grep, cat, ls, cd) in addition to the special commands listed above.+ However, the environment does NOT support interactive session commands (e.g. python, vim), so please do not invoke them.+ instance_template: |-+ We're currently solving the following issue within our repository. Here's the issue text:+ ISSUE:+ {problem_statement}++ INSTRUCTIONS:+ Now, you're going to solve this issue on your own. Your terminal session has started and you're in the repository's root directory. You can use any bash commands or the special interface to help you. Edit all the files you need to and run any checks or tests that you want.+ Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.+ When you're satisfied with all of the changes you've made, you can submit your changes to the code base by simply running the submit command.+ Note however that you cannot use any interactive session commands (e.g. python, vim) in this environment, but you can write scripts and run them. E.g. you can write a python script and then run it with `python <script_name>.py`.++ NOTE ABOUT THE EDIT COMMAND: Indentation really matters! When editing a file, make sure to insert appropriate indentation before each line!++ IMPORTANT TIPS:+ 1. Always start by trying to replicate the bug that the issues discusses.+ If the issue includes code for reproducing the bug, we recommend that you re-implement that in your environment, and run it to make sure you can reproduce the bug.+ Then start trying to fix it.+ When you think you've fixed the bug, re-run the bug reproduction script to make sure that the bug has indeed been fixed.++ If the bug reproduction script does not print anything when it successfully runs, we recommend adding a print("Script completed successfully, no errors.") command at the end of the file,+ so that you can be sure that the script indeed ran fine all the way through.++ 2. If you run a command and it doesn't work, try running a different command. A command that did not work once will not work the second time unless you modify it!++ 3. If you open a file and need to get to an area around a specific line that is not in the first 100 lines, say line 583, don't just use the scroll_down command multiple times. Instead, use the goto 583 command. It's much quicker.++ 4. If the bug reproduction script requires inputting/reading a specific file, such as buggy-input.png, and you'd like to understand how to input that file, conduct a search in the existing repo code, to see whether someone else has already done that. Do this by running the command: find_file "buggy-input.png" If that doesn't work, use the linux 'find' command.++ 5. Always make sure to look at the currently open file and the current working directory (which appears right after the currently open file). The currently open file might be in a different directory than the working directory! Note that some commands, such as 'create', open files, so they might change the current open file.++ 6. When editing files, it is easy to accidentally specify a wrong line number or to write code with incorrect indentation. Always check the code after you issue an edit to make sure that it reflects what you wanted to accomplish. If it didn't, issue another command to fix it.+++ (Open file: {open_file})+ (Current directory: {working_dir})+ bash-$+ next_step_template: |-+ {observation}+ (Open file: {open_file})+ (Current directory: {working_dir})+ bash-$+ next_step_no_output_template: |-+ Your command ran successfully and did not produce any output.+ (Open file: {open_file})+ (Current directory: {working_dir})+ bash-$+ # demonstration_template: |+ # Here is a demonstration of how to correctly accomplish this task.+ # It is included to show you how to correctly use the interface.+ # You do not need to follow exactly what is done in the demonstration.+ # --- DEMONSTRATION ---+ # {demonstration}+ # --- END OF DEMONSTRATION ---+ # demonstrations:+ # - trajectories/demonstrations/replay__marshmallow-code__marshmallow-1867__default_sys-env_window100__t-0.20__p-0.95__c-2.00__install-1/marshmallow-code__marshmallow-1867.traj+ tools:+ env_variables:+ WINDOW: 100+ OVERLAP: 2+ bundles:+ - tools/defaults+ - tools/search+ - tools/edit_linting+ - tools/submit+ - tools/state- include_bash_tool: true++ enable_bash_tool: true+ parse_command:+ type: detailed+ state_command: _state+ parse_function:+ type: function_calling+ history_processor:+ type: last_n_observations+ n: 5diff --cc sweagent/agent/agents.pyindex 8e29e61e,808e0936..e21a3379--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@@ -26,9 -28,12 +28,12 @@@ from sweagent.agent.models import)from sweagent.environment.config.problem_statement import ProblemStatement, ProblemStatementConfigfrom sweagent.environment.swe_env import SWEEnv- from sweagent.tools.parsing import FormatError+ from sweagent.tools.parsing import (+ FormatError,+ ThoughtActionParser,+ )from sweagent.tools.tools import ToolConfig, ToolHandler-from sweagent.types import AgentInfo, AgentRunResult, History, HistoryItem, StepOutput, Trajectory, TrajectoryStep+from sweagent.types import AgentInfo, AgentRunResult, History, StepOutput, Trajectory, TrajectoryStepfrom sweagent.utils.config import _convert_paths_to_abspathfrom sweagent.utils.log import get_loggerfrom sweagent.utils.patch_formatter import PatchFormatter@@@ -555,15 -545,16 +559,19 @@@ class Agenttry:# Forward model and get actionsself._chook.on_model_query(messages=history, agent=self.name)- output = self.model.query(history) # type: ignore- step.output = output+ output = self.model.query(history)+ step.output = output["message"]- if isinstance(self.model, HumanModel):+ if isinstance(self.model, HumanThoughtModel):+ # TODO: This might be a bit hacky+ # consider changing sweagent/tools/tools.py:ToolConfig to enforce this.+ step.thought, step.action = ThoughtActionParser()(output, self.tools.config.commands)+ elif isinstance(self.model, HumanModel):- step.thought, step.action = "", output+ step.thought, step.action = "", output["message"]else:step.thought, step.action = self.tools.parse_actions(output)- if output["tool_calls"]:++ if output.get("tool_calls", None) is not None:+ step.tool_call_ids = [call["id"] for call in output["tool_calls"]]+ step.tool_calls = output["tool_calls"]self.logger.info(f"💭 THOUGHT\n{step.thought}\n🎬 ACTION\n{step.action.strip()}")self._chook.on_actions_generated(step=step)return self.handle_action(step)@@@ -667,6 -658,6 +679,10 @@@"exit_error",f"Exit due to unknown error: {e}",)++ self.logger.exception(++ "Exit due to repeated format/blocklist/bash syntax errors",++ exc_info=True,++ )return handle_error_with_autosubmission("exit_format","Exit due to repeated format/blocklist/bash syntax errors",diff --cc sweagent/agent/hooks/abstract.pyindex 9eb57652,ca6db3d7..6e0c70ce--- a/sweagent/agent/hooks/abstract.py+++ b/sweagent/agent/hooks/abstract.py@@@ -109,12 -100,12 +111,19 @@@ class CombinedAgentHook(AbstractAgentHo):for hook in self.hooks:hook.on_query_message_added(- role=role, content=content, agent=agent, is_demo=is_demo, thought=thought, action=action+ agent=agent,+ role=role,+ content=content,+ is_demo=is_demo,+ thought=thought,+ action=action,+ tool_calls=tool_calls,+ tool_call_ids=tool_call_ids,)++ def on_setup_done(self):+ return super().on_setup_done()++ def on_tools_installation_started(self):+ for hook in self.hooks:+ hook.on_tools_installation_started()diff --cc sweagent/agent/models.pyindex d1590774,c5dd30aa..dab9cb9d--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@@ -142,21 -154,21 +154,21 @@@ class TotalCostLimitExceededError(CostLclass AbstractModel(ABC):- def __init__(self, config: PydanticBaseModel, commands: list[Command]):+ def __init__(self, config: PydanticBaseModel, tools: ToolConfig):self.config: PydanticBaseModel- self.stats: APIStats+ self.stats: InstanceStatsdef reset_stats(self):- self.stats = APIStats()+ self.stats = InstanceStats()@abstractmethod- def query(self, history: History, action_prompt: str = "> ") -> str: ...+ def query(self, history: History, action_prompt: str = "> ") -> dict: ...class HumanModel(AbstractModel):- def __init__(self, config: HumanModelConfig, commands: list[Command]):+ def __init__(self, config: HumanModelConfig, tools: ToolConfig):self.config = config- self.stats = APIStats()+ self.stats = InstanceStats()# Determine which commands require multi-line inputself.multi_line_command_endings = {@@@ -209,9 -221,9 +221,9 @@@ class HumanThoughtModel(HumanModel)class ReplayModel(AbstractModel):- def __init__(self, config: ReplayModelConfig, commands: list[Command]):+ def __init__(self, config: ReplayModelConfig, tools: ToolConfig):self.config = config- self.stats = APIStats()+ self.stats = InstanceStats()if not self.config.replay_path.exists():msg = f"Replay file {self.config.replay_path} not found"@@@ -256,9 -268,9 +268,9 @@@ class PredeterminedTestModel(AbstractModef __init__(self, outputs: list[str]):self._outputs = outputsself._idx = -1- self.stats = APIStats()+ self.stats = InstanceStats()- def query(self, *args, **kwargs) -> str:+ def query(self, *args, **kwargs) -> dict:self._idx += 1output = self._outputs[self._idx]if output == "raise_runtime":@@@ -271,12 -283,14 +283,15 @@@class InstantEmptySubmitTestModel(AbstractModel):- def __init__(self, args: InstantEmptySubmitModelConfig, commands: list[Command]):+ def __init__(self, args: InstantEmptySubmitModelConfig, tools: ToolConfig):"""This model immediately submits. Useful for testing purposes"""+ super().__init__(args, tools)+ self.config: InstantEmptySubmitModelConfig = args+ self.stats = InstanceStats()self._action_idx = 0- def query(self, history: list[dict[str, str]]) -> str:+ def query(self, history: list[dict[str, str]]) -> dict:+ time.sleep(random.uniform(0, self.config.delay))# Need to at least do _something_ to submitif self._action_idx == 0:self._action_idx = 1@@@ -289,18 -303,14 +304,19 @@@class LiteLLMModel(AbstractModel):- def __init__(self, args: ModelConfig, commands: list[Command]):+ def __init__(self, args: ModelConfig, tools: ToolConfig):self.args = args- self.commands = commands+ self.stats = InstanceStats()+ self.tools = tools- self.stats = APIStats()+ if tools.use_function_calling:+ assert litellm.supports_function_calling(+ model=self.args.name+ ), f"Model {self.args.name} does not support function calling"+ self.model_max_tokens = litellm.model_cost.get(self.args.name, {}).get("max_tokens")def _update_stats(self, *, input_tokens: int, output_tokens: int, cost: float) -> None:- self.stats.total_cost += cost+ with GLOBAL_STATS_LOCK:+ GLOBAL_STATS.total_cost += costself.stats.instance_cost += costself.stats.tokens_sent += input_tokensself.stats.tokens_received += output_tokens@@@ -331,42 -341,13 +347,12 @@@msg = "Instance cost limit exceeded"raise InstanceCostLimitExceededError(msg)- # def _query(self, messages: list[dict[str, str]]) -> dict:- # input_tokens: int = litellm.utils.token_counter(messages=messages, model=self.args.name)- # max_input_tokens: int | None = litellm.model_cost.get(self.args.name, {}).get("max_input_tokens")- # if max_input_tokens is None:- # logger.warning(f"No max input tokens found for model {self.args.name!r}")- # elif input_tokens > max_input_tokens:- # msg = f"Input tokens {input_tokens} exceed max tokens {max_input_tokens}"- # raise ContextWindowExceededError(msg)- # extra_args = {}- # if self.args.api_base:- # # Not assigned a default value in litellm, so only pass this if it's set- # extra_args["api_base"] = self.args.api_base- # response: litellm.types.utils.ModelResponse = litellm.completion( # type: ignore- # model=self.args.name,- # messages=messages,- # temperature=self.args.temperature,- # top_p=self.args.top_p,- # api_version=self.args.api_version,- # api_key=self.args.api_key.get_secret_value() if self.args.api_key else None,- # **self.args.completion_kwargs,- # **extra_args,- # )- # choices: litellm.types.utils.Choices = response.choices # type: ignore- # output = choices[0].message.content- # cost = litellm.cost_calculator.completion_cost(response)- # output_tokens = litellm.utils.token_counter(text=output, model=self.args.name)- # self._update_stats(input_tokens=input_tokens, output_tokens=output_tokens, cost=cost)-- # return {"message": output}-- def _query(self, messages: list[dict[str, str]]) -> str:+ def _query(self, messages: list[dict[str, str]]) -> dict:input_tokens: int = litellm.utils.token_counter(messages=messages, model=self.args.name)- max_input_tokens: int | None = litellm.model_cost.get(self.args.name, {}).get("max_input_tokens")- if max_input_tokens is None:+ if self.model_max_tokens is None:logger.warning(f"No max input tokens found for model {self.args.name!r}")- elif input_tokens > max_input_tokens:- msg = f"Input tokens {input_tokens} exceed max tokens {max_input_tokens}"+ elif input_tokens > self.model_max_tokens:+ msg = f"Input tokens {input_tokens} exceed max tokens {self.model_max_tokens}"raise ContextWindowExceededError(msg)extra_args = {}if self.args.api_base:diff --cc sweagent/tools/parsing.pyindex 85e148d0,6fd0586b..5c6dafbe--- a/sweagent/tools/parsing.py+++ b/sweagent/tools/parsing.py@@@ -218,65 -214,7 +218,66 @@@ class Identity(AbstractParseFunction, B"""This doesn't do any parsing. It just returns the model response as the thought and action."""- return model_response, model_response+ return model_response["message"], model_response["message"]+++class FunctionCallingParser(AbstractParseFunction, BaseModel):+ """Expects the model response to be a LiteLLM tool call."""++ error_message: str = """\+ Your output could not be parsed as a tool call.+ Please make sure your output includes a thought and exactly _ONE_ tool call.++ Make sure your tool call doesn't include any extra arguments that are not in the allowed arguments, and only use the allowed commands.+ """++ type: Literal["function_calling"] = "function_calling"+ """Type for (de)serialization. Do not change."""++ def _parse_tool_call(self, tool_call: dict, commands: list[Command]):+ name = tool_call["function"]["name"]+ command = {c.name: c for c in commands}.get(name)+ if not command:+ msg = f"Command '{name}' not found in list of available commands."+ raise FormatError(msg)+ try:+ values = json.loads(tool_call["function"]["arguments"])+ except json.JSONDecodeError:+ msg = "Tool call arguments are not valid JSON."+ raise FormatError(msg)+ required_args = {arg.name for arg in command.arguments if arg.required}+ missing_args = required_args - values.keys()+ if missing_args:+ msg = f"Required argument(s) missing: {', '.join(missing_args)}"+ raise FormatError(msg)+ valid_args = {arg.name for arg in command.arguments}+ extra_args = set(values.keys()) - valid_args+ if command.end_name:+ # sometimes the model will include the end_name in the arguments - just ignore it+ extra_args.discard(command.end_name)+ if extra_args:+ msg = f"Unexpected argument(s): {', '.join(extra_args)}"+ raise FormatError(msg)+ formatted_args = {+ arg.name: arg.argument_format.format(+ value=quote(values[arg.name]) if _should_quote(values[arg.name], command) else values[arg.name]+ )+ if arg.name in values+ else ""+ for arg in command.arguments+ }+ return command.invoke_format.format(**formatted_args).strip()++ def __call__(self, model_response: dict, commands: list[Command], strict=False):+ message = model_response["message"]- tool_calls = model_response["tool_calls"]++ tool_calls = model_response.get("tool_calls", None)+ if tool_calls is None or len(tool_calls) != 1:- msg = f"Expected exactly one tool call in model response - received {len(tool_calls)} tool calls."++ num_tools = len(tool_calls) if tool_calls else 0++ msg = f"Expected exactly one tool call in model response - received {num_tools} tool calls."+ raise FormatError(msg)+ tool_call = tool_calls[0]+ action = self._parse_tool_call(tool_call, commands)+ return message, actionclass JsonParser(AbstractParseFunction, BaseModel):@@@ -333,24 -271,30 +334,32 @@@raise FormatError(msg)thought = data["thought"]---- # Generate actioncommands_dict = {c.name: c for c in commands}command = commands_dict.get(data_command["name"])++++ # Handle command parsing based on strict modeif command is None:- action = " ".join([data_command["name"], *data_command["arguments"].values()])- action = data_command["name"]- if "arguments" in data_command:- action += " " + " ".join(data_command["arguments"].values())- else:- signature = command.signature- assert signature is not None- signature = signature.replace("[", "").replace("]", "").replace("<", "{").replace(">", "}")- signature_args = _extract_keys(signature)- command_args = {k: "" for k in signature_args}-- if "arguments" in data_command:- for arg in signature_args:- if arg in data_command["arguments"]:- value = data_command["arguments"][arg]- if _should_quote(value, command):- value = shlex.quote(value)- command_args[arg] = value- action = signature.format(**command_args)- action = action.strip()++ if strict:++ msg = f"Command '{data_command['name']}' not found in list of available commands."++ raise FormatError(msg)++ # In non-strict mode, just join command name with argument values++ return thought, " ".join([data_command["name"], *data_command.get("arguments", {}).values()])++ # Format arguments using their individual argument_format+ formatted_args = {}+ if command.arguments:+ for arg in command.arguments:+ if arg.name in data_command.get("arguments", {}):+ value = data_command["arguments"][arg.name]+ if _should_quote(value, command):+ value = quote(value)+ formatted_args[arg.name] = arg.argument_format.format(value=value)++ elif strict and arg.required:++ msg = f"Required argument '{arg.name}' missing for command '{command.name}'"++ raise FormatError(msg)+++ # Use the formatted arguments with invoke_format+ action = command.invoke_format.format(**formatted_args).strip()return thought, actionexcept json.JSONDecodeError:msg = "Model output is not valid JSON."diff --cc sweagent/tools/tools.pyindex 937d3094,4fe5788b..7fcc8f1b--- a/sweagent/tools/tools.py+++ b/sweagent/tools/tools.py@@@ -9,10 -9,11 +9,11 @@@ import yamfrom pydantic import BaseModel, Fieldfrom swerex.runtime.abstract import Command as RexCommandfrom swerex.runtime.abstract import UploadRequest+ from typing_extensions import Selffrom sweagent.environment.swe_env import SWEEnv-from sweagent.tools.commands import Command, ParseCommand, ParseCommandBash-from sweagent.tools.parsing import ParseFunction, ThoughtActionParser+from sweagent.tools.commands import BASH_COMMAND, Command, ParseCommand, ParseCommandBash+from sweagent.tools.parsing import FunctionCallingParser, JsonParser, ParseFunctionfrom sweagent.tools.utils import _guard_multiline_inputfrom sweagent.utils.log import get_logger@@@ -61,11 -63,9 +63,11 @@@ class ToolConfig(BaseModel)submit_command: str = "submit"- parse_function: ParseFunction | None = Field(default=None)- parse_function: ParseFunction = Field(default_factory=ThoughtActionParser)++ parse_function: ParseFunction = Field(default_factory=FunctionCallingParser)parse_command: ParseCommand = Field(default_factory=ParseCommandBash)- include_bash_tool: bool = True++ enable_bash_tool: bool = True+format_error_template: str = None # type: ignore"""Defaults to format_error_template in ParseFunction"""@@@ -114,14 -110,8 +116,14 @@@raise ValueError(msg)commands.append(Command(name=tool, **tool_config))tool_sources[tool] = path- if self.include_bash_tool:++ if self.enable_bash_tool:+ commands.append(BASH_COMMAND)return commands+ @cached_property+ def tools(self) -> list[dict]:+ return [command.get_function_calling_tool() for command in self.commands]+# todo: can some of these be moved to ToolHandler?def model_post_init(self, __context):# for caching:@@@ -129,15 -119,7 +131,15 @@@multi_line_command_endings = {command.name: command.end_name for command in commands if command.end_name is not None}+ self.tools+- # assert not self.include_bash_tool and parse_function is not FunctionCallingParser- if self.include_bash_tool and not (++ # assert not self.enable_bash_tool and parse_function is FunctionCallingParser or JsonParser++ if not self.enable_bash_tool and not (+ isinstance(self.parse_function, FunctionCallingParser) or isinstance(self.parse_function, JsonParser)+ ):- msg = "Bash tool can only be used with function calling parser or JSON parser."++ msg = f"Bash tool can only be disabled if {FunctionCallingParser.type} parser or {JsonParser.type} parser is used."+ raise ValueError(msg)+self.multi_line_command_endings = multi_line_command_endingsself.command_docs = self.parse_command.generate_command_docs(self.commands,diff --cc tests/test_agent.pyindex d1eca447,d1eca447..07337f0f--- a/tests/test_agent.py+++ b/tests/test_agent.py@@@ -9,6 -9,6 +9,8 @@@ from sweagent.agent.agents import Agentfrom sweagent.agent.models import InstantEmptySubmitModelConfig, PredeterminedTestModelfrom sweagent.environment.config.problem_statement import EmptyProblemStatement, TextProblemStatementfrom sweagent.environment.swe_env import SWEEnv++from sweagent.tools.parsing import FunctionCallingParser, Identity, ThoughtActionParser++from sweagent.tools.tools import ToolConfigdef test_dummy_env(dummy_env):@@@ -16,8 -16,8 +18,33 @@@@pytest.fixture--def agent_config():-- return AgentConfig(model=InstantEmptySubmitModelConfig())++def identity_agent_config():++ return AgentConfig(++ model=InstantEmptySubmitModelConfig(),++ tools=ToolConfig(++ parse_function=Identity(),++ ),++ )++++++def thought_action_agent_config():++ return AgentConfig(++ model=InstantEmptySubmitModelConfig(),++ tools=ToolConfig(++ parse_function=ThoughtActionParser(),++ ),++ )++++++def function_calling_agent_config():++ return AgentConfig(++ model=InstantEmptySubmitModelConfig(),++ tools=ToolConfig(++ parse_function=FunctionCallingParser(),++ ),++ )@pytest.fixture@@@ -36,8 -36,8 +63,13 @@@ def default_agent(default_agent_config@pytest.fixture--def test_agent(agent_config: AgentConfig) -> Agent:-- return Agent.from_config(agent_config)++def test_agent(identity_agent_config: AgentConfig) -> Agent:++ return Agent.from_config(identity_agent_config)++++++def thought_action_agent(thought_action_agent_config: AgentConfig) -> Agent:++ return Agent.from_config(thought_action_agent_config)def test_exit_cost(dummy_env: SWEEnv, test_agent: Agent, tmp_path):@@@ -70,9 -70,9 +102,9 @@@ def test_exit_model_error(dummy_env: SWassert r.info["exit_status"] == "exit_environment_error" # type: ignore--def test_exit_format(dummy_env: SWEEnv, test_agent: Agent, tmp_path):-- test_agent.model = PredeterminedTestModel(["a", "b", "c", "d"]) # type: ignore-- r = test_agent.run(++def test_exit_format(dummy_env: SWEEnv, thought_action_agent: Agent, tmp_path):++ thought_action_agent.model = PredeterminedTestModel(["a", "b", "c", "d"]) # type: ignore++ r = thought_action_agent.run(problem_statement=EmptyProblemStatement(),env=dummy_env,output_dir=tmp_path,@@@ -81,7 -81,7 +113,7 @@@def test_exit_blocklist(dummy_env: SWEEnv, test_agent: Agent, tmp_path):-- test_agent.model = PredeterminedTestModel(["```\nvim\n```", "```\npython\n```", "```\nsu\n```", "```\nnano\n```"]) # type: ignore++ test_agent.model = PredeterminedTestModel(["vim", "python", "su", "nano"]) # type: ignorer = test_agent.run(problem_statement=EmptyProblemStatement(),env=dummy_env,@@@ -98,7 -98,7 +130,7 @@@ class RuntimeRaisesFirst(DummyRuntime)def test_early_exit(dummy_env: SWEEnv, test_agent: Agent, tmp_path):-- test_agent.model = PredeterminedTestModel(["```\nraise\n```"]) # type: ignore++ test_agent.model = PredeterminedTestModel(["raise"]) # type: ignoretest_agent._catch_errors = Truedummy_env.deployment.runtime = RuntimeRaisesFirst() # type: ignorer = test_agent.run(diff --cc tests/test_models.pyindex 9f2cb595,9f2cb595..6b1f20b7--- a/tests/test_models.py+++ b/tests/test_models.py@@@ -3,6 -3,6 +3,8 @@@ from __future__ import annotationfrom pydantic import SecretStrfrom sweagent.agent.models import GenericAPIModelConfig, get_model++from sweagent.tools.parsing import Identity++from sweagent.tools.tools import ToolConfigfrom sweagent.types import History@@@ -12,6 -12,6 +14,9 @@@ def test_litellm_mock()name="anthropic/o1-preview",completion_kwargs={"mock_response": "Hello, world!"},api_key=SecretStr("dummy_key"),-- )++ ),++ ToolConfig(++ parse_function=Identity(),++ ),)-- assert model.query(History([{"role": "user", "content": "Hello, world!"}])) == "Hello, world!"++ assert model.query(History([{"role": "user", "content": "Hello, world!"}])) == {"message": "Hello, world!"}diff --cc tests/test_parsing.pyindex 4833d3ee,4833d3ee..9ddf4328--- a/tests/test_parsing.py+++ b/tests/test_parsing.py@@@ -7,6 -7,6 +7,7 @@@ from sweagent.tools.parsing importActionParser,EditFormat,FormatError,++ FunctionCallingParser,Identity,JsonParser,ThoughtActionParser,@@@ -16,48 -16,48 +17,48 @@@def test_action_parser():parser = ActionParser()-- command = Command(code="ls", name="ls")-- thought, action = parser("ls -l", [command])++ command = Command(name="ls", docstring="")++ thought, action = parser({"message": "ls -l"}, [command])assert thought == "ls -l"assert action == "ls -l"with pytest.raises(FormatError):-- parser("invalid command", [command])++ parser({"message": "invalid command"}, [command])def test_thought_action_parser():parser = ThoughtActionParser()model_response = "Let's look at the files in the current directory.\n```\nls -l\n```"-- thought, action = parser(model_response, [])++ thought, action = parser({"message": model_response}, [])assert thought == "Let's look at the files in the current directory.\n"assert action == "ls -l\n"with pytest.raises(FormatError):-- parser("No code block", [])++ parser({"message": "No code block"}, [])def test_xml_thought_action_parser():parser = XMLThoughtActionParser()model_response = "Let's look at the files in the current directory.\n<command>\nls -l\n</command>"-- thought, action = parser(model_response, [])++ thought, action = parser({"message": model_response}, [])assert thought == "Let's look at the files in the current directory."assert action == "ls -l"with pytest.raises(FormatError):-- parser("No command tags", [])++ parser({"message": "No command tags"}, [])def test_edit_format_parser():parser = EditFormat()model_response = "Let's replace the contents.\n```\nimport os\nos.listdir()\n```"-- thought, action = parser(model_response, [])++ thought, action = parser({"message": model_response}, [])assert thought == "Let's replace the contents.\n"assert action == "import os\nos.listdir()\n"with pytest.raises(FormatError):-- parser("No code block", [])++ parser({"message": "No code block"}, [])def test_identity_parser():parser = Identity()model_response = "Return as is"-- thought, action = parser(model_response, [])++ thought, action = parser({"message": model_response}, [])assert thought == model_responseassert action == model_response@@@ -65,14 -65,14 +66,59 @@@def test_json_parser():parser = JsonParser()model_response = '{"thought": "List files", "command": {"name": "ls", "arguments": {"path": "."}}}'-- thought, action = parser(model_response, [])++ thought, action = parser({"message": model_response}, [])assert thought == "List files"assert action == "ls ."invalid_json = "Not a JSON"with pytest.raises(FormatError):-- parser(invalid_json, [])++ parser({"message": invalid_json}, [])missing_keys = '{"thought": "Missing command key"}'with pytest.raises(FormatError):-- parser(missing_keys, [])++ parser({"message": missing_keys}, [])++++++def test_function_calling_parser():++ parser = FunctionCallingParser()++ command = Command(name="ls", docstring="", arguments=[])++++ # Test successful parsing++ model_response = {++ "message": "Let's list the files",++ "tool_calls": [{"function": {"name": "ls", "arguments": "{}"}}],++ }++ thought, action = parser(model_response, [command])++ assert thought == "Let's list the files"++ assert action == "ls"++++ # Test with missing tool_calls++ with pytest.raises(FormatError):++ parser({"message": "No tool calls"}, [command])++++ # Test with multiple tool calls++ multiple_calls = {++ "message": "Multiple calls",++ "tool_calls": [++ {"function": {"name": "ls", "arguments": "{}"}},++ {"function": {"name": "cd", "arguments": "{}"}},++ ],++ }++ with pytest.raises(FormatError):++ parser(multiple_calls, [command])++++ # Test with invalid command++ invalid_command = {++ "message": "Invalid command",++ "tool_calls": [{"function": {"name": "invalid", "arguments": "{}"}}],++ }++ with pytest.raises(FormatError):++ parser(invalid_command, [command])++++ # Test with invalid JSON arguments++ invalid_json = {++ "message": "Invalid JSON",++ "tool_calls": [{"function": {"name": "ls", "arguments": "invalid json"}}],++ }++ with pytest.raises(FormatError):++ parser(invalid_json, [command])