open-swarm 0.1.1744943015__py3-none-any.whl → 0.1.1744943085__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {open_swarm-0.1.1744943015.dist-info → open_swarm-0.1.1744943085.dist-info}/METADATA +1 -1
- {open_swarm-0.1.1744943015.dist-info → open_swarm-0.1.1744943085.dist-info}/RECORD +25 -5
- swarm/core/agent_utils.py +21 -0
- swarm/core/blueprint_base.py +395 -0
- swarm/core/blueprint_discovery.py +128 -0
- swarm/core/blueprint_runner.py +59 -0
- swarm/core/blueprint_utils.py +17 -0
- swarm/core/build_launchers.py +14 -0
- swarm/core/build_swarm_wrapper.py +12 -0
- swarm/core/common_utils.py +12 -0
- swarm/core/config_loader.py +122 -0
- swarm/core/config_manager.py +274 -0
- swarm/core/output_utils.py +173 -0
- swarm/core/server_config.py +81 -0
- swarm/core/setup_wizard.py +103 -0
- swarm/core/slash_commands.py +17 -0
- swarm/core/spinner.py +100 -0
- swarm/core/swarm_api.py +68 -0
- swarm/core/swarm_cli.py +216 -0
- swarm/core/swarm_wrapper.py +29 -0
- swarm/core/utils/__init__.py +0 -0
- swarm/core/utils/logger.py +36 -0
- {open_swarm-0.1.1744943015.dist-info → open_swarm-0.1.1744943085.dist-info}/WHEEL +0 -0
- {open_swarm-0.1.1744943015.dist-info → open_swarm-0.1.1744943085.dist-info}/entry_points.txt +0 -0
- {open_swarm-0.1.1744943015.dist-info → open_swarm-0.1.1744943085.dist-info}/licenses/LICENSE +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: open-swarm
|
3
|
-
Version: 0.1.
|
3
|
+
Version: 0.1.1744943085
|
4
4
|
Summary: Open Swarm: Orchestrating AI Agent Swarms with Django
|
5
5
|
Project-URL: Homepage, https://github.com/yourusername/open-swarm
|
6
6
|
Project-URL: Documentation, https://github.com/yourusername/open-swarm/blob/main/README.md
|
@@ -49,6 +49,26 @@ swarm/blueprints/unapologetic_press/blueprint_unapologetic_press.py,sha256=MDegK
|
|
49
49
|
swarm/blueprints/whiskeytango_foxtrot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
50
50
|
swarm/blueprints/whiskeytango_foxtrot/apps.py,sha256=V1QKvyb2Vz-EtDNhhNe4tw2W9LYhNDuiaIq_fAU4ilw,334
|
51
51
|
swarm/blueprints/whiskeytango_foxtrot/blueprint_whiskeytango_foxtrot.py,sha256=8PjKGDHSTaQ76DXPD3T4MXQ8uLIlm4xmJ5s0i64a_Jw,16179
|
52
|
+
swarm/core/agent_utils.py,sha256=exKnbJEm1VRL270x6XqQXHtJhqD8ogY3ZBIGZO_tYUE,552
|
53
|
+
swarm/core/blueprint_base.py,sha256=YRn8wYfOAnLlO40x7M-m9gcl2dCnq8uuwRiqEicQwN8,18602
|
54
|
+
swarm/core/blueprint_discovery.py,sha256=rNbfe0D98kfWiW5MdushT8405899tfm_hnpVN5jDg_Q,5688
|
55
|
+
swarm/core/blueprint_runner.py,sha256=TIfcIFfW86gCIeYs67ePmurKRPrcGgVYmVFGbpNuojQ,2576
|
56
|
+
swarm/core/blueprint_utils.py,sha256=Ef_pu-RYomqzFjMg6LOSPSdbYFCbYXjEoSvK1OT49Eo,702
|
57
|
+
swarm/core/build_launchers.py,sha256=Eh3ODR9L4KinG1GDK4-lF3NE0EZ-ArCrP3fxtGYhXgs,433
|
58
|
+
swarm/core/build_swarm_wrapper.py,sha256=c_9oR3To4M2cZyc1uYSiysHLhUGX5FkCAQk9AG7Va2Q,231
|
59
|
+
swarm/core/common_utils.py,sha256=jeKcN3lMdrpOYWIpErH3L5am13jHjaImpVvk2b0mps4,462
|
60
|
+
swarm/core/config_loader.py,sha256=ldQGtv4tXeDJzL2GCylDxykZxYBo4ALFY2kS0jZ79Eo,5652
|
61
|
+
swarm/core/config_manager.py,sha256=rRTBpqVJrJdHzJ8GD_PCtt6NHfB7_gJmpWkqzy_M-nk,10599
|
62
|
+
swarm/core/output_utils.py,sha256=HGpXIujoJNM5nCCzXH0Upog_ctw5BuftmMBiPujh-ZM,7139
|
63
|
+
swarm/core/server_config.py,sha256=v2t7q22qZwMAPdiUZreQaLAy1706k3VbR8Wk0NCQuCQ,3224
|
64
|
+
swarm/core/setup_wizard.py,sha256=yAZ7MOgc8ZGti2kjZ72G6QLFBI0lbhXAa7Wi7SeXDYo,4567
|
65
|
+
swarm/core/slash_commands.py,sha256=5LEO_veo50_eRDmiGPNnFsI-I6-X-C9NvNNmu1187T0,498
|
66
|
+
swarm/core/spinner.py,sha256=9lyjzLnQBdEBy_dXr6N6I7nxx6KfrNp7wf44sQN06GU,3756
|
67
|
+
swarm/core/swarm_api.py,sha256=f8olTI5JVdayp923etVQWsP8WRquPG5Mw3Q40ItN6kY,2877
|
68
|
+
swarm/core/swarm_cli.py,sha256=dlvMq2HvUI2XlADuTzM8kpeedPkqzKB6k0oy7z2V_p0,9747
|
69
|
+
swarm/core/swarm_wrapper.py,sha256=3K58yqPN4Ct0c7zfSDKRIGdL1Q7WOBXmAVHXT-aaPj4,1004
|
70
|
+
swarm/core/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
71
|
+
swarm/core/utils/logger.py,sha256=sUkKdZsjRiCGGCEPfZ4YqeZDbiaUeGFOa3mdbVOTmvU,1242
|
52
72
|
swarm/extensions/__init__.py,sha256=SadbzfxckByaaqzuKPfXMvqmj45-dcMlavlfQYhGnzE,56
|
53
73
|
swarm/extensions/blueprint/__init__.py,sha256=CqPy-gR0KAeVGxDnOWKOYZZzVC1FXRzQDtUCY8jmP1c,1850
|
54
74
|
swarm/extensions/blueprint/cli_handler.py,sha256=ZdjnTmBzSimQv8rCTwI3ZDp_2Zrjf9hqWLXYD3jzMck,9091
|
@@ -235,8 +255,8 @@ swarm/views/message_views.py,sha256=sDUnXyqKXC8WwIIMAlWf00s2_a2T9c75Na5FvYMJwBM,
|
|
235
255
|
swarm/views/model_views.py,sha256=aAbU4AZmrOTaPeKMWtoKK7FPYHdaN3Zbx55JfKzYTRY,2937
|
236
256
|
swarm/views/utils.py,sha256=8Usc0g0L0NPegNAyY20tJBNBy-JLwODf4VmxV0yUtpw,3627
|
237
257
|
swarm/views/web_views.py,sha256=T1CKe-Nyv1C8aDt6QFTGWo_dkH7ojWAvS_QW9mZnZp0,7371
|
238
|
-
open_swarm-0.1.
|
239
|
-
open_swarm-0.1.
|
240
|
-
open_swarm-0.1.
|
241
|
-
open_swarm-0.1.
|
242
|
-
open_swarm-0.1.
|
258
|
+
open_swarm-0.1.1744943085.dist-info/METADATA,sha256=j21Gbmh-ylnfyUmQC-_Zr6BCSw7qc6TftUHblyD7np0,18813
|
259
|
+
open_swarm-0.1.1744943085.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
260
|
+
open_swarm-0.1.1744943085.dist-info/entry_points.txt,sha256=fo28d0_zJrytRsh8QqkdlWQT_9lyAwYUx1WuSTDI3HM,177
|
261
|
+
open_swarm-0.1.1744943085.dist-info/licenses/LICENSE,sha256=BU9bwRlnOt_JDIb6OT55Q4leLZx9RArDLTFnlDIrBEI,1062
|
262
|
+
open_swarm-0.1.1744943085.dist-info/RECORD,,
|
@@ -0,0 +1,21 @@
|
|
1
|
+
"""
|
2
|
+
agent_utils.py
|
3
|
+
|
4
|
+
Utility functions for agent operations used in blueprints.
|
5
|
+
This module has been updated to remove dependency on swarm.types;
|
6
|
+
instead, it now imports Agent from the openai-agents SDK.
|
7
|
+
"""
|
8
|
+
|
9
|
+
from blueprint_agents.agent import Agent # Updated import
|
10
|
+
|
11
|
+
def get_agent_name(agent: Agent) -> str:
|
12
|
+
"""
|
13
|
+
Returns the name of the agent.
|
14
|
+
"""
|
15
|
+
return agent.name
|
16
|
+
|
17
|
+
def initialize_agents(blueprint) -> dict:
|
18
|
+
"""
|
19
|
+
Initializes agents by calling the blueprint's create_agents() method.
|
20
|
+
"""
|
21
|
+
return blueprint.create_agents()
|
@@ -0,0 +1,395 @@
|
|
1
|
+
# --- REMOVE noisy debug/framework prints unless SWARM_DEBUG=1 ---
|
2
|
+
import os
|
3
|
+
|
4
|
+
def _should_debug():
|
5
|
+
return os.environ.get("SWARM_DEBUG") == "1"
|
6
|
+
|
7
|
+
def _debug_print(*args, **kwargs):
|
8
|
+
if _should_debug():
|
9
|
+
print(*args, **kwargs)
|
10
|
+
|
11
|
+
def _framework_print(*args, **kwargs):
|
12
|
+
if _should_debug():
|
13
|
+
print(*args, **kwargs)
|
14
|
+
|
15
|
+
# --- Content for src/swarm/extensions/blueprint/blueprint_base.py ---
|
16
|
+
import logging
|
17
|
+
import json
|
18
|
+
from abc import ABC, abstractmethod
|
19
|
+
from typing import Dict, Any, Optional, List, AsyncGenerator
|
20
|
+
from pathlib import Path
|
21
|
+
from django.apps import apps # Import Django apps registry
|
22
|
+
|
23
|
+
# Keep the function import
|
24
|
+
from swarm.core.config_loader import _substitute_env_vars
|
25
|
+
|
26
|
+
from openai import AsyncOpenAI
|
27
|
+
from agents import set_default_openai_client
|
28
|
+
|
29
|
+
logger = logging.getLogger(__name__)
|
30
|
+
from rich.console import Console
|
31
|
+
import traceback
|
32
|
+
|
33
|
+
# --- PATCH: Suppress OpenAI tracing/telemetry errors if using LiteLLM/custom endpoint ---
|
34
|
+
import logging
|
35
|
+
import os
|
36
|
+
if os.environ.get("LITELLM_BASE_URL") or os.environ.get("OPENAI_BASE_URL"):
|
37
|
+
# Silence openai.agents tracing/telemetry errors
|
38
|
+
logging.getLogger("openai.agents").setLevel(logging.CRITICAL)
|
39
|
+
try:
|
40
|
+
import openai.agents.tracing
|
41
|
+
openai.agents.tracing.TracingClient = lambda *a, **kw: None
|
42
|
+
except Exception:
|
43
|
+
pass
|
44
|
+
|
45
|
+
# --- Spinner/Status Message Enhancements ---
|
46
|
+
# To be used by all blueprints for consistent UX
|
47
|
+
import itertools
|
48
|
+
import sys
|
49
|
+
import threading
|
50
|
+
import time
|
51
|
+
|
52
|
+
class Spinner:
|
53
|
+
def __init__(self, message_sequence=None, interval=0.3, slow_threshold=10):
|
54
|
+
self.message_sequence = message_sequence or ['Generating.', 'Generating..', 'Generating...', 'Running...']
|
55
|
+
self.interval = interval
|
56
|
+
self.slow_threshold = slow_threshold # seconds before 'Taking longer than expected'
|
57
|
+
self._stop_event = threading.Event()
|
58
|
+
self._thread = None
|
59
|
+
self._start_time = None
|
60
|
+
|
61
|
+
def start(self):
|
62
|
+
self._stop_event.clear()
|
63
|
+
self._start_time = time.time()
|
64
|
+
self._thread = threading.Thread(target=self._spin)
|
65
|
+
self._thread.start()
|
66
|
+
|
67
|
+
def _spin(self):
|
68
|
+
for msg in itertools.cycle(self.message_sequence):
|
69
|
+
if self._stop_event.is_set():
|
70
|
+
break
|
71
|
+
elapsed = time.time() - self._start_time
|
72
|
+
if elapsed > self.slow_threshold:
|
73
|
+
sys.stdout.write('\rGenerating... Taking longer than expected ')
|
74
|
+
else:
|
75
|
+
sys.stdout.write(f'\r{msg} ')
|
76
|
+
sys.stdout.flush()
|
77
|
+
time.sleep(self.interval)
|
78
|
+
sys.stdout.write('\r')
|
79
|
+
sys.stdout.flush()
|
80
|
+
|
81
|
+
def stop(self, final_message=''):
|
82
|
+
self._stop_event.set()
|
83
|
+
if self._thread:
|
84
|
+
self._thread.join()
|
85
|
+
if final_message:
|
86
|
+
sys.stdout.write(f'\r{final_message}\n')
|
87
|
+
sys.stdout.flush()
|
88
|
+
|
89
|
+
# Usage Example (to be called in blueprints):
|
90
|
+
# spinner = Spinner()
|
91
|
+
# spinner.start()
|
92
|
+
# ... do work ...
|
93
|
+
# spinner.stop('Done!')
|
94
|
+
|
95
|
+
def configure_openai_client_from_env():
|
96
|
+
"""
|
97
|
+
Framework-level function: Always instantiate and set the default OpenAI client.
|
98
|
+
Prints out the config being used for debug.
|
99
|
+
"""
|
100
|
+
import os
|
101
|
+
from agents import set_default_openai_client
|
102
|
+
from openai import AsyncOpenAI
|
103
|
+
base_url = os.environ.get("LITELLM_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
|
104
|
+
api_key = os.environ.get("LITELLM_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
105
|
+
_debug_print(f"[DEBUG] Using OpenAI client config: base_url={base_url}, api_key={'set' if api_key else 'NOT SET'}")
|
106
|
+
if base_url and api_key:
|
107
|
+
client = AsyncOpenAI(base_url=base_url, api_key=api_key)
|
108
|
+
set_default_openai_client(client)
|
109
|
+
_framework_print(f"[FRAMEWORK] Set default OpenAI client: base_url={base_url}, api_key={'set' if api_key else 'NOT SET'}")
|
110
|
+
else:
|
111
|
+
_framework_print("[FRAMEWORK] WARNING: base_url or api_key missing, OpenAI client not set!")
|
112
|
+
|
113
|
+
configure_openai_client_from_env()
|
114
|
+
|
115
|
+
class BlueprintBase(ABC):
|
116
|
+
"""
|
117
|
+
Abstract base class for all Swarm blueprints.
|
118
|
+
|
119
|
+
Defines the core interface for blueprint initialization and execution.
|
120
|
+
"""
|
121
|
+
enable_terminal_commands: bool = False # By default, terminal command execution is disabled
|
122
|
+
|
123
|
+
@classmethod
|
124
|
+
def main(cls):
|
125
|
+
"""
|
126
|
+
Standard CLI entry point for all blueprints.
|
127
|
+
Subclasses can override metadata/config_path if needed.
|
128
|
+
"""
|
129
|
+
from swarm.extensions.blueprint.cli_handler import run_blueprint_cli
|
130
|
+
from pathlib import Path
|
131
|
+
swarm_version = getattr(cls, "SWARM_VERSION", "1.0.0")
|
132
|
+
config_path = getattr(cls, "DEFAULT_CONFIG_PATH", Path(__file__).parent / "swarm_config.json")
|
133
|
+
run_blueprint_cli(cls, swarm_version=swarm_version, default_config_path=config_path)
|
134
|
+
|
135
|
+
def display_splash_screen(self, animated: bool = False):
|
136
|
+
"""Default splash screen. Subclasses can override for custom CLI/API branding."""
|
137
|
+
console = Console()
|
138
|
+
console.print(f"[bold cyan]Welcome to {self.__class__.__name__}![/]", style="bold")
|
139
|
+
|
140
|
+
def __init__(self, blueprint_id: str, config: dict = None, config_path: 'Optional[Path]' = None, enable_terminal_commands: 'Optional[bool]' = None, **kwargs):
|
141
|
+
try:
|
142
|
+
if not blueprint_id:
|
143
|
+
raise ValueError("blueprint_id cannot be empty or None")
|
144
|
+
self.blueprint_id = blueprint_id
|
145
|
+
self.config_path = config_path # for legacy compatibility
|
146
|
+
self._config = config # Allow test injection
|
147
|
+
self._llm_profile_name = None
|
148
|
+
self._llm_profile_data = None
|
149
|
+
self._markdown_output = None
|
150
|
+
# Allow per-instance override
|
151
|
+
if enable_terminal_commands is not None:
|
152
|
+
self.enable_terminal_commands = enable_terminal_commands
|
153
|
+
# Else: use class attribute (default False or set by subclass)
|
154
|
+
|
155
|
+
logger.info(f"Initializing blueprint '{self.blueprint_id}' (Type: {self.__class__.__name__})")
|
156
|
+
|
157
|
+
# --- Ensure custom OpenAI client for custom LLM providers ---
|
158
|
+
import os
|
159
|
+
|
160
|
+
# Remove monkey patching and envvar hacks. Always pass config values directly.
|
161
|
+
# (Retain only explicit AsyncOpenAI client instantiation in blueprints)
|
162
|
+
# (No changes needed here for direct client pattern)
|
163
|
+
|
164
|
+
self._load_and_process_config()
|
165
|
+
except AttributeError as e:
|
166
|
+
logger.debug(f"[BlueprintBase.__init__] AttributeError: {e}")
|
167
|
+
traceback.print_exc()
|
168
|
+
raise
|
169
|
+
|
170
|
+
def _load_and_process_config(self):
|
171
|
+
"""Loads the main Swarm config and extracts relevant settings. Falls back to empty config if Django unavailable or not found."""
|
172
|
+
import os
|
173
|
+
import json
|
174
|
+
from pathlib import Path
|
175
|
+
def redact(val):
|
176
|
+
if not isinstance(val, str) or len(val) <= 4:
|
177
|
+
return "****"
|
178
|
+
return val[:2] + "*" * (len(val)-4) + val[-2:]
|
179
|
+
def redact_dict(d):
|
180
|
+
if isinstance(d, dict):
|
181
|
+
return {k: (redact_dict(v) if not (isinstance(v, str) and ("key" in k.lower() or "token" in k.lower() or "secret" in k.lower())) else redact(v)) for k, v in d.items()}
|
182
|
+
elif isinstance(d, list):
|
183
|
+
return [redact_dict(item) for item in d]
|
184
|
+
return d
|
185
|
+
try:
|
186
|
+
if self._config is None:
|
187
|
+
try:
|
188
|
+
# --- Get config from the AppConfig instance (Django) ---
|
189
|
+
app_config_instance = apps.get_app_config('swarm')
|
190
|
+
if not hasattr(app_config_instance, 'config') or not app_config_instance.config:
|
191
|
+
raise ValueError("AppConfig for 'swarm' does not have a valid 'config' attribute.")
|
192
|
+
self._config = app_config_instance.config
|
193
|
+
logger.debug("Loaded config from Django AppConfig.")
|
194
|
+
except Exception as e:
|
195
|
+
if _should_debug():
|
196
|
+
logger.warning(f"Falling back to CLI/home config due to error: {e}")
|
197
|
+
# 1. CLI argument (not handled here, handled in cli_handler)
|
198
|
+
# 2. Current working directory
|
199
|
+
cwd_config = Path.cwd() / "swarm_config.json"
|
200
|
+
if cwd_config.exists():
|
201
|
+
with open(cwd_config, 'r') as f:
|
202
|
+
self._config = json.load(f)
|
203
|
+
# 3. XDG_CONFIG_HOME or ~/.config/swarm/swarm_config.json
|
204
|
+
elif os.environ.get("XDG_CONFIG_HOME"):
|
205
|
+
xdg_config = Path(os.environ["XDG_CONFIG_HOME"]) / "swarm" / "swarm_config.json"
|
206
|
+
if xdg_config.exists():
|
207
|
+
with open(xdg_config, 'r') as f:
|
208
|
+
self._config = json.load(f)
|
209
|
+
elif (Path.home() / ".config/swarm/swarm_config.json").exists():
|
210
|
+
with open(Path.home() / ".config/swarm/swarm_config.json", 'r') as f:
|
211
|
+
self._config = json.load(f)
|
212
|
+
# 4. Legacy fallback: ~/.swarm/swarm_config.json
|
213
|
+
elif (Path.home() / ".swarm/swarm_config.json").exists():
|
214
|
+
with open(Path.home() / ".swarm/swarm_config.json", 'r') as f:
|
215
|
+
self._config = json.load(f)
|
216
|
+
# 5. Fallback: OPENAI_API_KEY envvar
|
217
|
+
elif os.environ.get("OPENAI_API_KEY"):
|
218
|
+
self._config = {
|
219
|
+
"llm": {"default": {"provider": "openai", "model": "gpt-3.5-turbo", "api_key": os.environ["OPENAI_API_KEY"]}},
|
220
|
+
"settings": {"default_llm_profile": "default", "default_markdown_output": True},
|
221
|
+
"blueprints": {},
|
222
|
+
"llm_profile": "default",
|
223
|
+
"mcpServers": {}
|
224
|
+
}
|
225
|
+
logger.info("No config file found, using default config with OPENAI_API_KEY for CLI mode.")
|
226
|
+
else:
|
227
|
+
self._config = {}
|
228
|
+
logger.warning("No config file found and OPENAI_API_KEY is not set. Using empty config. CLI blueprints may fail if LLM config is required.")
|
229
|
+
if self._config is not None:
|
230
|
+
self._config = _substitute_env_vars(self._config)
|
231
|
+
# Ensure self._config is always a dict
|
232
|
+
if self._config is None:
|
233
|
+
self._config = {}
|
234
|
+
settings_section = self._config.get("settings", {})
|
235
|
+
llm_section = self._config.get("llm", {})
|
236
|
+
|
237
|
+
# --- After config is loaded, set OpenAI client from config if possible ---
|
238
|
+
try:
|
239
|
+
llm_profiles = self._config.get("llm", {})
|
240
|
+
default_profile = llm_profiles.get("default", {})
|
241
|
+
base_url = default_profile.get("base_url")
|
242
|
+
api_key = default_profile.get("api_key")
|
243
|
+
# Expand env vars if present
|
244
|
+
import os
|
245
|
+
if base_url and base_url.startswith("${"):
|
246
|
+
var = base_url[2:-1]
|
247
|
+
base_url = os.environ.get(var, base_url)
|
248
|
+
if api_key and api_key.startswith("${"):
|
249
|
+
var = api_key[2:-1]
|
250
|
+
api_key = os.environ.get(var, api_key)
|
251
|
+
if base_url and api_key:
|
252
|
+
from openai import AsyncOpenAI
|
253
|
+
from agents import set_default_openai_client
|
254
|
+
_debug_print(f"[DEBUG] (config) Setting OpenAI client: base_url={base_url}, api_key={'set' if api_key else 'NOT SET'}")
|
255
|
+
client = AsyncOpenAI(base_url=base_url, api_key=api_key)
|
256
|
+
set_default_openai_client(client)
|
257
|
+
except Exception as e:
|
258
|
+
_debug_print(f"[DEBUG] Failed to set OpenAI client from config: {e}")
|
259
|
+
|
260
|
+
# --- Debug: Print and log redacted config ---
|
261
|
+
redacted_config = redact_dict(self._config)
|
262
|
+
logger.debug(f"Loaded config (redacted): {json.dumps(redacted_config, indent=2)}")
|
263
|
+
|
264
|
+
# --- Process LLM profile name and data ---
|
265
|
+
default_profile = settings_section.get("default_llm_profile") or "default"
|
266
|
+
self._llm_profile_name = self._config.get("llm_profile") or default_profile
|
267
|
+
if "profiles" in llm_section:
|
268
|
+
self._llm_profile_data = llm_section["profiles"].get(self._llm_profile_name, {})
|
269
|
+
else:
|
270
|
+
self._llm_profile_data = llm_section.get(self._llm_profile_name, {})
|
271
|
+
|
272
|
+
blueprint_specific_settings = self._config.get("blueprints", {}).get(self.blueprint_id, {})
|
273
|
+
global_markdown_setting = settings_section.get("default_markdown_output", True)
|
274
|
+
self._markdown_output = blueprint_specific_settings.get("markdown_output", global_markdown_setting)
|
275
|
+
logger.debug(f"Markdown output for '{self.blueprint_id}': {self._markdown_output}")
|
276
|
+
|
277
|
+
except ValueError as e:
|
278
|
+
logger.error(f"Configuration error for blueprint '{self.blueprint_id}': {e}", exc_info=True)
|
279
|
+
raise
|
280
|
+
except Exception as e:
|
281
|
+
logger.error(f"Unexpected error loading config for blueprint '{self.blueprint_id}': {e}", exc_info=True)
|
282
|
+
raise
|
283
|
+
|
284
|
+
@property
|
285
|
+
def config(self) -> Dict[str, Any]:
|
286
|
+
"""Returns the loaded and processed Swarm configuration."""
|
287
|
+
if self._config is None:
|
288
|
+
raise RuntimeError("Configuration accessed before initialization or after failure.")
|
289
|
+
return self._config
|
290
|
+
|
291
|
+
@property
|
292
|
+
def llm_profile(self) -> Dict[str, Any]:
|
293
|
+
"""
|
294
|
+
Returns the LLM profile dict for this blueprint.
|
295
|
+
Raises a clear error if provider is missing.
|
296
|
+
"""
|
297
|
+
llm_section = self._config.get("llm", {}) if self._config else {}
|
298
|
+
profile_name = self.llm_profile_name or "default"
|
299
|
+
profile = llm_section.get(profile_name)
|
300
|
+
if not profile:
|
301
|
+
raise ValueError(f"LLM profile '{profile_name}' not found in config: {llm_section}")
|
302
|
+
if "provider" not in profile:
|
303
|
+
raise ValueError(f"'provider' missing in LLM profile '{profile_name}': {profile}")
|
304
|
+
return profile
|
305
|
+
|
306
|
+
@property
|
307
|
+
def llm_profile_name(self) -> str:
|
308
|
+
"""Returns the name of the LLM profile being used."""
|
309
|
+
if self._llm_profile_name is None:
|
310
|
+
raise RuntimeError("LLM profile name accessed before initialization or after failure.")
|
311
|
+
return self._llm_profile_name
|
312
|
+
|
313
|
+
@property
|
314
|
+
def slash_commands(self):
|
315
|
+
from swarm.core.slash_commands import slash_registry
|
316
|
+
return slash_registry
|
317
|
+
|
318
|
+
def get_llm_profile(self, profile_name: str) -> dict:
|
319
|
+
"""Returns the LLM profile dict for the given profile name from config, or empty dict if not found.
|
320
|
+
Supports both llm.profiles and direct llm keys for backward compatibility."""
|
321
|
+
llm_section = self.config.get("llm", {})
|
322
|
+
if "profiles" in llm_section:
|
323
|
+
return llm_section["profiles"].get(profile_name, {})
|
324
|
+
return llm_section.get(profile_name, {})
|
325
|
+
|
326
|
+
@property
|
327
|
+
def should_output_markdown(self) -> bool:
|
328
|
+
"""
|
329
|
+
Determines if markdown output should be used for this blueprint.
|
330
|
+
Priority: blueprint config > global config > False
|
331
|
+
"""
|
332
|
+
settings = self._config.get("settings", {}) if self._config else {}
|
333
|
+
bp_settings = self._config.get("blueprints", {}).get(self.blueprint_id, {}) if self._config else {}
|
334
|
+
if "output_markdown" in bp_settings:
|
335
|
+
return bool(bp_settings["output_markdown"])
|
336
|
+
if "default_markdown_output" in settings:
|
337
|
+
return bool(settings["default_markdown_output"])
|
338
|
+
return False
|
339
|
+
|
340
|
+
def _get_model_instance(self, profile_name: str):
|
341
|
+
"""Retrieves or creates an LLM Model instance, respecting LITELLM_MODEL/DEFAULT_LLM if set."""
|
342
|
+
if not hasattr(self, '_model_instance_cache'):
|
343
|
+
self._model_instance_cache = {}
|
344
|
+
if not hasattr(self, '_openai_client_cache'):
|
345
|
+
self._openai_client_cache = {}
|
346
|
+
if profile_name in self._model_instance_cache:
|
347
|
+
return self._model_instance_cache[profile_name]
|
348
|
+
profile_data = self.get_llm_profile(profile_name)
|
349
|
+
import os
|
350
|
+
model_name = os.getenv("LITELLM_MODEL") or os.getenv("DEFAULT_LLM") or profile_data.get("model") or "gpt-3.5-turbo"
|
351
|
+
openai_kwargs = {}
|
352
|
+
if "base_url" in profile_data:
|
353
|
+
openai_kwargs["base_url"] = profile_data["base_url"]
|
354
|
+
if "api_key" in profile_data:
|
355
|
+
openai_kwargs["api_key"] = profile_data["api_key"]
|
356
|
+
from openai import AsyncOpenAI
|
357
|
+
from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel
|
358
|
+
client_cache_key = f"{model_name}:{openai_kwargs.get('base_url','')}:key={bool(openai_kwargs.get('api_key'))}"
|
359
|
+
if client_cache_key not in self._openai_client_cache:
|
360
|
+
try:
|
361
|
+
self._openai_client_cache[client_cache_key] = AsyncOpenAI(**openai_kwargs)
|
362
|
+
except Exception as e:
|
363
|
+
raise ValueError(f"Failed to init client: {e}") from e
|
364
|
+
client = self._openai_client_cache[client_cache_key]
|
365
|
+
try:
|
366
|
+
model_instance = OpenAIChatCompletionsModel(model=model_name, openai_client=client)
|
367
|
+
self._model_instance_cache[profile_name] = model_instance
|
368
|
+
return model_instance
|
369
|
+
except Exception as e:
|
370
|
+
raise ValueError(f"Failed to init LLM: {e}") from e
|
371
|
+
|
372
|
+
def make_agent(self, name, instructions, tools, mcp_servers=None, **kwargs):
|
373
|
+
"""Factory for creating an Agent with the correct model instance from framework config."""
|
374
|
+
from agents import Agent # Ensure Agent is always in scope
|
375
|
+
model_instance = self._get_model_instance(self.config.get("llm_profile", "default"))
|
376
|
+
return Agent(
|
377
|
+
name=name,
|
378
|
+
model=model_instance,
|
379
|
+
instructions=instructions,
|
380
|
+
tools=tools,
|
381
|
+
mcp_servers=mcp_servers or [],
|
382
|
+
**kwargs
|
383
|
+
)
|
384
|
+
|
385
|
+
@abstractmethod
|
386
|
+
async def run(self, messages: List[Dict[str, Any]], **kwargs: Any) -> AsyncGenerator[Dict[str, Any], None]:
|
387
|
+
"""
|
388
|
+
The main execution method for the blueprint.
|
389
|
+
"""
|
390
|
+
import os
|
391
|
+
import pprint
|
392
|
+
logger.debug("ENVIRONMENT DUMP BEFORE MODEL CALL:")
|
393
|
+
pprint.pprint(dict(os.environ))
|
394
|
+
raise NotImplementedError("Subclasses must implement the 'run' method.")
|
395
|
+
yield {}
|
@@ -0,0 +1,128 @@
|
|
1
|
+
import os
|
2
|
+
import importlib
|
3
|
+
import importlib.util
|
4
|
+
import inspect
|
5
|
+
import logging # Ensure logging is imported
|
6
|
+
import sys
|
7
|
+
from typing import Dict, Type, Any
|
8
|
+
from pathlib import Path
|
9
|
+
|
10
|
+
# *** Define logger EARLIER ***
|
11
|
+
logger = logging.getLogger(__name__)
|
12
|
+
|
13
|
+
# *** Import the ACTUAL BlueprintBase from the likely correct path ***
|
14
|
+
try:
|
15
|
+
# Adjust this path if BlueprintBase lives elsewhere
|
16
|
+
from swarm.core.blueprint_base import BlueprintBase
|
17
|
+
except ImportError:
|
18
|
+
# This logger call is now safe
|
19
|
+
logger.error("Failed to import BlueprintBase from swarm.core.blueprint_base. Using placeholder.", exc_info=True)
|
20
|
+
class BlueprintBase: # Fallback placeholder
|
21
|
+
metadata: Dict[str, Any] = {}
|
22
|
+
def __init__(self, *args, **kwargs): pass
|
23
|
+
async def run(self, *args, **kwargs): pass
|
24
|
+
|
25
|
+
|
26
|
+
class BlueprintLoadError(Exception):
|
27
|
+
"""Custom exception for errors during blueprint loading."""
|
28
|
+
pass
|
29
|
+
|
30
|
+
def _get_blueprint_name_from_dir(dir_name: str) -> str:
|
31
|
+
"""Converts directory name (e.g., 'blueprint_my_agent') to blueprint name (e.g., 'my_agent')."""
|
32
|
+
prefix = "blueprint_"
|
33
|
+
if dir_name.startswith(prefix):
|
34
|
+
return dir_name[len(prefix):]
|
35
|
+
return dir_name
|
36
|
+
|
37
|
+
def discover_blueprints(blueprint_dir: str) -> Dict[str, Type[BlueprintBase]]:
|
38
|
+
"""
|
39
|
+
Discovers blueprints (subclasses of BlueprintBase) by looking for
|
40
|
+
'blueprint_{name}.py' files within subdirectories of the given blueprint directory.
|
41
|
+
|
42
|
+
Args:
|
43
|
+
blueprint_dir: The path to the directory containing blueprint subdirectories.
|
44
|
+
|
45
|
+
Returns:
|
46
|
+
A dictionary mapping blueprint names to their corresponding class objects.
|
47
|
+
"""
|
48
|
+
logger.info(f"Starting blueprint discovery in directory: {blueprint_dir}")
|
49
|
+
blueprints: Dict[str, Type[BlueprintBase]] = {}
|
50
|
+
base_dir = Path(blueprint_dir).resolve()
|
51
|
+
|
52
|
+
if not base_dir.is_dir():
|
53
|
+
logger.error(f"Blueprint directory not found or is not a directory: {base_dir}")
|
54
|
+
return blueprints
|
55
|
+
|
56
|
+
# Iterate over items inside the base blueprint directory
|
57
|
+
for subdir in base_dir.iterdir():
|
58
|
+
if not subdir.is_dir():
|
59
|
+
continue # Skip files directly under blueprints/
|
60
|
+
|
61
|
+
# Use directory name as blueprint name (e.g., 'echocraft')
|
62
|
+
blueprint_name = subdir.name
|
63
|
+
logger.debug(f"Processing potential blueprint '{blueprint_name}' in directory: {subdir.name}")
|
64
|
+
|
65
|
+
# Look for the specific .py file, e.g., blueprint_echocraft.py
|
66
|
+
py_file_name = f"blueprint_{blueprint_name}.py"
|
67
|
+
py_file_path = subdir / py_file_name
|
68
|
+
|
69
|
+
if not py_file_path.is_file():
|
70
|
+
# Also check for just {blueprint_name}.py if that's a convention
|
71
|
+
alt_py_file_name = f"{blueprint_name}.py"
|
72
|
+
alt_py_file_path = subdir / alt_py_file_name
|
73
|
+
if alt_py_file_path.is_file():
|
74
|
+
py_file_path = alt_py_file_path # Use the alternative path
|
75
|
+
py_file_name = alt_py_file_name
|
76
|
+
logger.debug(f"Found alternative blueprint file: {py_file_name}")
|
77
|
+
else:
|
78
|
+
logger.warning(f"Skipping directory '{subdir.name}': Neither '{py_file_name}' nor '{alt_py_file_name}' found.")
|
79
|
+
continue
|
80
|
+
|
81
|
+
|
82
|
+
# Construct module import path, e.g., blueprints.echocraft.blueprint_echocraft
|
83
|
+
if py_file_path.name.startswith('blueprint_gatcha'):
|
84
|
+
module_import_path = f"swarm.blueprints.gatcha.{py_file_path.stem}"
|
85
|
+
elif py_file_path.name.startswith('blueprint_'):
|
86
|
+
module_import_path = f"swarm.blueprints.{subdir.name}.{py_file_path.stem}"
|
87
|
+
else:
|
88
|
+
continue
|
89
|
+
|
90
|
+
try:
|
91
|
+
# Ensure parent directory is in path
|
92
|
+
parent_dir = str(base_dir.parent)
|
93
|
+
if parent_dir not in sys.path:
|
94
|
+
logger.debug(f"Adding '{parent_dir}' to sys.path for blueprint discovery.")
|
95
|
+
sys.path.insert(0, parent_dir)
|
96
|
+
|
97
|
+
# Create module spec from file path
|
98
|
+
module_spec = importlib.util.spec_from_file_location(module_import_path, py_file_path)
|
99
|
+
|
100
|
+
if module_spec and module_spec.loader:
|
101
|
+
module = importlib.util.module_from_spec(module_spec)
|
102
|
+
sys.modules[module_import_path] = module
|
103
|
+
module_spec.loader.exec_module(module)
|
104
|
+
logger.debug(f"Successfully loaded module: {module_import_path}")
|
105
|
+
|
106
|
+
found_bp_class = None
|
107
|
+
for name, obj in inspect.getmembers(module):
|
108
|
+
if inspect.isclass(obj) and obj.__module__ == module_import_path and issubclass(obj, BlueprintBase) and obj is not BlueprintBase:
|
109
|
+
if found_bp_class:
|
110
|
+
logger.warning(f"Multiple BlueprintBase subclasses found in {py_file_name}. Using the first: {found_bp_class.__name__}.")
|
111
|
+
else:
|
112
|
+
logger.debug(f"Found Blueprint class '{name}' in module '{module_import_path}'")
|
113
|
+
found_bp_class = obj
|
114
|
+
blueprints[blueprint_name] = found_bp_class
|
115
|
+
# break
|
116
|
+
|
117
|
+
if not found_bp_class:
|
118
|
+
logger.warning(f"No BlueprintBase subclass found directly defined in module: {module_import_path}")
|
119
|
+
else:
|
120
|
+
logger.warning(f"Could not create module spec for {py_file_path}")
|
121
|
+
|
122
|
+
except Exception as e:
|
123
|
+
logger.error(f"Error processing blueprint file '{py_file_path}': {e}", exc_info=True)
|
124
|
+
if module_import_path in sys.modules:
|
125
|
+
del sys.modules[module_import_path]
|
126
|
+
|
127
|
+
logger.info(f"Blueprint discovery complete. Found: {list(blueprints.keys())}")
|
128
|
+
return blueprints
|
@@ -0,0 +1,59 @@
|
|
1
|
+
import sys
|
2
|
+
import traceback
|
3
|
+
import types
|
4
|
+
from typing import AsyncGenerator
|
5
|
+
import inspect
|
6
|
+
|
7
|
+
from .blueprint_base import Spinner
|
8
|
+
|
9
|
+
class BlueprintRunner:
|
10
|
+
@staticmethod
|
11
|
+
async def run_agent(agent, instruction, filter_llm_function_calls=True, spinner_enabled=True) -> AsyncGenerator[dict, None]:
|
12
|
+
"""
|
13
|
+
Runs the agent using Runner.run as an async generator or coroutine, with spinner and error handling.
|
14
|
+
Filters out LLM function call outputs if requested.
|
15
|
+
Handles both coroutine and async generator return types.
|
16
|
+
"""
|
17
|
+
from agents import Runner
|
18
|
+
# Only enable spinner if spinner_enabled is True and not in non-interactive mode
|
19
|
+
# (i.e., only if show_intermediate is True)
|
20
|
+
spinner = None
|
21
|
+
if spinner_enabled:
|
22
|
+
# Check for a marker in instruction or a kwarg to disable spinner in non-interactive
|
23
|
+
frame = inspect.currentframe()
|
24
|
+
show_intermediate = False
|
25
|
+
while frame:
|
26
|
+
if 'kwargs' in frame.f_locals and isinstance(frame.f_locals['kwargs'], dict):
|
27
|
+
show_intermediate = frame.f_locals['kwargs'].get('show_intermediate', False)
|
28
|
+
break
|
29
|
+
frame = frame.f_back
|
30
|
+
if show_intermediate:
|
31
|
+
spinner = Spinner()
|
32
|
+
try:
|
33
|
+
if spinner:
|
34
|
+
spinner.start()
|
35
|
+
result = await Runner.run(agent, instruction)
|
36
|
+
# If result is an async generator, iterate over it
|
37
|
+
if isinstance(result, types.AsyncGeneratorType):
|
38
|
+
async for chunk in result:
|
39
|
+
if filter_llm_function_calls:
|
40
|
+
content = chunk.get("content")
|
41
|
+
if content and ("function call" in content or "args" in content):
|
42
|
+
continue
|
43
|
+
yield chunk
|
44
|
+
elif isinstance(result, (list, dict)):
|
45
|
+
# If it's a list of chunks or a single chunk, yield directly
|
46
|
+
if isinstance(result, list):
|
47
|
+
for chunk in result:
|
48
|
+
yield chunk
|
49
|
+
else:
|
50
|
+
yield result
|
51
|
+
elif result is not None:
|
52
|
+
# Fallback: yield as a single chunk
|
53
|
+
yield {"messages": [{"role": "assistant", "content": str(result)}]}
|
54
|
+
except Exception as e:
|
55
|
+
tb = traceback.format_exc()
|
56
|
+
yield {"messages": [{"role": "assistant", "content": f"Error: {e}\n{tb}"}]}
|
57
|
+
finally:
|
58
|
+
if spinner:
|
59
|
+
spinner.stop()
|
@@ -0,0 +1,17 @@
|
|
1
|
+
"""
|
2
|
+
Utility functions for blueprint management.
|
3
|
+
"""
|
4
|
+
|
5
|
+
def filter_blueprints(all_blueprints: dict, allowed_blueprints_str: str) -> dict:
|
6
|
+
"""
|
7
|
+
Filters the given blueprints dictionary using a comma-separated string of allowed blueprint keys.
|
8
|
+
|
9
|
+
Args:
|
10
|
+
all_blueprints (dict): A dictionary containing all discovered blueprints.
|
11
|
+
allowed_blueprints_str (str): A comma-separated string of allowed blueprint keys.
|
12
|
+
|
13
|
+
Returns:
|
14
|
+
dict: A dictionary containing only the blueprints whose keys are present in the allowed list.
|
15
|
+
"""
|
16
|
+
allowed_list = [bp.strip() for bp in allowed_blueprints_str.split(",")]
|
17
|
+
return {k: v for k, v in all_blueprints.items() if k in allowed_list}
|