flock-core 0.5.0b1__py3-none-any.whl → 0.5.0b3__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.

Potentially problematic release.


This version of flock-core might be problematic. Click here for more details.

Files changed (45) hide show
  1. flock/cli/manage_agents.py +3 -3
  2. flock/components/evaluation/declarative_evaluation_component.py +10 -10
  3. flock/components/routing/conditional_routing_component.py +7 -6
  4. flock/components/routing/default_routing_component.py +3 -3
  5. flock/components/routing/llm_routing_component.py +24 -26
  6. flock/components/utility/memory_utility_component.py +3 -3
  7. flock/components/utility/metrics_utility_component.py +11 -11
  8. flock/components/utility/output_utility_component.py +11 -9
  9. flock/core/__init__.py +24 -10
  10. flock/core/agent/flock_agent_components.py +16 -16
  11. flock/core/agent/flock_agent_integration.py +88 -29
  12. flock/core/agent/flock_agent_serialization.py +23 -20
  13. flock/core/api/endpoints.py +1 -1
  14. flock/core/component/__init__.py +7 -7
  15. flock/core/component/{evaluation_component_base.py → evaluation_component.py} +2 -2
  16. flock/core/component/{routing_component_base.py → routing_component.py} +3 -4
  17. flock/core/component/{utility_component_base.py → utility_component.py} +3 -3
  18. flock/core/flock.py +7 -7
  19. flock/core/flock_agent.py +68 -38
  20. flock/core/flock_factory.py +21 -18
  21. flock/core/flock_server_manager.py +8 -8
  22. flock/core/mcp/flock_mcp_server.py +11 -11
  23. flock/core/mcp/{flock_mcp_tool_base.py → flock_mcp_tool.py} +2 -2
  24. flock/core/mcp/mcp_client.py +9 -9
  25. flock/core/mcp/mcp_client_manager.py +9 -9
  26. flock/core/mcp/mcp_config.py +24 -24
  27. flock/core/orchestration/flock_execution.py +3 -3
  28. flock/core/orchestration/flock_initialization.py +6 -6
  29. flock/core/orchestration/flock_server_manager.py +8 -6
  30. flock/core/registry/__init__.py +16 -10
  31. flock/core/registry/registry_hub.py +7 -4
  32. flock/core/registry/server_registry.py +6 -6
  33. flock/core/serialization/flock_serializer.py +3 -2
  34. flock/mcp/servers/sse/flock_sse_server.py +10 -10
  35. flock/mcp/servers/stdio/flock_stdio_server.py +10 -10
  36. flock/mcp/servers/streamable_http/flock_streamable_http_server.py +10 -10
  37. flock/mcp/servers/websockets/flock_websocket_server.py +10 -10
  38. flock/workflow/activities.py +10 -10
  39. {flock_core-0.5.0b1.dist-info → flock_core-0.5.0b3.dist-info}/METADATA +1 -1
  40. {flock_core-0.5.0b1.dist-info → flock_core-0.5.0b3.dist-info}/RECORD +43 -45
  41. flock/core/flock_registry.py.backup +0 -688
  42. flock/workflow/activities_unified.py +0 -230
  43. {flock_core-0.5.0b1.dist-info → flock_core-0.5.0b3.dist-info}/WHEEL +0 -0
  44. {flock_core-0.5.0b1.dist-info → flock_core-0.5.0b3.dist-info}/entry_points.txt +0 -0
  45. {flock_core-0.5.0b1.dist-info → flock_core-0.5.0b3.dist-info}/licenses/LICENSE +0 -0
