llmling 0.0.1__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.
- llmling/__init__.py +115 -0
- llmling/client.py +548 -0
- llmling/config/__init__.py +32 -0
- llmling/config/loading.py +119 -0
- llmling/config/manager.py +145 -0
- llmling/config/models.py +284 -0
- llmling/config/validation.py +192 -0
- llmling/context/__init__.py +32 -0
- llmling/context/base.py +55 -0
- llmling/context/loaders/__init__.py +15 -0
- llmling/context/loaders/callable.py +61 -0
- llmling/context/loaders/cli.py +109 -0
- llmling/context/loaders/path.py +65 -0
- llmling/context/loaders/source.py +66 -0
- llmling/context/loaders/text.py +54 -0
- llmling/context/models.py +36 -0
- llmling/context/registry.py +53 -0
- llmling/core/__init__.py +0 -0
- llmling/core/exceptions.py +43 -0
- llmling/core/log.py +59 -0
- llmling/core/typedefs.py +31 -0
- llmling/core/utils.py +36 -0
- llmling/llm/__init__.py +0 -0
- llmling/llm/base.py +160 -0
- llmling/llm/providers/__init__.py +0 -0
- llmling/llm/providers/litellm.py +286 -0
- llmling/llm/registry.py +77 -0
- llmling/processors/__init__.py +87 -0
- llmling/processors/base.py +200 -0
- llmling/processors/implementations/__init__.py +0 -0
- llmling/processors/implementations/function.py +92 -0
- llmling/processors/implementations/template.py +58 -0
- llmling/processors/registry.py +381 -0
- llmling/py.typed +0 -0
- llmling/resources/system_tools.yml +21 -0
- llmling/resources/test.yml +178 -0
- llmling/resources/web_research.yml +28 -0
- llmling/task/__init__.py +71 -0
- llmling/task/concurrent.py +63 -0
- llmling/task/executor.py +308 -0
- llmling/task/manager.py +182 -0
- llmling/task/models.py +44 -0
- llmling/testing/__init__.py +4 -0
- llmling/testing/processors.py +40 -0
- llmling/testing/tools.py +38 -0
- llmling/testtest.py +112 -0
- llmling/tools/__init__.py +14 -0
- llmling/tools/actions.py +37 -0
- llmling/tools/base.py +197 -0
- llmling/tools/browser.py +159 -0
- llmling/tools/code.py +64 -0
- llmling/tools/exceptions.py +21 -0
- llmling/utils/__init__.py +1 -0
- llmling/utils/calling.py +74 -0
- llmling/utils/importing.py +69 -0
- llmling-0.0.1.dist-info/METADATA +146 -0
- llmling-0.0.1.dist-info/RECORD +59 -0
- llmling-0.0.1.dist-info/WHEEL +4 -0
- llmling-0.0.1.dist-info/licenses/LICENSE +22 -0
llmling/__init__.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from llmling.context import (
|
|
4
|
+
ContextLoader,
|
|
5
|
+
LoadedContext,
|
|
6
|
+
default_registry as context_registry,
|
|
7
|
+
)
|
|
8
|
+
from llmling.core.exceptions import (
|
|
9
|
+
LLMLingError,
|
|
10
|
+
ConfigError,
|
|
11
|
+
ContextError,
|
|
12
|
+
LoaderError,
|
|
13
|
+
ProcessorError,
|
|
14
|
+
LLMError,
|
|
15
|
+
TaskError,
|
|
16
|
+
)
|
|
17
|
+
from llmling.llm.registry import default_registry as llm_registry
|
|
18
|
+
from llmling.processors.registry import ProcessorRegistry
|
|
19
|
+
from llmling.task.executor import TaskExecutor
|
|
20
|
+
from llmling.task.manager import TaskManager
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__version__ = "0.0.1"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
# Core components
|
|
27
|
+
"ContextLoader",
|
|
28
|
+
"LoadedContext",
|
|
29
|
+
"ProcessorRegistry",
|
|
30
|
+
"TaskExecutor",
|
|
31
|
+
"TaskManager",
|
|
32
|
+
# Default registries
|
|
33
|
+
"context_registry",
|
|
34
|
+
"llm_registry",
|
|
35
|
+
# Exceptions
|
|
36
|
+
"LLMLingError",
|
|
37
|
+
"ConfigError",
|
|
38
|
+
"ContextError",
|
|
39
|
+
"LoaderError",
|
|
40
|
+
"ProcessorError",
|
|
41
|
+
"LLMError",
|
|
42
|
+
"TaskError",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
# llmling/
|
|
46
|
+
# ├── src/
|
|
47
|
+
# │ └── llmling/
|
|
48
|
+
# │ ├── __init__.py # Main package exports
|
|
49
|
+
# │ ├── cli.py # Command-line interface
|
|
50
|
+
# │ │
|
|
51
|
+
# │ ├── core/ # Core components
|
|
52
|
+
# │ │ ├── __init__.py
|
|
53
|
+
# │ │ ├── exceptions.py # Central exception hierarchy
|
|
54
|
+
# │ │ ├── log.py # Logging configuration
|
|
55
|
+
# │ │ └── types.py # Common type definitions
|
|
56
|
+
# │ │
|
|
57
|
+
# │ ├── config/ # Configuration management
|
|
58
|
+
# │ │ ├── __init__.py
|
|
59
|
+
# │ │ ├── models.py # Configuration models
|
|
60
|
+
# │ │ ├── manager.py # Configuration management
|
|
61
|
+
# │ │ └── validation.py # Configuration validation
|
|
62
|
+
# │ │
|
|
63
|
+
# │ ├── context/ # Context handling
|
|
64
|
+
# │ │ ├── __init__.py
|
|
65
|
+
# │ │ ├── base.py # Base context classes
|
|
66
|
+
# │ │ ├── registry.py # Context loader registry
|
|
67
|
+
# │ │ └── loaders/ # Context loaders
|
|
68
|
+
# │ │ ├── __init__.py
|
|
69
|
+
# │ │ ├── path.py
|
|
70
|
+
# │ │ ├── text.py
|
|
71
|
+
# │ │ ├── cli.py
|
|
72
|
+
# │ │ ├── source.py
|
|
73
|
+
# │ │ └── callable.py
|
|
74
|
+
# │ │
|
|
75
|
+
# │ ├── processors/ # Content processing
|
|
76
|
+
# │ │ ├── __init__.py
|
|
77
|
+
# │ │ ├── base.py # Base processor classes
|
|
78
|
+
# │ │ ├── registry.py # Processor registry
|
|
79
|
+
# │ │ └── implementations/ # Processor implementations
|
|
80
|
+
# │ │ ├── __init__.py
|
|
81
|
+
# │ │ ├── function.py
|
|
82
|
+
# │ │ └── template.py
|
|
83
|
+
# │ │
|
|
84
|
+
# │ ├── llm/ # LLM integration
|
|
85
|
+
# │ │ ├── __init__.py
|
|
86
|
+
# │ │ ├── base.py # Base LLM classes
|
|
87
|
+
# │ │ ├── registry.py # LLM provider registry
|
|
88
|
+
# │ │ └── providers/ # LLM providers
|
|
89
|
+
# │ │ ├── __init__.py
|
|
90
|
+
# │ │ └── litellm.py
|
|
91
|
+
# │ │
|
|
92
|
+
# │ ├── task/ # Task management
|
|
93
|
+
# │ │ ├── __init__.py
|
|
94
|
+
# │ │ ├── models.py # Task models
|
|
95
|
+
# │ │ ├── executor.py # Task execution
|
|
96
|
+
# │ │ ├── manager.py # Task management
|
|
97
|
+
# │ │ └── concurrent.py # Concurrent execution
|
|
98
|
+
# │ │
|
|
99
|
+
# │ └── utils/ # Utilities
|
|
100
|
+
# │ ├── __init__.py
|
|
101
|
+
# │ ├── importing.py # Import utilities
|
|
102
|
+
# │ └── calling.py # Callable utilities
|
|
103
|
+
# │
|
|
104
|
+
# ├── tests/ # Test suite
|
|
105
|
+
# │ ├── __init__.py
|
|
106
|
+
# │ ├── test_config.py
|
|
107
|
+
# │ ├── test_context.py
|
|
108
|
+
# │ ├── test_processors.py
|
|
109
|
+
# │ ├── test_llm.py
|
|
110
|
+
# │ ├── test_task.py
|
|
111
|
+
# │ └── test_concurrent.py
|
|
112
|
+
# │
|
|
113
|
+
# ├── examples/ # Example usage
|
|
114
|
+
# ├── docs/ # Documentation
|
|
115
|
+
# └── resources/ # Resource files
|
llmling/client.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
"""High-level client interface for LLMling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Literal, Protocol, Self, TypeVar, cast, overload
|
|
7
|
+
|
|
8
|
+
from llmling.config.loading import load_config
|
|
9
|
+
from llmling.config.manager import ConfigManager
|
|
10
|
+
from llmling.context import default_registry as context_registry
|
|
11
|
+
from llmling.core import exceptions
|
|
12
|
+
from llmling.core.log import get_logger, setup_logging
|
|
13
|
+
from llmling.llm.registry import default_registry as llm_registry
|
|
14
|
+
from llmling.processors.registry import ProcessorRegistry
|
|
15
|
+
from llmling.task.concurrent import execute_concurrent
|
|
16
|
+
from llmling.task.executor import TaskExecutor
|
|
17
|
+
from llmling.task.manager import TaskManager
|
|
18
|
+
from llmling.tools.base import ToolRegistry
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from collections.abc import AsyncIterator, Sequence
|
|
23
|
+
import os
|
|
24
|
+
|
|
25
|
+
from llmling.task.models import TaskResult
|
|
26
|
+
|
|
27
|
+
logger = get_logger(__name__)
|
|
28
|
+
|
|
29
|
+
T = TypeVar("T")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Registerable(Protocol):
|
|
33
|
+
"""Protocol for objects that can be registered."""
|
|
34
|
+
|
|
35
|
+
def register(self, name: str, item: Any) -> None: ...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
ComponentType = Literal["processor", "context", "provider", "tool"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class LLMLingClient:
|
|
42
|
+
"""High-level client interface for interacting with LLMling."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
config_path: str | os.PathLike[str],
|
|
47
|
+
*,
|
|
48
|
+
log_level: int | str | None = None,
|
|
49
|
+
validate_config: bool = True,
|
|
50
|
+
components: dict[ComponentType, dict[str, Any]] | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Initialize the client.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
config_path: Path to YAML configuration file
|
|
56
|
+
log_level: Optional logging level
|
|
57
|
+
validate_config: Whether to validate configuration on load
|
|
58
|
+
components: Optional dictionary of components to register
|
|
59
|
+
Example:
|
|
60
|
+
{
|
|
61
|
+
"processor": {"name": ProcessorConfig(...)},
|
|
62
|
+
"context": {"name": ContextLoader(...)},
|
|
63
|
+
"provider": {"name": LLMProvider(...)},
|
|
64
|
+
}
|
|
65
|
+
"""
|
|
66
|
+
if log_level is not None:
|
|
67
|
+
setup_logging(level=log_level)
|
|
68
|
+
|
|
69
|
+
self.config_path = config_path
|
|
70
|
+
self.validate_config = validate_config
|
|
71
|
+
self.components = components or {}
|
|
72
|
+
self.tool_registry = ToolRegistry()
|
|
73
|
+
# Components will be initialized in startup
|
|
74
|
+
self.config_manager: ConfigManager | None = None
|
|
75
|
+
self._processor_registry: ProcessorRegistry | None = None
|
|
76
|
+
self._executor: TaskExecutor | None = None
|
|
77
|
+
self._manager: TaskManager | None = None
|
|
78
|
+
self._initialized = False
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def manager(self) -> TaskManager:
|
|
82
|
+
"""Get the task manager, raising if not initialized."""
|
|
83
|
+
self._ensure_initialized()
|
|
84
|
+
if self._manager is None:
|
|
85
|
+
msg = "Task manager not initialized"
|
|
86
|
+
raise exceptions.LLMLingError(msg)
|
|
87
|
+
return self._manager
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def create(
|
|
91
|
+
cls,
|
|
92
|
+
config_path: str | os.PathLike[str],
|
|
93
|
+
**kwargs: Any,
|
|
94
|
+
) -> LLMLingClient:
|
|
95
|
+
"""Create and initialize a client synchronously.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
config_path: Path to configuration file
|
|
99
|
+
**kwargs: Additional arguments for initialization
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Initialized client instance
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
LLMLingError: If initialization fails
|
|
106
|
+
"""
|
|
107
|
+
client = cls(config_path, **kwargs)
|
|
108
|
+
try:
|
|
109
|
+
# Create new event loop for sync operations
|
|
110
|
+
loop = asyncio.new_event_loop()
|
|
111
|
+
asyncio.set_event_loop(loop)
|
|
112
|
+
try:
|
|
113
|
+
loop.run_until_complete(client.startup())
|
|
114
|
+
return client
|
|
115
|
+
finally:
|
|
116
|
+
loop.close()
|
|
117
|
+
asyncio.set_event_loop(None)
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
logger.exception("Failed to create client")
|
|
120
|
+
msg = f"Failed to create client: {exc}"
|
|
121
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
122
|
+
|
|
123
|
+
async def startup(self) -> None:
|
|
124
|
+
"""Initialize all components."""
|
|
125
|
+
if self._initialized:
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
# Initialize registries
|
|
130
|
+
self._processor_registry = ProcessorRegistry()
|
|
131
|
+
llm_registry.reset() # Ensure clean state
|
|
132
|
+
|
|
133
|
+
# Load configuration
|
|
134
|
+
config = load_config(
|
|
135
|
+
self.config_path,
|
|
136
|
+
validate=self.validate_config,
|
|
137
|
+
)
|
|
138
|
+
self.config_manager = ConfigManager(config)
|
|
139
|
+
|
|
140
|
+
# Register providers
|
|
141
|
+
await self._register_providers()
|
|
142
|
+
|
|
143
|
+
# Register components
|
|
144
|
+
await self._register_components()
|
|
145
|
+
|
|
146
|
+
# Start processor registry
|
|
147
|
+
await self._processor_registry.startup()
|
|
148
|
+
|
|
149
|
+
# Create executor with empty tool registry
|
|
150
|
+
self._executor = TaskExecutor(
|
|
151
|
+
context_registry=context_registry,
|
|
152
|
+
processor_registry=self._processor_registry,
|
|
153
|
+
provider_registry=llm_registry,
|
|
154
|
+
tool_registry=ToolRegistry(), # Empty registry, TaskManager will populate
|
|
155
|
+
config_manager=self.config_manager,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# Create manager (will handle tool registration)
|
|
159
|
+
self._manager = TaskManager(self.config_manager.config, self._executor)
|
|
160
|
+
|
|
161
|
+
self._initialized = True
|
|
162
|
+
logger.debug("Client initialized successfully")
|
|
163
|
+
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
logger.exception("Client initialization failed")
|
|
166
|
+
await self.shutdown()
|
|
167
|
+
msg = f"Failed to initialize client: {exc}"
|
|
168
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
169
|
+
|
|
170
|
+
async def _register_components(self) -> None:
|
|
171
|
+
"""Register all configured components.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
LLMLingError: If component registration fails
|
|
175
|
+
"""
|
|
176
|
+
registries: dict[ComponentType, Registerable] = {
|
|
177
|
+
"processor": cast(Registerable, self._processor_registry),
|
|
178
|
+
"context": cast(Registerable, context_registry),
|
|
179
|
+
"provider": cast(Registerable, llm_registry),
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
for component_type, items in self.components.items():
|
|
183
|
+
registry = registries.get(component_type)
|
|
184
|
+
if registry is None:
|
|
185
|
+
logger.warning("Unknown component type: %s", component_type)
|
|
186
|
+
continue
|
|
187
|
+
|
|
188
|
+
for name, item in items.items():
|
|
189
|
+
try:
|
|
190
|
+
registry.register(name, item)
|
|
191
|
+
logger.debug("Registered %s: %s", component_type, name)
|
|
192
|
+
except Exception as exc:
|
|
193
|
+
msg = f"Failed to register {component_type} {name}: {exc}"
|
|
194
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
195
|
+
|
|
196
|
+
async def _register_providers(self) -> None:
|
|
197
|
+
"""Register all providers from configuration.
|
|
198
|
+
|
|
199
|
+
Raises:
|
|
200
|
+
LLMLingError: If provider registration fails
|
|
201
|
+
"""
|
|
202
|
+
if not self.config_manager:
|
|
203
|
+
msg = "Configuration not loaded"
|
|
204
|
+
raise exceptions.LLMLingError(msg)
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
# Register direct providers
|
|
208
|
+
for provider_key in self.config_manager.config.llm_providers:
|
|
209
|
+
llm_registry.register_provider(provider_key, "litellm")
|
|
210
|
+
logger.debug("Registered provider: %s", provider_key)
|
|
211
|
+
|
|
212
|
+
# Register provider groups
|
|
213
|
+
for (
|
|
214
|
+
group_name,
|
|
215
|
+
providers,
|
|
216
|
+
) in self.config_manager.config.provider_groups.items():
|
|
217
|
+
if providers:
|
|
218
|
+
llm_registry.register_provider(group_name, "litellm")
|
|
219
|
+
logger.debug("Registered provider group: %s", group_name)
|
|
220
|
+
except Exception as exc:
|
|
221
|
+
msg = "Failed to register providers"
|
|
222
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
223
|
+
|
|
224
|
+
def execute_sync(
|
|
225
|
+
self,
|
|
226
|
+
template: str,
|
|
227
|
+
*,
|
|
228
|
+
system_prompt: str | None = None,
|
|
229
|
+
**kwargs: Any,
|
|
230
|
+
) -> TaskResult:
|
|
231
|
+
"""Execute a task template synchronously.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
template: Name of template to execute
|
|
235
|
+
system_prompt: Optional system prompt
|
|
236
|
+
**kwargs: Additional parameters for LLM
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
Task result
|
|
240
|
+
|
|
241
|
+
Raises:
|
|
242
|
+
TaskError: If execution fails
|
|
243
|
+
"""
|
|
244
|
+
try:
|
|
245
|
+
# Create new event loop for sync operation
|
|
246
|
+
loop = asyncio.new_event_loop()
|
|
247
|
+
asyncio.set_event_loop(loop)
|
|
248
|
+
try:
|
|
249
|
+
return loop.run_until_complete(
|
|
250
|
+
self.execute(
|
|
251
|
+
template,
|
|
252
|
+
system_prompt=system_prompt,
|
|
253
|
+
stream=False,
|
|
254
|
+
**kwargs,
|
|
255
|
+
)
|
|
256
|
+
)
|
|
257
|
+
finally:
|
|
258
|
+
loop.close()
|
|
259
|
+
asyncio.set_event_loop(None)
|
|
260
|
+
except Exception as exc:
|
|
261
|
+
msg = f"Synchronous execution failed: {exc}"
|
|
262
|
+
raise exceptions.TaskError(msg) from exc
|
|
263
|
+
|
|
264
|
+
def execute_many_sync(
|
|
265
|
+
self,
|
|
266
|
+
templates: Sequence[str],
|
|
267
|
+
**kwargs: Any,
|
|
268
|
+
) -> list[TaskResult]:
|
|
269
|
+
"""Execute multiple templates synchronously.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
templates: Template names to execute
|
|
273
|
+
**kwargs: Additional parameters passed to execute_many
|
|
274
|
+
|
|
275
|
+
Returns:
|
|
276
|
+
List of task results
|
|
277
|
+
|
|
278
|
+
Raises:
|
|
279
|
+
TaskError: If execution fails
|
|
280
|
+
"""
|
|
281
|
+
try:
|
|
282
|
+
# Create new event loop for sync operation
|
|
283
|
+
loop = asyncio.new_event_loop()
|
|
284
|
+
asyncio.set_event_loop(loop)
|
|
285
|
+
try:
|
|
286
|
+
return loop.run_until_complete(self.execute_many(templates, **kwargs))
|
|
287
|
+
finally:
|
|
288
|
+
loop.close()
|
|
289
|
+
asyncio.set_event_loop(None)
|
|
290
|
+
except Exception as exc:
|
|
291
|
+
msg = f"Synchronous concurrent execution failed: {exc}"
|
|
292
|
+
raise exceptions.TaskError(msg) from exc
|
|
293
|
+
|
|
294
|
+
@overload
|
|
295
|
+
async def execute(
|
|
296
|
+
self,
|
|
297
|
+
template: str,
|
|
298
|
+
*,
|
|
299
|
+
system_prompt: str | None = None,
|
|
300
|
+
stream: Literal[True],
|
|
301
|
+
**kwargs: Any,
|
|
302
|
+
) -> AsyncIterator[TaskResult]: ...
|
|
303
|
+
|
|
304
|
+
@overload
|
|
305
|
+
async def execute(
|
|
306
|
+
self,
|
|
307
|
+
template: str,
|
|
308
|
+
*,
|
|
309
|
+
system_prompt: str | None = None,
|
|
310
|
+
stream: Literal[False] = False,
|
|
311
|
+
**kwargs: Any,
|
|
312
|
+
) -> TaskResult: ...
|
|
313
|
+
|
|
314
|
+
async def execute(
|
|
315
|
+
self,
|
|
316
|
+
template: str,
|
|
317
|
+
*,
|
|
318
|
+
system_prompt: str | None = None,
|
|
319
|
+
stream: bool = False,
|
|
320
|
+
**kwargs: Any,
|
|
321
|
+
) -> TaskResult | AsyncIterator[TaskResult]:
|
|
322
|
+
"""Execute a task template.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
template: Name of template to execute
|
|
326
|
+
system_prompt: Optional system prompt
|
|
327
|
+
stream: Whether to stream results
|
|
328
|
+
**kwargs: Additional parameters for LLM
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
Task result or async iterator of results if streaming
|
|
332
|
+
|
|
333
|
+
Raises:
|
|
334
|
+
TaskError: If execution fails
|
|
335
|
+
"""
|
|
336
|
+
self._ensure_initialized()
|
|
337
|
+
try:
|
|
338
|
+
if stream:
|
|
339
|
+
return self.manager.execute_template_stream(
|
|
340
|
+
template,
|
|
341
|
+
system_prompt=system_prompt,
|
|
342
|
+
**kwargs,
|
|
343
|
+
)
|
|
344
|
+
return await self.manager.execute_template(
|
|
345
|
+
template,
|
|
346
|
+
system_prompt=system_prompt,
|
|
347
|
+
**kwargs,
|
|
348
|
+
)
|
|
349
|
+
except Exception as exc:
|
|
350
|
+
logger.exception("Task execution failed")
|
|
351
|
+
msg = f"Failed to execute template {template}: {exc}"
|
|
352
|
+
raise exceptions.TaskError(msg) from exc
|
|
353
|
+
|
|
354
|
+
async def execute_many(
|
|
355
|
+
self,
|
|
356
|
+
templates: Sequence[str],
|
|
357
|
+
*,
|
|
358
|
+
system_prompt: str | None = None,
|
|
359
|
+
max_concurrent: int = 3,
|
|
360
|
+
**kwargs: Any,
|
|
361
|
+
) -> list[TaskResult]:
|
|
362
|
+
"""Execute multiple templates concurrently.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
templates: Template names to execute
|
|
366
|
+
system_prompt: Optional system prompt
|
|
367
|
+
max_concurrent: Maximum concurrent executions
|
|
368
|
+
**kwargs: Additional parameters for LLM
|
|
369
|
+
|
|
370
|
+
Returns:
|
|
371
|
+
List of task results
|
|
372
|
+
|
|
373
|
+
Raises:
|
|
374
|
+
TaskError: If execution fails
|
|
375
|
+
"""
|
|
376
|
+
self._ensure_initialized()
|
|
377
|
+
try:
|
|
378
|
+
return await execute_concurrent(
|
|
379
|
+
self.manager,
|
|
380
|
+
templates,
|
|
381
|
+
system_prompt=system_prompt,
|
|
382
|
+
max_concurrent=max_concurrent,
|
|
383
|
+
**kwargs,
|
|
384
|
+
)
|
|
385
|
+
except Exception as exc:
|
|
386
|
+
logger.exception("Concurrent execution failed")
|
|
387
|
+
msg = f"Concurrent execution failed: {exc}"
|
|
388
|
+
raise exceptions.TaskError(msg) from exc
|
|
389
|
+
|
|
390
|
+
async def stream(
|
|
391
|
+
self,
|
|
392
|
+
template: str,
|
|
393
|
+
*,
|
|
394
|
+
system_prompt: str | None = None,
|
|
395
|
+
**kwargs: Any,
|
|
396
|
+
) -> AsyncIterator[TaskResult]:
|
|
397
|
+
"""Stream results from a task template.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
template: Name of template to execute
|
|
401
|
+
system_prompt: Optional system prompt
|
|
402
|
+
**kwargs: Additional parameters for LLM
|
|
403
|
+
|
|
404
|
+
Yields:
|
|
405
|
+
Task results
|
|
406
|
+
|
|
407
|
+
Raises:
|
|
408
|
+
TaskError: If streaming fails
|
|
409
|
+
"""
|
|
410
|
+
self._ensure_initialized()
|
|
411
|
+
try:
|
|
412
|
+
async for result in self.manager.execute_template_stream(
|
|
413
|
+
template,
|
|
414
|
+
system_prompt=system_prompt,
|
|
415
|
+
**kwargs,
|
|
416
|
+
):
|
|
417
|
+
yield result
|
|
418
|
+
except Exception as exc:
|
|
419
|
+
logger.exception("Task streaming failed")
|
|
420
|
+
msg = f"Failed to stream template {template}: {exc}"
|
|
421
|
+
raise exceptions.TaskError(msg) from exc
|
|
422
|
+
|
|
423
|
+
def _ensure_initialized(self) -> None:
|
|
424
|
+
"""Ensure client is initialized."""
|
|
425
|
+
if not self._initialized:
|
|
426
|
+
msg = "Client not initialized"
|
|
427
|
+
raise exceptions.LLMLingError(msg)
|
|
428
|
+
|
|
429
|
+
async def shutdown(self) -> None:
|
|
430
|
+
"""Clean up resources."""
|
|
431
|
+
if not self._initialized:
|
|
432
|
+
return
|
|
433
|
+
|
|
434
|
+
try:
|
|
435
|
+
if self._processor_registry:
|
|
436
|
+
await self._processor_registry.shutdown()
|
|
437
|
+
except Exception as exc:
|
|
438
|
+
logger.exception("Error during shutdown")
|
|
439
|
+
msg = f"Failed to shutdown client: {exc}"
|
|
440
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
441
|
+
finally:
|
|
442
|
+
self._initialized = False
|
|
443
|
+
logger.info("Client shut down successfully")
|
|
444
|
+
|
|
445
|
+
async def __aenter__(self) -> Self:
|
|
446
|
+
"""Async context manager entry."""
|
|
447
|
+
await self.startup()
|
|
448
|
+
return self
|
|
449
|
+
|
|
450
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
451
|
+
"""Async context manager exit."""
|
|
452
|
+
await self.shutdown()
|
|
453
|
+
|
|
454
|
+
def __enter__(self) -> Self:
|
|
455
|
+
"""Synchronous context manager entry."""
|
|
456
|
+
try:
|
|
457
|
+
# Create new event loop for sync operation
|
|
458
|
+
loop = asyncio.new_event_loop()
|
|
459
|
+
asyncio.set_event_loop(loop)
|
|
460
|
+
try:
|
|
461
|
+
loop.run_until_complete(self.startup())
|
|
462
|
+
return self
|
|
463
|
+
finally:
|
|
464
|
+
loop.close()
|
|
465
|
+
asyncio.set_event_loop(None)
|
|
466
|
+
except Exception as exc:
|
|
467
|
+
msg = "Failed to enter context"
|
|
468
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
469
|
+
|
|
470
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
471
|
+
"""Synchronous context manager exit."""
|
|
472
|
+
try:
|
|
473
|
+
# Create new event loop for sync operation
|
|
474
|
+
loop = asyncio.new_event_loop()
|
|
475
|
+
asyncio.set_event_loop(loop)
|
|
476
|
+
try:
|
|
477
|
+
loop.run_until_complete(self.shutdown())
|
|
478
|
+
finally:
|
|
479
|
+
loop.close()
|
|
480
|
+
asyncio.set_event_loop(None)
|
|
481
|
+
except Exception as exc:
|
|
482
|
+
logger.exception("Error during context exit")
|
|
483
|
+
msg = "Failed to exit context"
|
|
484
|
+
raise exceptions.LLMLingError(msg) from exc
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
async def async_example() -> None:
|
|
488
|
+
"""Example of async usage."""
|
|
489
|
+
async with LLMLingClient("src/llmling/resources/test.yml") as client:
|
|
490
|
+
# Single execution
|
|
491
|
+
result = await client.execute("quick_review")
|
|
492
|
+
print("\nSingle execution result:")
|
|
493
|
+
print("-" * 40)
|
|
494
|
+
print(result.content)
|
|
495
|
+
|
|
496
|
+
# Streaming execution
|
|
497
|
+
print("\nStreaming execution:")
|
|
498
|
+
print("-" * 40)
|
|
499
|
+
async for chunk in client.stream("quick_review"):
|
|
500
|
+
print(chunk.content, end="")
|
|
501
|
+
|
|
502
|
+
# Concurrent execution
|
|
503
|
+
print("\n\nConcurrent execution:")
|
|
504
|
+
print("-" * 40)
|
|
505
|
+
results = await client.execute_many(
|
|
506
|
+
["quick_review", "detailed_review"],
|
|
507
|
+
max_concurrent=2,
|
|
508
|
+
)
|
|
509
|
+
for r in results:
|
|
510
|
+
print(f"\nResult from {r.model}:")
|
|
511
|
+
print(r.content)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def sync_example() -> None:
|
|
515
|
+
"""Example of synchronous usage."""
|
|
516
|
+
with LLMLingClient.create("src/llmling/resources/test.yml") as client:
|
|
517
|
+
# Single execution
|
|
518
|
+
result = client.execute_sync("quick_review")
|
|
519
|
+
print("\nSync execution result:")
|
|
520
|
+
print("-" * 40)
|
|
521
|
+
print(result.content)
|
|
522
|
+
|
|
523
|
+
# Concurrent execution
|
|
524
|
+
print("\nSync concurrent execution:")
|
|
525
|
+
print("-" * 40)
|
|
526
|
+
results = client.execute_many_sync(
|
|
527
|
+
["quick_review", "detailed_review"],
|
|
528
|
+
max_concurrent=2,
|
|
529
|
+
)
|
|
530
|
+
for r in results:
|
|
531
|
+
print(f"\nResult from {r.model}:")
|
|
532
|
+
print(r.content)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
if __name__ == "__main__":
|
|
536
|
+
"""Run both async and sync examples."""
|
|
537
|
+
# Reset the registry before running examples
|
|
538
|
+
llm_registry.reset()
|
|
539
|
+
|
|
540
|
+
print("\nRunning async example...")
|
|
541
|
+
print("=" * 50)
|
|
542
|
+
asyncio.run(async_example())
|
|
543
|
+
|
|
544
|
+
print("\nRunning sync example...")
|
|
545
|
+
print("=" * 50)
|
|
546
|
+
# Reset registry between examples
|
|
547
|
+
llm_registry.reset()
|
|
548
|
+
sync_example()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Configuration management for LLMling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from llmling.config.manager import ConfigManager
|
|
6
|
+
from llmling.config.models import (
|
|
7
|
+
Config,
|
|
8
|
+
Context,
|
|
9
|
+
GlobalSettings,
|
|
10
|
+
LLMProviderConfig,
|
|
11
|
+
TaskSettings,
|
|
12
|
+
TaskTemplate,
|
|
13
|
+
CallableContext,
|
|
14
|
+
SourceContext,
|
|
15
|
+
)
|
|
16
|
+
from llmling.config.validation import ConfigValidator
|
|
17
|
+
from llmling.config.loading import load_config
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Config",
|
|
22
|
+
"ConfigManager",
|
|
23
|
+
"CallableContext",
|
|
24
|
+
"SourceContext",
|
|
25
|
+
"ConfigValidator",
|
|
26
|
+
"Context",
|
|
27
|
+
"GlobalSettings",
|
|
28
|
+
"LLMProviderConfig",
|
|
29
|
+
"TaskSettings",
|
|
30
|
+
"TaskTemplate",
|
|
31
|
+
"load_config",
|
|
32
|
+
]
|