Skip to content

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]

add function_calling parser

carlosejimenez4204a48dfaa4
diff --git a/config/function_calling.yaml b/config/function_calling.yaml
new file mode 100644
index 00000000..e05e130e
--- /dev/null
+++ b/config/function_calling.yaml
@@ -0,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
+ parse_command:
+ type: detailed
+ state_command: _state
+ parse_function:
+ type: function_calling
+ history_processor:
+ type: last_n_observations
+ n: 5
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 5b4bdfe3..8e29e61e 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -28,7 +28,7 @@ from sweagent.environment.config.problem_statement import ProblemStatement, Prob
from sweagent.environment.swe_env import SWEEnv
from sweagent.tools.parsing import FormatError
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, TrajectoryStep
from sweagent.utils.config import _convert_paths_to_abspath
from sweagent.utils.log import get_logger
from sweagent.utils.patch_formatter import PatchFormatter
@@ -148,10 +148,10 @@ class Agent:
@classmethod
def from_config(cls, config: AgentConfig) -> Self:
- model = get_model(config.model)
+ model = get_model(config.model, config.tools)
return cls(
templates=config.templates,
- tools=ToolHandler.from_config(config.tools),
+ tools=ToolHandler(config.tools),
history_processor=config.history_processor,
model=model,
max_requeries=config.max_requeries,
@@ -205,7 +205,7 @@ class Agent:
# Methods
# -------
- def _append_history(self, item: HistoryItem) -> None:
+ def _append_history(self, item: dict[str, Any]) -> None:
"""Adds an item to the history."""
self._chook.on_query_message_added(**item)
self.history.append(item)
@@ -265,7 +265,7 @@ class Agent:
problem_statement=self._problem_statement.get_problem_statement(),
)
self.logger.info(f"SYSTEM ({self.name})\n{system_msg}")
- self._append_history(HistoryItem({"role": "system", "content": system_msg, "agent": self.name}))
+ self._append_history({"role": "system", "content": system_msg, "agent": self.name})
def add_demonstrations_to_history(self) -> None:
"""Add demonstrations to history"""
@@ -286,6 +286,7 @@ class Agent:
if self.templates.demonstration_template is not None:
self.logger.warning("Demonstration template is ignored for put_demos_in_history=True")
# Add demonstration to history directly as separate messages
+ # TODO: check that this still works with function calling
for entry in demo_history:
if entry["role"] != "system":
entry["is_demo"] = True
@@ -316,12 +317,15 @@ class Agent:
problem_statement=self._problem_statement.get_problem_statement(),
)
- def _add_templated_messages_to_history(self, templates: list[str], **kwargs: str) -> None:
+ def _add_templated_messages_to_history(
+ self, templates: list[str], tool_call_ids: list[str] | None = None, **kwargs: str
+ ) -> None:
"""Populate selected template(s) with information (e.g., issue, arguments, state)
and add to history.
Args:
templates: templates to populate and add to history
+ tool_call_ids: tool call ids to be added to the history
**kwargs: keyword arguments to be passed to the templates (in addition to the
ones in `self._get_format_dict`)
"""
@@ -338,7 +342,12 @@ class Agent:
message = "\n".join(messages)
self.logger.info(f"🤖 MODEL INPUT\n{message}")
- self._append_history({"role": "user", "content": message, "agent": self.name})
+ history_item = {"role": "user", "content": message, "agent": self.name}
+ if tool_call_ids:
+ assert len(tool_call_ids) == 1, "This should be ensured by the FunctionCalling parse method"
+ history_item["role"] = "tool"
+ history_item["tool_call_ids"] = tool_call_ids
+ self._append_history(history_item)
def add_step_to_history(self, step: StepOutput) -> None:
"""Adds a step (command that was run and output) to the model history"""
@@ -349,6 +358,7 @@ class Agent:
"thought": step.thought,
"action": step.action,
"agent": self.name,
+ "tool_calls": step.tool_calls,
},
)
@@ -358,8 +368,12 @@ class Agent:
else:
# Show standard output template if there is observation content
templates = [self.templates.next_step_template]
-
- self._add_templated_messages_to_history(templates, observation=step.observation, **step.state)
+ self._add_templated_messages_to_history(
+ templates,
+ observation=step.observation,
+ tool_call_ids=step.tool_call_ids,
+ **step.state,
+ )
def add_instance_template_to_history(self, state: dict[str, str]) -> None:
"""Add observation to history, as well as the instance template or demonstrations if we're
@@ -541,12 +555,15 @@ class Agent:
try:
# Forward model and get actions
self._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):
- 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"]:
+ 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)
@@ -627,21 +644,25 @@ class Agent:
"Exit due to cost limit",
)
except RetryError as e:
+ self.logger.exception(f"Exiting due to retry error: {e}", exc_info=True)
return handle_error_with_autosubmission(
"exit_api",
f"Exit due to retry error: {e}",
)
except SweRexception as e:
+ self.logger.exception(f"Exiting due to environment error: {e}", exc_info=True)
return handle_error_with_autosubmission(
"exit_environment_error",
f"Exit due to environment error: {e}",
)
except RuntimeError as e:
+ self.logger.exception(f"Exiting due to runtime error: {e}", exc_info=True)
return handle_error_with_autosubmission(
"exit_error",
f"Exit due to runtime error: {e}",
)
except Exception as e:
+ self.logger.exception(f"Exiting due to unknown error: {e}", exc_info=True)
return handle_error_with_autosubmission(
"exit_error",
f"Exit due to unknown error: {e}",
diff --git a/sweagent/agent/hooks/abstract.py b/sweagent/agent/hooks/abstract.py
index 8b1f9f13..9eb57652 100644
--- a/sweagent/agent/hooks/abstract.py
+++ b/sweagent/agent/hooks/abstract.py
@@ -35,12 +35,14 @@ class AbstractAgentHook:
def on_query_message_added(
self,
*,
+ agent: str,
role: str,
content: str,
- agent: str,
is_demo: bool = False,
thought: str = "",
action: str = "",
+ tool_calls: list[dict[str, str]] | None = None,
+ tool_call_ids: list[str] | None = None,
): ...
def on_setup_done(self): ...
@@ -94,9 +96,25 @@ class CombinedAgentHook(AbstractAgentHook):
hook.on_model_query(messages=messages, agent=agent)
def on_query_message_added(
- self, *, role: str, content: str, agent: str, is_demo: bool = False, thought: str = "", action: str = ""
+ self,
+ *,
+ agent: str,
+ role: str,
+ content: str,
+ is_demo: bool = False,
+ thought: str = "",
+ action: str = "",
+ tool_calls: list[dict[str, str]] | None = None,
+ tool_call_ids: list[str] | None = None,
):
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,
)
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 1a65053c..d1590774 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -17,7 +17,7 @@ from tenacity import (
wait_random_exponential,
)
-from sweagent.tools.commands import Command
+from sweagent.tools.tools import ToolConfig
from sweagent.types import History, HistoryItem
from sweagent.utils.log import get_logger
@@ -142,7 +142,7 @@ class TotalCostLimitExceededError(CostLimitExceededError):
class AbstractModel(ABC):
- def __init__(self, config: PydanticBaseModel, commands: list[Command]):
+ def __init__(self, config: PydanticBaseModel, tools: ToolConfig):
self.config: PydanticBaseModel
self.stats: APIStats
@@ -150,20 +150,20 @@ class AbstractModel(ABC):
self.stats = APIStats()
@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()
# Determine which commands require multi-line input
self.multi_line_command_endings = {
- command.name: command.end_name for command in commands if command.end_name is not None
+ command.name: command.end_name for command in tools.commands if command.end_name is not None
}
- def query(self, history: History, action_prompt: str = "> ") -> str:
+ def query(self, history: History, action_prompt: str = "> ") -> dict:
"""Logic for handling user input to pass to SWEEnv"""
action = input(action_prompt)
command_name = action.split()[0] if action.strip() else ""
@@ -187,11 +187,11 @@ class HumanModel(AbstractModel):
break
buffer.append(action)
action = "\n".join(buffer)
- return action
+ return {"message": action}
class HumanThoughtModel(HumanModel):
- def query(self, history: History) -> str:
+ def query(self, history: History) -> dict:
"""Logic for handling user input (both thought + action) to pass to SWEEnv"""
thought_all = ""
thought = input("Thought (end w/ END_THOUGHT): ")
@@ -205,11 +205,11 @@ class HumanThoughtModel(HumanModel):
action = super().query(history, action_prompt="Action: ")
- return f"{thought_all}\n```\n{action}\n```"
+ return {"message": f"{thought_all}\n```\n{action}\n```"}
class ReplayModel(AbstractModel):
- def __init__(self, config: ReplayModelConfig, commands: list[Command]):
+ def __init__(self, config: ReplayModelConfig, tools: ToolConfig):
self.config = config
self.stats = APIStats()
@@ -228,7 +228,7 @@ class ReplayModel(AbstractModel):
self._replay_idx += 1
self._action_idx = 0
- def query(self, history: History) -> str:
+ def query(self, history: History) -> dict:
"""Logic for tracking which replay action to pass to SWEEnv"""
self.stats.api_calls += 1
actions = self._replays[self._replay_idx]
@@ -249,7 +249,7 @@ class ReplayModel(AbstractModel):
if action == "submit":
self._next_replay()
- return action
+ return {"message": action}
class PredeterminedTestModel(AbstractModel):
@@ -258,7 +258,7 @@ class PredeterminedTestModel(AbstractModel):
self._idx = -1
self.stats = APIStats()
- def query(self, *args, **kwargs) -> str:
+ def query(self, *args, **kwargs) -> dict:
self._idx += 1
output = self._outputs[self._idx]
if output == "raise_runtime":
@@ -267,16 +267,16 @@ class PredeterminedTestModel(AbstractModel):
raise CostLimitExceededError()
elif output == "raise_context":
raise ContextWindowExceededError()
- return output
+ return {"message": output}
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, commands)
+ super().__init__(args, tools)
self._action_idx = 0
- def query(self, history: list[dict[str, str]]) -> str:
+ def query(self, history: list[dict[str, str]]) -> dict:
# Need to at least do _something_ to submit
if self._action_idx == 0:
self._action_idx = 1
@@ -285,14 +285,19 @@ class InstantEmptySubmitTestModel(AbstractModel):
self._action_idx = 0
action = "DISCUSSION\nThe task should be resolved, so let's submit the patch.\n\n```\nsubmit\n```\n"
self.stats.api_calls += 1
- return action
+ return {"message": action}
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.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
@@ -326,18 +331,51 @@ class LiteLLMModel(AbstractModel):
msg = "Instance cost limit exceeded"
raise InstanceCostLimitExceededError(msg)
- 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:
+ # 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]]) -> 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:
# Not assigned a default value in litellm, so only pass this if it's set
extra_args["api_base"] = self.args.api_base
+ if self.tools.use_function_calling:
+ extra_args["tools"] = self.tools.tools
+ # We need to always set max_tokens for anthropic models
+ completion_kwargs = {**self.args.completion_kwargs, "max_tokens": self.model_max_tokens}
response: litellm.types.utils.ModelResponse = litellm.completion( # type: ignore
model=self.args.name,
messages=messages,
@@ -345,18 +383,24 @@ class LiteLLMModel(AbstractModel):
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,
+ **completion_kwargs,
**extra_args,
)
choices: litellm.types.utils.Choices = response.choices # type: ignore
- output = choices[0].message.content
+ output = choices[0].message.content or ""
+ output_dict = {"message": output}
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 output
-
- def query(self, history: History) -> str:
+ if self.tools.use_function_calling:
+ if response.choices[0].message.tool_calls:
+ tool_calls = [call.to_dict() for call in response.choices[0].message.tool_calls]
+ else:
+ tool_calls = []
+ output_dict["tool_calls"] = tool_calls
+ return output_dict
+
+ def query(self, history: History) -> dict:
for attempt in Retrying(
stop=stop_after_attempt(self.args.retry.retries),
wait=wait_random_exponential(min=self.args.retry.min_wait, max=self.args.retry.max_wait),
@@ -388,25 +432,39 @@ class LiteLLMModel(AbstractModel):
return "user" if self.args.convert_system_to_user else "system"
return history_item["role"]
- return [{"role": get_role(history_item), "content": history_item["content"]} for history_item in history]
+ messages = []
+ for history_item in history:
+ role = get_role(history_item)
+ if role == "tool":
+ messages.append(
+ {
+ "role": role,
+ "content": history_item["content"],
+ "tool_call_id": history_item["tool_call_ids"][0], # Only one tool call per observations
+ }
+ )
+ elif "tool_calls" in history_item:
+ messages.append(
+ {"role": role, "content": history_item["content"], "tool_calls": history_item["tool_calls"]}
+ )
+ else:
+ messages.append({"role": role, "content": history_item["content"]})
+ return messages
-def get_model(args: ModelConfig, commands: list[Command] | None = None) -> AbstractModel:
+def get_model(args: ModelConfig, tools: ToolConfig) -> AbstractModel:
"""Returns correct model object given arguments and commands"""
- if commands is None:
- commands = []
-
if args.name == "human":
assert isinstance(args, HumanModelConfig)
- return HumanModel(args, commands)
+ return HumanModel(args, tools)
if args.name == "human_thought":
assert isinstance(args, HumanThoughtModelConfig)
- return HumanThoughtModel(args, commands)
+ return HumanThoughtModel(args, tools)
if args.name == "replay":
assert isinstance(args, ReplayModelConfig)
- return ReplayModel(args, commands)
+ return ReplayModel(args, tools)
elif args.name == "instant_empty_submit":
assert isinstance(args, InstantEmptySubmitModelConfig)
- return InstantEmptySubmitTestModel(args, commands)
+ return InstantEmptySubmitTestModel(args, tools)
assert isinstance(args, GenericAPIModelConfig)
- return LiteLLMModel(args, commands)
+ return LiteLLMModel(args, tools)
diff --git a/sweagent/tools/commands.py b/sweagent/tools/commands.py
index 4d916c9c..b839e1a2 100644
--- a/sweagent/tools/commands.py
+++ b/sweagent/tools/commands.py
@@ -1,21 +1,103 @@
from __future__ import annotations
import re
+import string
from abc import ABC, abstractmethod
+from functools import cached_property
from pathlib import Path
from typing import Literal
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, model_validator
+
+ARGUMENT_NAME_PATTERN = r"[a-zA-Z_][a-zA-Z0-9_-]+"
+
+
+def _extract_keys(format_string: str) -> set[str]:
+ """Given a format string, returns a set of all the keys in the format string."""
+ formatter = string.Formatter()
+ keys = set()
+ for _, field_name, _, _ in formatter.parse(format_string):
+ if field_name is not None:
+ keys.add(field_name)
+ return keys
+
+
+class Argument(BaseModel):
+ name: str
+ type: str
+ description: str
+ required: bool
+ enum: list[str] | None = None
+ argument_format: str = "{value}" # how to invoke the argument in the command
class Command(BaseModel):
name: str
- docstring: str | None = None
+ docstring: str | None
+ signature: str | None = None
# if there is an end_name, then it is a multi-line command
end_name: str | None = None
- arguments: list[dict] | None = None
- signature: str | None = None
+ arguments: list[Argument] | None = None
+
+ @cached_property
+ def invoke_format(self) -> str:
+ if self.signature:
+ return re.sub(rf"\[?<({ARGUMENT_NAME_PATTERN})>\]?", r"{\1}", self.signature)
+ else:
+ # cmd arg_format_1 arg_format_2 ...
+ _invoke_format = f"{self.name} "
+ for arg in self.arguments:
+ _invoke_format += f"{{{arg.name}}} "
+ return _invoke_format
+
+ def get_function_calling_tool(self) -> dict:
+ tool = {
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "description": self.docstring or "",
+ },
+ }
+ properties = {}
+ required = []
+ if self.arguments:
+ for arg in self.arguments:
+ properties[arg.name] = {"type": arg.type, "description": arg.description}
+
+ if arg.required:
+ required.append(arg.name)
+
+ # Handle enum if present
+ if arg.enum:
+ properties[arg.name]["enum"] = arg.enum
+ tool["function"]["parameters"] = {"type": "object", "properties": properties, "required": required}
+ return tool
+
+ @model_validator(mode="after")
+ def validate_arguments(self) -> Command:
+ """Validates that optional arguments come after required arguments and argument names are unique."""
+ if not self.arguments:
+ return self
+ found_optional = False
+ for arg in self.arguments:
+ if found_optional and arg.required:
+ msg = f"Command '{self.name}': Required argument '{arg.name}' cannot come after optional arguments"
+ raise ValueError(msg)
+ if not arg.required:
+ found_optional = True
+ duplicates = {arg.name for arg in self.arguments if self.arguments.count(arg) > 1}
+ if duplicates:
+ msg = f"Command '{self.name}': Duplicate argument names: {duplicates}"
+ raise ValueError(msg)
+ for arg in self.arguments:
+ if not re.match(ARGUMENT_NAME_PATTERN, arg.name):
+ msg = f"Command '{self.name}': Invalid argument name: '{arg.name}'"
+ raise ValueError(msg)
+ if _extract_keys(self.invoke_format) != {arg.name for arg in self.arguments}:
+ msg = f"Command '{self.name}': Argument names in signature / invoke_format do not match argument names"
+ raise ValueError(msg)
+ return self
class AbstractParseCommand(ABC):
@@ -221,11 +303,26 @@ class ParseCommandDetailed(ParseCommandBash):
if "arguments" in cmd.__dict__ and cmd.arguments is not None:
docs += " arguments:\n"
for argument in cmd.arguments:
- param = argument["name"]
- req_string = "required" if argument["required"] else "optional"
- docs += f" - {param} ({argument['type']}) [{req_string}]: {argument['description']}\n"
+ param = argument.name
+ req_string = "required" if argument.required else "optional"
+ docs += f" - {param} ({argument.type}) [{req_string}]: {argument.description}\n"
docs += "\n"
return docs
ParseCommand = ParseCommandBash | ParseCommandDetailed
+
+# Default Bash tool
+BASH_COMMAND = Command(
+ name="bash",
+ signature="<command>",
+ docstring="runs the given command directly in bash",
+ arguments=[
+ Argument(
+ name="command",
+ type="string",
+ description="a command to run directly in the current shell",
+ required=True,
+ )
+ ],
+)
diff --git a/sweagent/tools/parsing.py b/sweagent/tools/parsing.py
index 6fd0586b..85e148d0 100644
--- a/sweagent/tools/parsing.py
+++ b/sweagent/tools/parsing.py
@@ -2,15 +2,15 @@
import json
import re
-import shlex
-import string
import textwrap
from abc import ABC, abstractmethod
-from typing import Any, Literal
+from shlex import quote
+from typing import Literal
from pydantic import BaseModel
from sweagent.tools.commands import Command
+from sweagent.tools.utils import _should_quote
class FormatError(Exception):
@@ -53,11 +53,11 @@ class ActionParser(AbstractParseFunction, BaseModel):
type: Literal["action"] = "action"
"""Type for (de)serialization. Do not change."""
- def __call__(self, model_response, commands: list[Command], strict=False):
- if model_response.split():
- action = model_response.strip().split()[0]
+ def __call__(self, model_response: dict, commands: list[Command], strict=False):
+ if model_response["message"].split():
+ action = model_response["message"].strip().split()[0]
if action in {command.name for command in commands}:
- return model_response, model_response
+ return model_response["message"], model_response["message"]
msg = "First word in model response is not a valid command."
raise FormatError(msg)
@@ -86,7 +86,7 @@ class ThoughtActionParser(AbstractParseFunction, BaseModel):
type: Literal["thought_action"] = "thought_action"
"""Type for (de)serialization. Do not change."""
- def __call__(self, model_response, commands: list[Command], strict=False):
+ def __call__(self, model_response: dict, commands: list[Command], strict=False):
"""
Parses the action from the output of the API call.
We assume that the action is the last code block in the model_response.
@@ -105,7 +105,7 @@ class ThoughtActionParser(AbstractParseFunction, BaseModel):
code_block_pat = re.compile(r"^```(\S*)\s*\n|^```\s*$", re.MULTILINE)
stack = []
last_valid_block = None
- for match in code_block_pat.finditer(model_response):
+ for match in code_block_pat.finditer(model_response["message"]):
if stack and not match.group(1): # Closing of a code block
start = stack.pop()
# Check if it's not nested within another block
@@ -115,8 +115,8 @@ class ThoughtActionParser(AbstractParseFunction, BaseModel):
stack.append(match)
if last_valid_block:
start, end = last_valid_block
- thought = model_response[: start.start()] + model_response[end.end() :]
- return thought, model_response[start.end() : end.start()]
+ thought = model_response["message"][: start.start()] + model_response["message"][end.end() :]
+ return thought, model_response["message"][start.end() : end.start()]
msg = "No action found in model response."
raise FormatError(msg)
@@ -139,7 +139,7 @@ class XMLThoughtActionParser(AbstractParseFunction, BaseModel):
type: Literal["xml_thought_action"] = "xml_thought_action"
"""Type for (de)serialization. Do not change."""
- def __call__(self, model_response, commands: list[Command], strict=False) -> tuple[str, str]:
+ def __call__(self, model_response: dict, commands: list[Command], strict=False) -> tuple[str, str]:
"""
Parses the action from the output of the API call.
We assume that the action is the last code block in the model_response.
@@ -155,17 +155,21 @@ class XMLThoughtActionParser(AbstractParseFunction, BaseModel):
In this case, only the second code block will be parsed as the action.
"""
- if "<command>" not in model_response or "</command>" not in model_response:
+ if "<command>" not in model_response["message"] or "</command>" not in model_response["message"]:
msg = "No action found in model response."
raise FormatError(msg)
# `action` is everything between the last <command> and </command> tags
- start_action = model_response.rfind("<command>") + len("<command>") # start after the last <command> tag
- end_thought = model_response.rfind("<command>") # end before the last <command> tag
- end_action = model_response.rfind("</command>") # end before the last </command> tag
- restart_thought = model_response.rfind("</command>") + len("</command>") # start after the last </command> tag
+ start_action = model_response["message"].rfind("<command>") + len(
+ "<command>"
+ ) # start after the last <command> tag
+ end_thought = model_response["message"].rfind("<command>") # end before the last <command> tag
+ end_action = model_response["message"].rfind("</command>") # end before the last </command> tag
+ restart_thought = model_response["message"].rfind("</command>") + len(
+ "</command>"
+ ) # start after the last </command> tag
# `thought` is everything not in between <command> and </command> tags (includes after the last </command> tag)
- action = model_response[start_action:end_action]
- thought = model_response[:end_thought] + model_response[restart_thought:]
+ action = model_response["message"][start_action:end_action]
+ thought = model_response["message"][:end_thought] + model_response["message"][restart_thought:]
return thought.strip(), action.strip()
@@ -210,11 +214,69 @@ class Identity(AbstractParseFunction, BaseModel):
type: Literal["identity"] = "identity"
"""Type for (de)serialization. Do not change."""
- def __call__(self, model_response, commands: list[Command], strict=False) -> tuple[str, str]:
+ def __call__(self, model_response: dict, commands: list[Command], strict=False) -> tuple[str, str]:
"""
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"]
+ 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."
+ raise FormatError(msg)
+ tool_call = tool_calls[0]
+ action = self._parse_tool_call(tool_call, commands)
+ return message, action
class JsonParser(AbstractParseFunction, BaseModel):
@@ -229,7 +291,7 @@ class JsonParser(AbstractParseFunction, BaseModel):
type: Literal["json"] = "json"
"""Type for (de)serialization. Do not change."""
- def __call__(self, model_response, commands: list[Command], strict=False):
+ def __call__(self, model_response: dict, commands: list[Command], strict=False):
"""Parses the action from the output of the API call.
We assume that model output is a JSON object with the following fields:
{
@@ -245,7 +307,7 @@ class JsonParser(AbstractParseFunction, BaseModel):
}
"""
try:
- data = json.loads(model_response)
+ data = json.loads(model_response["message"])
if not isinstance(data, dict):
msg = "Model output is not a JSON object."
raise FormatError(msg)
@@ -276,44 +338,31 @@ class JsonParser(AbstractParseFunction, BaseModel):
commands_dict = {c.name: c for c in commands}
command = commands_dict.get(data_command["name"])
if command is None:
- 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()
+ action = " ".join([data_command["name"], *data_command["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)
+ # Use the formatted arguments with invoke_format
+ action = command.invoke_format.format(**formatted_args).strip()
return thought, action
except json.JSONDecodeError:
msg = "Model output is not valid JSON."
raise FormatError(msg)
-ParseFunction = ActionParser | ThoughtActionParser | XMLThoughtActionParser | EditFormat | Identity | JsonParser
-
-
-def _extract_keys(format_string: str) -> set[str]:
- """Given a format string, returns a set of all the keys in the format string."""
- formatter = string.Formatter()
- keys = set()
- for _, field_name, _, _ in formatter.parse(format_string):
- if field_name is not None:
- keys.add(field_name)
- return keys
-
-
-def _should_quote(value: Any, command: Command) -> bool:
- """Returns True if the value should be quoted, False otherwise."""
- return isinstance(value, str) and command.end_name is None
+ParseFunction = (
+ ActionParser
+ | ThoughtActionParser
+ | XMLThoughtActionParser
+ | FunctionCallingParser
+ | EditFormat
+ | Identity
+ | JsonParser
+)
diff --git a/sweagent/tools/tools.py b/sweagent/tools/tools.py
index 5d9f2771..937d3094 100644
--- a/sweagent/tools/tools.py
+++ b/sweagent/tools/tools.py
@@ -11,8 +11,8 @@ from swerex.runtime.abstract import Command as RexCommand
from swerex.runtime.abstract import UploadRequest
from 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, ParseFunction
from sweagent.tools.utils import _guard_multiline_input
from sweagent.utils.log import get_logger
@@ -61,9 +61,11 @@ class ToolConfig(BaseModel):
submit_command: str = "submit"
- parse_function: ParseFunction = Field(default_factory=ThoughtActionParser)
+ parse_function: ParseFunction | None = Field(default=None)
parse_command: ParseCommand = Field(default_factory=ParseCommandBash)
+ include_bash_tool: bool = True
+
format_error_template: str = None # type: ignore
"""Defaults to format_error_template in ParseFunction"""
@@ -89,6 +91,10 @@ class ToolConfig(BaseModel):
install_timeout: int = 300
"""Timeout used for each of the installation commands"""
+ @property
+ def use_function_calling(self) -> bool:
+ return isinstance(self.parse_function, FunctionCallingParser)
+
# todo: move to ToolHandler?
@cached_property
def commands(self) -> list[Command]:
@@ -108,16 +114,30 @@ class ToolConfig(BaseModel):
raise ValueError(msg)
commands.append(Command(name=tool, **tool_config))
tool_sources[tool] = path
+ if self.include_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:
commands = self.commands
-
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 (
+ 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."
+ raise ValueError(msg)
+
self.multi_line_command_endings = multi_line_command_endings
self.command_docs = self.parse_command.generate_command_docs(
self.commands,
@@ -274,7 +294,7 @@ class ToolHandler:
return None
return match.group(1)
- def parse_actions(self, output: str) -> tuple[str, str]:
+ def parse_actions(self, output: dict) -> tuple[str, str]:
"""Parse the model output into a thought and action."""
return self.config.parse_function(output, self.config.commands)
diff --git a/sweagent/tools/utils.py b/sweagent/tools/utils.py
index 172a7f5c..8c4c1efe 100644
--- a/sweagent/tools/utils.py
+++ b/sweagent/tools/utils.py
@@ -1,5 +1,8 @@
import re
from collections.abc import Callable
+from typing import Any
+
+from sweagent.tools.commands import Command
def _guard_multiline_input(action: str, match_fct: Callable[[str], re.Match | None]) -> str:
@@ -31,3 +34,10 @@ def _guard_multiline_input(action: str, match_fct: Callable[[str], re.Match | No
parsed_action.append(rem_action)
rem_action = ""
return "\n".join(parsed_action)
+
+
+def _should_quote(value: Any, command: Command) -> bool:
+ """Returns True if the value should be quoted, False otherwise."""
+ if command.name == "bash":
+ return False
+ return isinstance(value, str) and command.end_name is None
diff --git a/sweagent/types.py b/sweagent/types.py
index 1e8ba3dd..8d19f0ac 100644
--- a/sweagent/types.py
+++ b/sweagent/types.py
@@ -25,6 +25,8 @@ class StepOutput(BaseModel):
exit_status: str | None = None
submission: str | None = None
state: dict[str, str] = {}
+ tool_calls: list[dict[str, str]] | None = None
+ tool_call_ids: list[str] | None = None
"""State of the environment at the end of the step"""
@@ -47,6 +49,8 @@ class HistoryItem(_HistoryItem, total=False):
is_demo: bool
thought: str
action: str | None
+ tool_calls: list[dict[str, str]] | None = None
+ tool_call_ids: list[str] | None = None
History = list[HistoryItem]