@@ -1,688 +0,0 @@
1
- # src/flock/core/flock_registry.py
2
- """Centralized registry for managing Agents, Callables, Types, and Component Classes
3
- within the Flock framework to support dynamic lookup and serialization.
4
- """
5
-
6
- from __future__ import annotations # Add this at the very top
7
-
8
- import builtins
9
- import importlib
10
- import inspect
11
- import os
12
- import pkgutil
13
- import sys
14
- from collections.abc import Callable, Mapping, Sequence
15
- from dataclasses import is_dataclass
16
- from typing import ( # Add TYPE_CHECKING
17
- TYPE_CHECKING,
18
- Any,
19
- Literal,
20
- Optional,
21
- TypeVar,
22
- Union,
23
- overload,
24
- )
25
-
26
- from pydantic import BaseModel
27
-
28
- if TYPE_CHECKING:
29
- from flock.core.flock_agent import (
30
- FlockAgent, # Import only for type checking
31
- )
32
- from flock.core.mcp.flock_mcp_server import FlockMCPServerBase
33
- from flock.core.component.agent_component_base import AgentComponent
34
-
35
- COMPONENT_BASE_TYPES = (AgentComponent,)
36
-
37
- IS_COMPONENT_CHECK_ENABLED = True
38
- else:
39
- # Define dummy types or skip check if not type checking
40
- FlockAgent = Any # Or define a dummy class
41
- COMPONENT_BASE_TYPES = ()
42
- IS_COMPONENT_CHECK_ENABLED = False
43
-
44
- # Fallback if core types aren't available during setup
45
- from flock.core.logging.logging import get_logger
46
-
47
- logger = get_logger("registry")
48
- T = TypeVar("T")
49
- ClassType = TypeVar("ClassType", bound=type)
50
- FuncType = TypeVar("FuncType", bound=Callable)
51
- ConfigType = TypeVar("ConfigType", bound=BaseModel)
52
- _COMPONENT_CONFIG_MAP: dict[type[BaseModel], type[any]] = {}
53
-
54
-
55
- class FlockRegistry:
56
- """Singleton registry for Agents, Callables (functions/methods) and MCP Servers.
57
-
58
- Types (Pydantic/Dataclasses used in signatures), and Component Classes
59
- (Modules, Evaluators, Routers).
60
- """
61
-
62
- _instance = None
63
-
64
- _agents: dict[str, FlockAgent]
65
- _servers: dict[str, FlockMCPServerBase]
66
- _callables: dict[str, Callable]
67
- _types: dict[str, type]
68
- _components: dict[str, type] # For Module, Evaluator, Router classes
69
-
70
- def __new__(cls):
71
- if cls._instance is None:
72
- cls._instance = super().__new__(cls)
73
- cls._instance._initialize()
74
- # logger.info("FlockRegistry instance created.")
75
- return cls._instance
76
-
77
- def _initialize(self):
78
- """Initialize the internal dictionaries."""
79
- self._agents = {}
80
- self._servers = {}
81
- self._callables = {}
82
- self._types = {}
83
- self._components = {}
84
- # logger.debug("FlockRegistry initialized internal stores.")
85
- # Auto-register core Python types
86
- self._register_core_types()
87
-
88
- def _register_core_types(self):
89
- """Registers common built-in and typing types."""
90
- core_types = [
91
- str,
92
- int,
93
- float,
94
- bool,
95
- list,
96
- dict,
97
- tuple,
98
- set,
99
- Any,
100
- Mapping,
101
- Sequence,
102
- TypeVar,
103
- Literal,
104
- Optional,
105
- Union, # Common typing generics
106
- ]
107
- for t in core_types:
108
- try:
109
- self.register_type(t)
110
- except Exception as e:
111
- logger.error(f"Failed to auto-register core type {t}: {e}")
112
-
113
- @staticmethod
114
- def register_config_component_pair(
115
- config_cls: type[ConfigType], component_cls: type[ClassType]
116
- ):
117
- """Explicitly registers the mapping between a config and component class."""
118
- # Component config validation can be added here if needed
119
- # Add more checks if needed (e.g., component_cls inherits from Module/Router/Evaluator)
120
-
121
- if (
122
- config_cls in _COMPONENT_CONFIG_MAP
123
- and _COMPONENT_CONFIG_MAP[config_cls] != component_cls
124
- ):
125
- logger.warning(
126
- f"Config class {config_cls.__name__} already mapped to {_COMPONENT_CONFIG_MAP[config_cls].__name__}. Overwriting with {component_cls.__name__}."
127
- )
128
-
129
- _COMPONENT_CONFIG_MAP[config_cls] = component_cls
130
- logger.debug(
131
- f"Registered config mapping: {config_cls.__name__} -> {component_cls.__name__}"
132
- )
133
-
134
- @staticmethod
135
- def get_component_class_for_config(
136
- config_cls: type[ConfigType],
137
- ) -> type[ClassType] | None:
138
- """Looks up the Component Class associated with a Config Class."""
139
- return _COMPONENT_CONFIG_MAP.get(config_cls)
140
-
141
- # --- Path String Generation ---
142
- @staticmethod
143
- def _get_path_string(obj: Callable | type) -> str | None:
144
- """Generates a unique path string 'module.ClassName' or 'module.function_name'."""
145
- try:
146
- module = obj.__module__
147
- name = obj.__name__
148
- if module == "builtins":
149
- return name
150
- # Check if it's nested (basic check, might not cover all edge cases)
151
- if "." in name and hasattr(sys.modules[module], name.split(".")[0]):
152
- # Likely a nested class/method - serialization might need custom handling or pickle
153
- logger.warning(
154
- f"Object {name} appears nested in {module}. Path string might be ambiguous."
155
- )
156
- return f"{module}.{name}"
157
- except AttributeError:
158
- logger.warning(f"Could not determine module/name for object: {obj}")
159
- return None
160
-
161
- # --- Server Registration ---
162
- def register_server(self, server: FlockMCPServerBase) -> None:
163
- """Registers a flock mcp server by its name."""
164
- if not hasattr(server.config, "name") or not server.config.name:
165
- logger.error(
166
- "Attempted to register a server without a valid 'name' attribute."
167
- )
168
- return
169
- if (
170
- server.config.name in self._servers
171
- and self._servers[server.config.name] != server
172
- ):
173
- logger.warning(
174
- f"Server '{server.config.name}' already registered. Overwriting."
175
- )
176
- self._servers[server.config.name] = server
177
- logger.debug(f"Registered server: {server.config.name}")
178
-
179
- def get_server(self, name: str) -> FlockMCPServerBase | None:
180
- """Retrieves a registered FlockMCPServer instance by name."""
181
- server = self._servers.get(name)
182
- if not server:
183
- logger.warning(f"Server '{name}' not found in registry.")
184
- return server
185
-
186
- def get_all_server_names(self) -> list[str]:
187
- """Returns a list of names for all registered servers."""
188
- return list(self._servers.keys())
189
-
190
- # --- Agent Registration ---
191
- def register_agent(self, agent: FlockAgent, *, force: bool = False) -> None:
192
- """Registers a FlockAgent instance by its name.
193
-
194
- Args:
195
- agent: The agent instance to register.
196
- force: If True, allow overwriting an existing **different** agent registered under the same name.
197
- If False and a conflicting registration exists, a ValueError is raised.
198
- """
199
- if not hasattr(agent, "name") or not agent.name:
200
- logger.error(
201
- "Attempted to register an agent without a valid 'name' attribute."
202
- )
203
- return
204
-
205
- if agent.name in self._agents and self._agents[agent.name] is not agent:
206
- # Same agent already registered → silently ignore; different instance → error/force.
207
- if not force:
208
- raise ValueError(
209
- f"Agent '{agent.name}' already registered with a different instance. "
210
- "Pass force=True to overwrite the existing registration."
211
- )
212
- logger.warning(
213
- f"Overwriting existing agent '{agent.name}' registration due to force=True."
214
- )
215
-
216
- self._agents[agent.name] = agent
217
- logger.debug(f"Registered agent: {agent.name}")
218
-
219
- def get_agent(self, name: str) -> FlockAgent | None:
220
- """Retrieves a registered FlockAgent instance by name."""
221
- agent = self._agents.get(name)
222
- if not agent:
223
- logger.warning(f"Agent '{name}' not found in registry.")
224
- return agent
225
-
226
- def get_all_agent_names(self) -> list[str]:
227
- """Returns a list of names of all registered agents."""
228
- return list(self._agents.keys())
229
-
230
- # --- Callable Registration ---
231
- def register_callable(
232
- self, func: Callable, name: str | None = None
233
- ) -> str | None:
234
- """Registers a callable (function/method). Returns its path string identifier."""
235
- path_str = name or self._get_path_string(func)
236
- if path_str:
237
- if (
238
- path_str in self._callables
239
- and self._callables[path_str] != func
240
- ):
241
- logger.warning(
242
- f"Callable '{path_str}' already registered with a different function. Overwriting."
243
- )
244
- self._callables[path_str] = func
245
- logger.debug(f"Registered callable: '{path_str}' ({func.__name__})")
246
- return path_str
247
- logger.warning(
248
- f"Could not register callable {func.__name__}: Unable to determine path string"
249
- )
250
- return None
251
-
252
- def get_callable(self, name_or_path: str) -> Callable:
253
- """Retrieves a callable by its registered name or full path string.
254
- Attempts dynamic import if not found directly. Prioritizes exact match,
255
- then searches for matches ending with '.{name}'.
256
- """
257
- # 1. Try exact match first (covers full paths and simple names if registered that way)
258
- if name_or_path in self._callables:
259
- logger.debug(
260
- f"Found callable '{name_or_path}' directly in registry."
261
- )
262
- return self._callables[name_or_path]
263
-
264
- # 2. If not found, and it looks like a simple name, search registered paths
265
- if "." not in name_or_path:
266
- matches = []
267
- for path_str, func in self._callables.items():
268
- # Check if path ends with ".{simple_name}" or exactly matches simple_name
269
- if path_str == name_or_path or path_str.endswith(
270
- f".{name_or_path}"
271
- ):
272
- matches.append(func)
273
-
274
- if len(matches) == 1:
275
- logger.debug(
276
- f"Found unique callable for simple name '{name_or_path}' via path '{self.get_callable_path_string(matches[0])}'."
277
- )
278
- return matches[0]
279
- elif len(matches) > 1:
280
- # Ambiguous simple name - require full path
281
- found_paths = [
282
- self.get_callable_path_string(f) for f in matches
283
- ]
284
- logger.error(
285
- f"Ambiguous callable name '{name_or_path}'. Found matches: {found_paths}. Use full path string for lookup."
286
- )
287
- raise KeyError(
288
- f"Ambiguous callable name '{name_or_path}'. Use full path string."
289
- )
290
- # else: Not found by simple name search in registry, proceed to dynamic import
291
-
292
- # 3. Attempt dynamic import if it looks like a full path
293
- if "." in name_or_path:
294
- logger.debug(
295
- f"Callable '{name_or_path}' not in registry cache, attempting dynamic import."
296
- )
297
- try:
298
- module_name, func_name = name_or_path.rsplit(".", 1)
299
- module = importlib.import_module(module_name)
300
- func = getattr(module, func_name)
301
- if callable(func):
302
- self.register_callable(
303
- func, name_or_path
304
- ) # Cache dynamically imported
305
- logger.info(
306
- f"Successfully imported and registered module callable '{name_or_path}'"
307
- )
308
- return func
309
- else:
310
- raise TypeError(
311
- f"Dynamically imported object '{name_or_path}' is not callable."
312
- )
313
- except (ImportError, AttributeError, TypeError) as e:
314
- logger.error(
315
- f"Failed to dynamically load/find callable '{name_or_path}': {e}",
316
- exc_info=False,
317
- )
318
- # Fall through to raise KeyError
319
- # 4. Handle built-ins if not found yet (might be redundant if simple name check worked)
320
- elif name_or_path in builtins.__dict__:
321
- func = builtins.__dict__[name_or_path]
322
- if callable(func):
323
- self.register_callable(func, name_or_path) # Cache it
324
- logger.info(
325
- f"Found and registered built-in callable '{name_or_path}'"
326
- )
327
- return func
328
-
329
- # 5. Final failure
330
- logger.error(
331
- f"Callable '{name_or_path}' not found in registry or via import."
332
- )
333
- raise KeyError(f"Callable '{name_or_path}' not found.")
334
-
335
- def get_callable_path_string(self, func: Callable) -> str | None:
336
- """Gets the path string for a callable, registering it if necessary."""
337
- # First try to find by direct identity
338
- for path_str, registered_func in self._callables.items():
339
- if func == registered_func:
340
- logger.debug(
341
- f"Found existing path string for callable: '{path_str}'"
342
- )
343
- return path_str
344
-
345
- # If not found by identity, generate path, register, and return
346
- path_str = self.register_callable(func)
347
- if path_str:
348
- logger.debug(
349
- f"Generated and registered new path string for callable: '{path_str}'"
350
- )
351
- else:
352
- logger.warning(
353
- f"Failed to generate path string for callable {func.__name__}"
354
- )
355
-
356
- return path_str
357
-
358
- # --- Type Registration ---
359
- def register_type(
360
- self, type_obj: type, name: str | None = None
361
- ) -> str | None:
362
- """Registers a class/type (Pydantic, Dataclass, etc.) used in signatures."""
363
- type_name = name or type_obj.__name__
364
- if type_name:
365
- if type_name in self._types and self._types[type_name] != type_obj:
366
- logger.warning(
367
- f"Type '{type_name}' already registered. Overwriting."
368
- )
369
- self._types[type_name] = type_obj
370
- logger.debug(f"Registered type: {type_name}")
371
- return type_name
372
- return None
373
-
374
- def get_type(self, type_name: str) -> type:
375
- """Retrieves a registered type by its name."""
376
- if type_name in self._types:
377
- return self._types[type_name]
378
- else:
379
- # Consider adding dynamic import attempts for types if needed,
380
- # but explicit registration is generally safer for types.
381
- logger.warning(f"Type '{type_name}' not found in registry. Will attempt to build it from builtins.")
382
- raise KeyError(
383
- f"Type '{type_name}' not found. Ensure it is registered."
384
- )
385
-
386
- # --- Component Class Registration ---
387
- def register_component(
388
- self, component_class: type, name: str | None = None
389
- ) -> str | None:
390
- """Registers a component class (Module, Evaluator, Router)."""
391
- type_name = name or component_class.__name__
392
- if type_name:
393
- # Optional: Add check if it's a subclass of expected bases
394
- # if COMPONENT_BASE_TYPES and not issubclass(component_class, COMPONENT_BASE_TYPES):
395
- # logger.warning(f"Registering class '{type_name}' which is not a standard Flock component type.")
396
- if (
397
- type_name in self._components
398
- and self._components[type_name] != component_class
399
- ):
400
- logger.warning(
401
- f"Component class '{type_name}' already registered. Overwriting."
402
- )
403
- self._components[type_name] = component_class
404
- logger.debug(f"Registered component class: {type_name}")
405
- return type_name
406
- return None
407
-
408
- def get_component(self, type_name: str) -> type:
409
- """Retrieves a component class by its type name."""
410
- if type_name in self._components:
411
- return self._components[type_name]
412
- else:
413
- # Dynamic import attempts similar to get_callable could be added here if desired,
414
- # targeting likely module locations based on type_name conventions.
415
- logger.error(
416
- f"Component class '{type_name}' not found in registry."
417
- )
418
- raise KeyError(
419
- f"Component class '{type_name}' not found. Ensure it is registered."
420
- )
421
-
422
- def get_component_type_name(self, component_class: type) -> str | None:
423
- """Gets the type name for a component class, registering it if necessary."""
424
- for type_name, registered_class in self._components.items():
425
- if component_class == registered_class:
426
- return type_name
427
- # If not found, register using class name and return
428
- return self.register_component(component_class)
429
-
430
- # --- Auto-Registration ---
431
- def register_module_components(self, module_or_path: Any) -> None:
432
- """Scans a module (object or path string) and automatically registers.
433
-
434
- - Functions as callables.
435
- - Pydantic Models and Dataclasses as types.
436
- - Subclasses of FlockModule, FlockEvaluator, FlockRouter as components.
437
- """
438
- try:
439
- if isinstance(module_or_path, str):
440
- module = importlib.import_module(module_or_path)
441
- elif inspect.ismodule(module_or_path):
442
- module = module_or_path
443
- else:
444
- logger.error(
445
- f"Invalid input for auto-registration: {module_or_path}. Must be module object or path string."
446
- )
447
- return
448
-
449
- logger.info(
450
- f"Auto-registering components from module: {module.__name__}"
451
- )
452
- registered_count = {"callable": 0, "type": 0, "component": 0}
453
-
454
- for name, obj in inspect.getmembers(module):
455
- if name.startswith("_"):
456
- continue # Skip private/internal
457
-
458
- # Register Functions as Callables
459
- if (
460
- inspect.isfunction(obj)
461
- and obj.__module__ == module.__name__
462
- ):
463
- if self.register_callable(obj):
464
- registered_count["callable"] += 1
465
-
466
- # Register Classes (Types and Components)
467
- elif inspect.isclass(obj) and obj.__module__ == module.__name__:
468
- is_component = False
469
- # Register as Component if subclass of base types
470
- if (
471
- COMPONENT_BASE_TYPES
472
- and issubclass(obj, COMPONENT_BASE_TYPES)
473
- and self.register_component(obj)
474
- ):
475
- registered_count["component"] += 1
476
- is_component = True # Mark as component
477
-
478
- # Register as Type if Pydantic Model or Dataclass
479
- # A component can also be a type used in signatures
480
- base_model_or_dataclass = isinstance(obj, type) and (
481
- issubclass(obj, BaseModel) or is_dataclass(obj)
482
- )
483
- if (
484
- base_model_or_dataclass
485
- and self.register_type(obj)
486
- and not is_component
487
- ):
488
- # Only increment type count if it wasn't already counted as component
489
- registered_count["type"] += 1
490
-
491
- logger.info(
492
- f"Auto-registration summary for {module.__name__}: "
493
- f"{registered_count['callable']} callables, "
494
- f"{registered_count['type']} types, "
495
- f"{registered_count['component']} components."
496
- )
497
-
498
- except Exception as e:
499
- logger.error(
500
- f"Error during auto-registration for {module_or_path}: {e}",
501
- exc_info=True,
502
- )
503
-
504
-
505
- # --- Initialize Singleton ---
506
- _registry_instance = FlockRegistry()
507
-
508
-
509
- # --- Convenience Access ---
510
- # Provide a function to easily get the singleton instance
511
- def get_registry() -> FlockRegistry:
512
- """Returns the singleton FlockRegistry instance."""
513
- return _registry_instance
514
-
515
-
516
- # Type hinting for decorators to preserve signature
517
- @overload
518
- def flock_component(cls: ClassType) -> ClassType: ... # Basic registration
519
-
520
-
521
- @overload
522
- def flock_component(
523
- *, name: str | None = None, config_class: type[ConfigType] | None = None
524
- ) -> Callable[[ClassType], ClassType]: ... # With options
525
-
526
-
527
- def flock_component(
528
- cls: ClassType | None = None,
529
- *,
530
- name: str | None = None,
531
- config_class: type[ConfigType] | None = None,
532
- ) -> Any:
533
- """Decorator to register a Flock Component class and optionally link its config class."""
534
- registry = get_registry()
535
-
536
- def decorator(inner_cls: ClassType) -> ClassType:
537
- if not inspect.isclass(inner_cls):
538
- raise TypeError("@flock_component can only decorate classes.")
539
-
540
- component_name = name or inner_cls.__name__
541
- registry.register_component(
542
- inner_cls, name=component_name
543
- ) # Register component by name
544
-
545
- # If config_class is provided, register the mapping
546
- if config_class:
547
- FlockRegistry.register_config_component_pair(
548
- config_class, inner_cls
549
- )
550
-
551
- return inner_cls
552
-
553
- if cls is None:
554
- # Called as @flock_component(name="...", config_class=...)
555
- return decorator
556
- else:
557
- # Called as @flock_component
558
- return decorator(cls)
559
-
560
-
561
- # Type hinting for decorators
562
- @overload
563
- def flock_tool(func: FuncType) -> FuncType: ...
564
-
565
-
566
- @overload
567
- def flock_tool(
568
- *, name: str | None = None
569
- ) -> Callable[[FuncType], FuncType]: ...
570
-
571
-
572
- def flock_tool(func: FuncType | None = None, *, name: str | None = None) -> Any:
573
- """Decorator to register a callable function/method as a Tool (or general callable).
574
-
575
- Usage:
576
- @flock_tool
577
- def my_web_search(query: str): ...
578
-
579
- @flock_tool(name="utils.calculate_pi")
580
- def compute_pi(): ...
581
- """
582
- registry = get_registry()
583
-
584
- def decorator(inner_func: FuncType) -> FuncType:
585
- if not callable(inner_func):
586
- raise TypeError("@flock_tool can only decorate callables.")
587
- # Let registry handle default name generation if None
588
- registry.register_callable(inner_func, name=name)
589
- return inner_func
590
-
591
- if func is None:
592
- # Called as @flock_tool(name="...")
593
- return decorator
594
- else:
595
- # Called as @flock_tool
596
- return decorator(func)
597
-
598
-
599
- # Alias for clarity if desired
600
- flock_callable = flock_tool
601
-
602
-
603
- @overload
604
- def flock_type(cls: ClassType) -> ClassType: ...
605
-
606
-
607
- @overload
608
- def flock_type(
609
- *, name: str | None = None
610
- ) -> Callable[[ClassType], ClassType]: ...
611
-
612
-
613
- def flock_type(cls: ClassType | None = None, *, name: str | None = None) -> Any:
614
- """Decorator to register a Type (Pydantic Model, Dataclass) used in signatures.
615
-
616
- Usage:
617
- @flock_type
618
- class MyDataModel(BaseModel): ...
619
-
620
- @flock_type(name="UserInput")
621
- @dataclass
622
- class UserQuery: ...
623
- """
624
- registry = get_registry()
625
-
626
- def decorator(inner_cls: ClassType) -> ClassType:
627
- if not inspect.isclass(inner_cls):
628
- raise TypeError("@flock_type can only decorate classes.")
629
- type_name = name or inner_cls.__name__
630
- registry.register_type(inner_cls, name=type_name)
631
- return inner_cls
632
-
633
- if cls is None:
634
- # Called as @flock_type(name="...")
635
- return decorator
636
- else:
637
- # Called as @flock_type
638
- return decorator(cls)
639
-
640
-
641
- # --- Auto-register known core components and tools ---
642
- def _auto_register_by_path(self):
643
- # List of base packages to scan for components and tools
644
- packages_to_scan = [
645
- "flock.tools",
646
- "flock.evaluators",
647
- "flock.modules",
648
- "flock.routers",
649
- ]
650
-
651
- for package_name in packages_to_scan:
652
- try:
653
- package_spec = importlib.util.find_spec(package_name)
654
- if package_spec and package_spec.origin:
655
- package_path_list = [os.path.dirname(package_spec.origin)]
656
- logger.info(f"Recursively scanning for modules in package: {package_name} (path: {package_path_list[0]})")
657
-
658
- # Use walk_packages to recursively find all modules
659
- for module_loader, module_name, is_pkg in pkgutil.walk_packages(
660
- path=package_path_list,
661
- prefix=package_name + ".", # Ensures module_name is fully qualified
662
- onerror=lambda name: logger.warning(f"Error importing module {name} during scan.")
663
- ):
664
- if not is_pkg and not module_name.split('.')[-1].startswith("_"):
665
- # We are interested in actual modules, not sub-packages themselves for registration
666
- # And also skip modules starting with underscore (e.g. __main__.py)
667
- try:
668
- logger.debug(f"Attempting to auto-register components from module: {module_name}")
669
- _registry_instance.register_module_components(module_name)
670
- except ImportError as e:
671
- logger.warning(
672
- f"Could not auto-register from {module_name}: Module not found or import error: {e}"
673
- )
674
- except Exception as e: # Catch other potential errors during registration
675
- logger.error(
676
- f"Unexpected error during auto-registration of {module_name}: {e}",
677
- exc_info=True
678
- )
679
- else:
680
- logger.warning(f"Could not find package spec for '{package_name}' to auto-register components/tools.")
681
- except Exception as e:
682
- logger.error(f"Error while trying to dynamically register from '{package_name}': {e}", exc_info=True)
683
-
684
- # Bootstrapping the registry
685
- # _auto_register_by_path() # Commented out or removed
686
-
687
- # Make the registration function public and rename it
688
- FlockRegistry.discover_and_register_components = _auto_register_by_path