Skip to content

Commit bb64ca0

Browse files
committed
Convert swarm run to be sequential.
1 parent 158b714 commit bb64ca0

4 files changed

Lines changed: 53 additions & 57 deletions

File tree

agentstack/frameworks/openai_swarm.py

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -80,35 +80,6 @@ def {task.name}(self, messages: list[str] = []) -> Agent:
8080
existing_agent_methods = self.get_agent_methods()
8181
if not len(existing_agent_methods):
8282
return # no agents to update
83-
84-
# add a call to `self._handoff(task_name)` to the front of the update_method's
85-
# `function` argument which is a list of functions
86-
update_method = existing_agent_methods[-1]
87-
try:
88-
agent_instance = asttools.find_method_calls(update_method, 'Agent')[0]
89-
except IndexError:
90-
raise ValidationError(f"Agent method `{update_method.name}` does not instantiate `Agent` in {ENTRYPOINT}")
91-
92-
existing_agent_tools = asttools.find_kwarg_in_method_call(agent_instance, 'functions')
93-
if not existing_agent_tools:
94-
raise ValidationError(
95-
f"`@agent` method `{update_method.name}` does not have a keyword argument `functions` in {ENTRYPOINT}"
96-
)
97-
98-
assert isinstance(existing_agent_tools.value, ast.List)
99-
existing_elts = existing_agent_tools.value.elts
100-
existing_elts.insert(0, ast.Call(
101-
func=ast.Attribute(
102-
value=ast.Name(id='self', ctx=ast.Load()),
103-
attr='_handoff',
104-
ctx=ast.Load(),
105-
),
106-
args=[ast.Constant(value=task.name)],
107-
keywords=[],
108-
))
109-
new_node = ast.List(elts=existing_elts, ctx=ast.Load())
110-
start, end = self.get_node_range(existing_agent_tools.value)
111-
self.edit_node_range(start, end, new_node)
11283

11384
def get_agent_methods(self) -> list[ast.FunctionDef]:
11485
"""An `agent` method is a method decorated with `@agent`."""

agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,22 @@
44

55
class {{ cookiecutter.project_metadata.project_name|replace('-', '')|replace('_', '')|capitalize }}Stack:
66

7-
def _handoff(self, task_name: str):
8-
"""Return a task formatted as a tool for handing off to another agent."""
9-
task = getattr(self, task_name)
10-
def func(messages: list[str] = []) -> Agent:
11-
return task(messages=messages)
12-
func.__name__ = task_name
13-
return func
14-
15-
def _get_first_task(self) -> Agent:
16-
"""Get the first task."""
17-
task_name = agentstack.get_all_task_names()[0]
18-
return getattr(self, task_name)()
19-
207
def run(self, inputs: list[str]):
218
app = Swarm()
22-
response = app.run(
23-
agent=self._get_first_task(),
24-
messages=[],
25-
context_variables=inputs,
26-
debug=agentstack.conf.DEBUG,
27-
)
28-
29-
for message in response.messages:
30-
if message.get('tool_calls'):
31-
for tool_call in message['tool_calls']:
32-
agentstack.log.notify(f"Calling tool `{tool_call['function']['name']}`")
33-
agentstack.log.debug(tool_call['function']['arguments'])
34-
elif message.get('role') != 'tool':
35-
agentstack.log.notify(f"{message['role']}:")
9+
history = []
10+
for task in agentstack.get_all_tasks():
11+
agentstack.log.notify(f"Running task `{task.name}`")
12+
response = app.run(
13+
agent=getattr(self, task.name)(),
14+
messages=history,
15+
context_variables=inputs,
16+
debug=agentstack.conf.DEBUG,
17+
)
18+
for message in response.messages:
19+
if message.get('role') not in ['user', 'assistant']:
20+
continue
21+
if message.get('tool_calls'):
22+
continue
23+
history.append(message)
3624
agentstack.log.info(message['content'])
3725

agentstack/templates/proj_templates/hello_alex.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"name": "alex",
88
"role": "You are a friendly assistant.",
99
"goal": "Help the user with any of their requests.",
10-
"backstory": "After years travelling the world, you've decided to get back into tech, just in time for the AI boom!. You're working on AgentStack, the fastest way to get started with AI agents. You have a README file available at: ./README.md",
10+
"backstory": "After years traveling the world, you've decided to get back into tech, just in time for the AI boom!. You're working on AgentStack, the fastest way to get started with AI agents. You have a README file available at: ./README.md",
1111
"model": "openai/gpt-4o"
1212
}],
1313
"tasks": [{
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
{
2+
"name": "hola_alex",
3+
"description": "This is the start of your AgentStack project.",
4+
"template_version": 4,
5+
"framework": "openai_swarm",
6+
"agents": [{
7+
"name": "alex",
8+
"role": "You are a friendly assistant.",
9+
"goal": "Help the user with any of their requests.",
10+
"backstory": "After years traveling the world, you've decided to get back into tech, just in time for the AI boom!. You're working on AgentStack, the fastest way to get started with AI agents. You have a README file available at: ./README.md",
11+
"llm": "openai/gpt-4o"
12+
}, {
13+
"name": "translator",
14+
"role": "You are a professional translator.",
15+
"goal": "Translate content passed to you into the correct language.",
16+
"backstory": "You have an ivy league education in linguistics.",
17+
"llm": "openai/gpt-4o"
18+
}],
19+
"tasks": [{
20+
"name": "hello_world",
21+
"description": "As is tradition in software, let's start by saying 'Hello, World!'. Then, pick one or two tasks that they should try to do next with AgentStack.",
22+
"expected_output": "The sentence Hello, World! followed by two things the user should try to customize their agent further.",
23+
"agent": "alex"
24+
}, {
25+
"name": "translate_to_spanish",
26+
"description": "Translate the content to Spanish.",
27+
"expected_output": "The content translated to Spanish.",
28+
"agent": "translator"
29+
}],
30+
"tools": [{
31+
"name": "file_read",
32+
"agents": ["alex"]
33+
}],
34+
"method": "sequential",
35+
"graph": [],
36+
"inputs": {}
37+
}

0 commit comments

Comments
 (0)