| 1 | # Standard library imports |
| 2 | import copy |
| 3 | import json |
| 4 | from collections import defaultdict |
| 5 | from typing import List, Callable, Union |
| 6 | |
| 7 | # Package/library imports |
| 8 | from openai import OpenAI |
| 9 | |
| 10 | |
| 11 | # Local imports |
| 12 | from .util import function_to_json, debug_print, merge_chunk |
| 13 | from .types import ( |
| 14 | Agent, |
| 15 | AgentFunction, |
| 16 | ChatCompletionMessage, |
| 17 | ChatCompletionMessageToolCall, |
| 18 | Function, |
| 19 | Response, |
| 20 | Result, |
| 21 | ) |
| 22 | |
| 23 | __CTX_VARS_NAME__ = "context_variables" |
| 24 | |
| 25 | |
| 26 | class Swarm: |
| 27 | def __init__(self, client=None): |
| 28 | if not client: |
| 29 | client = OpenAI() |
| 30 | self.client = client |
| 31 | |
| 32 | def get_chat_completion( |
| 33 | self, |
| 34 | agent: Agent, |
| 35 | history: List, |
| 36 | context_variables: dict, |
| 37 | model_override: str, |
| 38 | stream: bool, |
| 39 | debug: bool, |
| 40 | ) -> ChatCompletionMessage: |
| 41 | context_variables = defaultdict(str, context_variables) |
| 42 | instructions = ( |
| 43 | agent.instructions(context_variables) |
| 44 | if callable(agent.instructions) |
| 45 | else agent.instructions |
| 46 | ) |
| 47 | messages = [{"role": "system", "content": instructions}] + history |
| 48 | debug_print(debug, "Getting chat completion for...:", messages) |
| 49 | |
| 50 | tools = [function_to_json(f) for f in agent.functions] |
| 51 | # hide context_variables from model |
| 52 | for tool in tools: |
| 53 | params = tool["function"]["parameters"] |
| 54 | params["properties"].pop(__CTX_VARS_NAME__, None) |
| 55 | if __CTX_VARS_NAME__ in params["required"]: |
| 56 | params["required"].remove(__CTX_VARS_NAME__) |
| 57 | |
| 58 | create_params = { |
| 59 | "model": model_override or agent.model, |
| 60 | "messages": messages, |
| 61 | "tools": tools or None, |
| 62 | "tool_choice": agent.tool_choice, |
| 63 | "stream": stream, |
| 64 | } |
| 65 | |
| 66 | if tools: |
| 67 | create_params["parallel_tool_calls"] = agent.parallel_tool_calls |
| 68 | |
| 69 | return self.client.chat.completions.create(**create_params) |
| 70 | |
| 71 | def handle_function_result(self, result, debug) -> Result: |
| 72 | match result: |
| 73 | case Result() as result: |
| 74 | return result |
| 75 | |
| 76 | case Agent() as agent: |
| 77 | return Result( |
| 78 | value=json.dumps({"assistant": agent.name}), |
| 79 | agent=agent, |
| 80 | ) |
| 81 | case _: |
| 82 | try: |
| 83 | return Result(value=str(result)) |
| 84 | except Exception as e: |
| 85 | error_message = f"Failed to cast response to string: {result}. Make sure agent functions return a string or Result object. Error: {str(e)}" |
| 86 | debug_print(debug, error_message) |
| 87 | raise TypeError(error_message) |
| 88 | |
| 89 | def handle_tool_calls( |
| 90 | self, |
| 91 | tool_calls: List[ChatCompletionMessageToolCall], |
| 92 | functions: List[AgentFunction], |
| 93 | context_variables: dict, |
| 94 | debug: bool, |
| 95 | ) -> Response: |
| 96 | function_map = {f.__name__: f for f in functions} |
| 97 | partial_response = Response( |
| 98 | messages=[], agent=None, context_variables={}) |
| 99 | |
| 100 | for tool_call in tool_calls: |
| 101 | name = tool_call.function.name |
| 102 | # handle missing tool case, skip to next tool |
| 103 | if name not in function_map: |
| 104 | debug_print(debug, f"Tool {name} not found in function map.") |
| 105 | partial_response.messages.append( |
| 106 | { |
| 107 | "role": "tool", |
| 108 | "tool_call_id": tool_call.id, |
| 109 | "tool_name": name, |
| 110 | "content": f"Error: Tool {name} not found.", |
| 111 | } |
| 112 | ) |
| 113 | continue |
| 114 | args = json.loads(tool_call.function.arguments) |
| 115 | debug_print( |
| 116 | debug, f"Processing tool call: {name} with arguments {args}") |
| 117 | |
| 118 | func = function_map[name] |
| 119 | # pass context_variables to agent functions |
| 120 | if __CTX_VARS_NAME__ in func.__code__.co_varnames: |
| 121 | args[__CTX_VARS_NAME__] = context_variables |
| 122 | raw_result = function_map[name](**args) |
| 123 | |
| 124 | result: Result = self.handle_function_result(raw_result, debug) |
| 125 | partial_response.messages.append( |
| 126 | { |
| 127 | "role": "tool", |
| 128 | "tool_call_id": tool_call.id, |
| 129 | "tool_name": name, |
| 130 | "content": result.value, |
| 131 | } |
| 132 | ) |
| 133 | partial_response.context_variables.update(result.context_variables) |
| 134 | if result.agent: |
| 135 | partial_response.agent = result.agent |
| 136 | |
| 137 | return partial_response |
| 138 | |
| 139 | def run_and_stream( |
| 140 | self, |
| 141 | agent: Agent, |
| 142 | messages: List, |
| 143 | context_variables: dict = {}, |
| 144 | model_override: str = None, |
| 145 | debug: bool = False, |
| 146 | max_turns: int = float("inf"), |
| 147 | execute_tools: bool = True, |
| 148 | ): |
| 149 | active_agent = agent |
| 150 | context_variables = copy.deepcopy(context_variables) |
| 151 | history = copy.deepcopy(messages) |
| 152 | init_len = len(messages) |
| 153 | |
| 154 | while len(history) - init_len < max_turns: |
| 155 | |
| 156 | message = { |
| 157 | "content": "", |
| 158 | "sender": agent.name, |
| 159 | "role": "assistant", |
| 160 | "function_call": None, |
| 161 | "tool_calls": defaultdict( |
| 162 | lambda: { |
| 163 | "function": {"arguments": "", "name": ""}, |
| 164 | "id": "", |
| 165 | "type": "", |
| 166 | } |
| 167 | ), |
| 168 | } |
| 169 | |
| 170 | # get completion with current history, agent |
| 171 | completion = self.get_chat_completion( |
| 172 | agent=active_agent, |
| 173 | history=history, |
| 174 | context_variables=context_variables, |
| 175 | model_override=model_override, |
| 176 | stream=True, |
| 177 | debug=debug, |
| 178 | ) |
| 179 | |
| 180 | yield {"delim": "start"} |
| 181 | for chunk in completion: |
| 182 | delta = json.loads(chunk.choices[0].delta.json()) |
| 183 | if delta["role"] == "assistant": |
| 184 | delta["sender"] = active_agent.name |
| 185 | yield delta |
| 186 | delta.pop("role", None) |
| 187 | delta.pop("sender", None) |
| 188 | merge_chunk(message, delta) |
| 189 | yield {"delim": "end"} |
| 190 | |
| 191 | message["tool_calls"] = list( |
| 192 | message.get("tool_calls", {}).values()) |
| 193 | if not message["tool_calls"]: |
| 194 | message["tool_calls"] = None |
| 195 | debug_print(debug, "Received completion:", message) |
| 196 | history.append(message) |
| 197 | |
| 198 | if not message["tool_calls"] or not execute_tools: |
| 199 | debug_print(debug, "Ending turn.") |
| 200 | break |
| 201 | |
| 202 | # convert tool_calls to objects |
| 203 | tool_calls = [] |
| 204 | for tool_call in message["tool_calls"]: |
| 205 | function = Function( |
| 206 | arguments=tool_call["function"]["arguments"], |
| 207 | name=tool_call["function"]["name"], |
| 208 | ) |
| 209 | tool_call_object = ChatCompletionMessageToolCall( |
| 210 | id=tool_call["id"], function=function, type=tool_call["type"] |
| 211 | ) |
| 212 | tool_calls.append(tool_call_object) |
| 213 | |
| 214 | # handle function calls, updating context_variables, and switching agents |
| 215 | partial_response = self.handle_tool_calls( |
| 216 | tool_calls, active_agent.functions, context_variables, debug |
| 217 | ) |
| 218 | history.extend(partial_response.messages) |
| 219 | context_variables.update(partial_response.context_variables) |
| 220 | if partial_response.agent: |
| 221 | active_agent = partial_response.agent |
| 222 | |
| 223 | yield { |
| 224 | "response": Response( |
| 225 | messages=history[init_len:], |
| 226 | agent=active_agent, |
| 227 | context_variables=context_variables, |
| 228 | ) |
| 229 | } |
| 230 | |
| 231 | def run( |
| 232 | self, |
| 233 | agent: Agent, |
| 234 | messages: List, |
| 235 | context_variables: dict = {}, |
| 236 | model_override: str = None, |
| 237 | stream: bool = False, |
| 238 | debug: bool = False, |
| 239 | max_turns: int = float("inf"), |
| 240 | execute_tools: bool = True, |
| 241 | ) -> Response: |
| 242 | if stream: |
| 243 | return self.run_and_stream( |
| 244 | agent=agent, |
| 245 | messages=messages, |
| 246 | context_variables=context_variables, |
| 247 | model_override=model_override, |
| 248 | debug=debug, |
| 249 | max_turns=max_turns, |
| 250 | execute_tools=execute_tools, |
| 251 | ) |
| 252 | active_agent = agent |
| 253 | context_variables = copy.deepcopy(context_variables) |
| 254 | history = copy.deepcopy(messages) |
| 255 | init_len = len(messages) |
| 256 | |
| 257 | while len(history) - init_len < max_turns and active_agent: |
| 258 | |
| 259 | # get completion with current history, agent |
| 260 | completion = self.get_chat_completion( |
| 261 | agent=active_agent, |
| 262 | history=history, |
| 263 | context_variables=context_variables, |
| 264 | model_override=model_override, |
| 265 | stream=stream, |
| 266 | debug=debug, |
| 267 | ) |
| 268 | message = completion.choices[0].message |
| 269 | debug_print(debug, "Received completion:", message) |
| 270 | message.sender = active_agent.name |
| 271 | history.append( |
| 272 | json.loads(message.model_dump_json()) |
| 273 | ) # to avoid OpenAI types (?) |
| 274 | |
| 275 | if not message.tool_calls or not execute_tools: |
| 276 | debug_print(debug, "Ending turn.") |
| 277 | break |
| 278 | |
| 279 | # handle function calls, updating context_variables, and switching agents |
| 280 | partial_response = self.handle_tool_calls( |
| 281 | message.tool_calls, active_agent.functions, context_variables, debug |
| 282 | ) |
| 283 | history.extend(partial_response.messages) |
| 284 | context_variables.update(partial_response.context_variables) |
| 285 | if partial_response.agent: |
| 286 | active_agent = partial_response.agent |
| 287 | |
| 288 | return Response( |
| 289 | messages=history[init_len:], |
| 290 | agent=active_agent, |
| 291 | context_variables=context_variables, |
| 292 | ) |