Skip to content

SlashedAgent

Base classes

Name Children Inherits
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  94350422887552["slashed_agent.SlashedAgent"]
  94350360566400["typing.Generic"]
  140709601677504["builtins.object"]
  94350360566400 --> 94350422887552
  140709601677504 --> 94350360566400

🛈 DocStrings

Wraps an agent with slash command support.

Source code in src/llmling_agent/agent/slashed_agent.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
class SlashedAgent[TDeps, TContext]:
    """Wraps an agent with slash command support."""

    message_output = Signal(AgentOutput)
    streamed_output = Signal(AgentOutput)
    streaming_started = Signal(str)  # message_id
    streaming_stopped = Signal(str)  # message_id

    def __init__(
        self,
        agent: AnyAgent[TDeps, Any],
        *,
        command_context: TContext | None = None,
        command_history_path: str | None = None,
        output: DefaultOutputWriter | None = None,
    ):
        self.agent = agent
        assert self.agent.context, "Agent must have a context!"
        assert self.agent.context.pool, "Agent must have a pool!"

        self.commands = CommandStore(
            history_file=command_history_path,
            enable_system_commands=True,
        )
        self.commands._initialize_sync()
        self._current_stream_id: str | None = None
        self.command_context: TContext = command_context or self  # type: ignore
        self.output = output or DefaultOutputWriter()
        # Connect to agent's signals
        agent.message_received.connect(self._handle_message_received)
        agent.message_sent.connect(self._handle_message_sent)
        agent.tool_used.connect(self._handle_tool_used)
        self.commands.command_executed.connect(self._handle_command_executed)
        self.commands.output.connect(self.streamed_output)
        agent.chunk_streamed.connect(self.streamed_output)

    @overload
    async def run[TMethodResult](
        self,
        *prompt: AnyPromptType,
        result_type: type[TMethodResult],
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ChatMessage[TMethodResult]: ...

    @overload
    async def run(
        self,
        *prompt: AnyPromptType,
        result_type: None = None,
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ChatMessage[str]: ...

    async def run(
        self,
        *prompt: AnyPromptType,
        result_type: type[Any] | None = None,
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ChatMessage[Any]:
        """Run with slash command support."""
        # First execute all commands sequentially
        remaining_prompts = []
        for p in prompt:
            if isinstance(p, str) and p.startswith("/"):
                await self.handle_command(
                    p[1:],
                    output=output or self.output,
                    metadata=metadata,
                )
            else:
                remaining_prompts.append(p)

        # Then pass remaining prompts to agent
        return await self.agent.run(
            *remaining_prompts, result_type=result_type, deps=deps, model=model
        )

    @overload
    def run_stream[TMethodResult](
        self,
        *prompt: AnyPromptType,
        result_type: type[TMethodResult],
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> AbstractAsyncContextManager[
        StreamedRunResult[AgentContext[TDeps], TMethodResult]
    ]: ...

    @overload
    def run_stream(
        self,
        *prompt: AnyPromptType,
        result_type: None = None,
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> AbstractAsyncContextManager[StreamedRunResult[AgentContext[TDeps], str]]: ...

    @asynccontextmanager
    async def run_stream(
        self,
        *prompt: AnyPromptType,
        result_type: type[Any] | None = None,
        deps: TDeps | None = None,
        model: ModelType = None,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> AsyncIterator[StreamedRunResult[AgentContext[TDeps], Any]]:
        """Stream responses with slash command support."""
        # First execute all commands sequentially
        remaining_prompts: list[AnyPromptType] = []
        for p in prompt:
            if isinstance(p, str) and p.startswith("/"):
                await self.handle_command(
                    p[1:],
                    output=output or self.output,
                    metadata=metadata,
                )
            else:
                remaining_prompts.append(p)

        # Then yield from agent's stream
        async with self.agent.run_stream(
            *remaining_prompts, result_type=result_type, deps=deps, model=model
        ) as stream:
            yield stream

    async def handle_command(
        self,
        command: str,
        output: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ChatMessage[str]:
        """Handle a slash command."""
        try:
            await self.commands.execute_command_with_context(
                command,
                context=self.command_context,
                output_writer=output or self.output,
                metadata=metadata,
            )
            return ChatMessage(content="", role="system")
        except ExitCommandError:
            raise
        except Exception as e:  # noqa: BLE001
            msg = f"Command error: {e}"
            return ChatMessage(content=msg, role="system")

    @property
    def tools(self) -> ToolManager:
        """Access to tool management."""
        return self.agent.tools

    @property
    def conversation(self) -> ConversationManager:
        """Access to conversation management."""
        return self.agent.conversation

    @property
    def provider(self) -> AgentProvider[TDeps]:
        """Access to the underlying provider."""
        return self.agent._provider

    @property
    def pool(self) -> AgentPool:
        """Get agent's pool from context."""
        assert self.agent.context.pool
        return self.agent.context.pool

    @property
    def model_name(self) -> str | None:
        """Get current model name."""
        return self.agent.model_name

    @property
    def context(self) -> AgentContext[TDeps]:
        """Access to agent context."""
        return self.agent.context

    def _handle_message_received(self, message: ChatMessage[str]):
        meta = {"role": message.role}
        output = AgentOutput(type="message_received", content=message, metadata=meta)
        self.message_output.emit(output)

    def _handle_message_sent(self, message: ChatMessage[Any]):
        cost = message.cost_info.total_cost if message.cost_info else None
        metadata = {"role": message.role, "model": message.model, "cost": cost}
        output = AgentOutput(type="message_sent", content=message, metadata=metadata)
        self.message_output.emit(output)

    def _handle_tool_used(self, tool_call: ToolCallInfo):
        metadata = {"tool_name": tool_call.tool_name}
        output = AgentOutput("tool_called", content=tool_call, metadata=metadata)
        self.message_output.emit(output)

    # Could also connect to Slashed's command signals
    def _handle_command_executed(self, event: CommandExecutedEvent):
        """Handle command execution events."""
        error = str(event.error) if event.error else None
        meta = {"success": event.success, "error": error, "context": event.context}
        output = AgentOutput("command_executed", content=event.command, metadata=meta)
        self.message_output.emit(output)

    def _handle_chunk_streamed(self, chunk: str, message_id: str):
        """Handle streaming chunks."""
        # If this is a new streaming session
        if message_id != self._current_stream_id:
            self._current_stream_id = message_id
            self.streaming_started.emit(message_id)

        if chunk:  # Only emit non-empty chunks
            output = AgentOutput(
                type="stream", content=chunk, metadata={"message_id": message_id}
            )
            self.streamed_output.emit(output)
        else:  # Empty chunk signals end of stream
            self.streaming_stopped.emit(message_id)
            self._current_stream_id = None

context property

context: AgentContext[TDeps]

Access to agent context.

conversation property

conversation: ConversationManager

Access to conversation management.

model_name property

model_name: str | None

Get current model name.

pool property

pool: AgentPool

Get agent's pool from context.

provider property

provider: AgentProvider[TDeps]

Access to the underlying provider.

tools property

tools: ToolManager

Access to tool management.

handle_command async

handle_command(
    command: str,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[str]

Handle a slash command.

Source code in src/llmling_agent/agent/slashed_agent.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
async def handle_command(
    self,
    command: str,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[str]:
    """Handle a slash command."""
    try:
        await self.commands.execute_command_with_context(
            command,
            context=self.command_context,
            output_writer=output or self.output,
            metadata=metadata,
        )
        return ChatMessage(content="", role="system")
    except ExitCommandError:
        raise
    except Exception as e:  # noqa: BLE001
        msg = f"Command error: {e}"
        return ChatMessage(content=msg, role="system")

run async

run(
    *prompt: AnyPromptType,
    result_type: type[TMethodResult],
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[TMethodResult]
run(
    *prompt: AnyPromptType,
    result_type: None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[str]
run(
    *prompt: AnyPromptType,
    result_type: type[Any] | None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[Any]

Run with slash command support.

Source code in src/llmling_agent/agent/slashed_agent.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
async def run(
    self,
    *prompt: AnyPromptType,
    result_type: type[Any] | None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> ChatMessage[Any]:
    """Run with slash command support."""
    # First execute all commands sequentially
    remaining_prompts = []
    for p in prompt:
        if isinstance(p, str) and p.startswith("/"):
            await self.handle_command(
                p[1:],
                output=output or self.output,
                metadata=metadata,
            )
        else:
            remaining_prompts.append(p)

    # Then pass remaining prompts to agent
    return await self.agent.run(
        *remaining_prompts, result_type=result_type, deps=deps, model=model
    )

run_stream async

run_stream(
    *prompt: AnyPromptType,
    result_type: type[TMethodResult],
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentContext[TDeps], TMethodResult]]
run_stream(
    *prompt: AnyPromptType,
    result_type: None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> AbstractAsyncContextManager[StreamedRunResult[AgentContext[TDeps], str]]
run_stream(
    *prompt: AnyPromptType,
    result_type: type[Any] | None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> AsyncIterator[StreamedRunResult[AgentContext[TDeps], Any]]

Stream responses with slash command support.

Source code in src/llmling_agent/agent/slashed_agent.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@asynccontextmanager
async def run_stream(
    self,
    *prompt: AnyPromptType,
    result_type: type[Any] | None = None,
    deps: TDeps | None = None,
    model: ModelType = None,
    output: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> AsyncIterator[StreamedRunResult[AgentContext[TDeps], Any]]:
    """Stream responses with slash command support."""
    # First execute all commands sequentially
    remaining_prompts: list[AnyPromptType] = []
    for p in prompt:
        if isinstance(p, str) and p.startswith("/"):
            await self.handle_command(
                p[1:],
                output=output or self.output,
                metadata=metadata,
            )
        else:
            remaining_prompts.append(p)

    # Then yield from agent's stream
    async with self.agent.run_stream(
        *remaining_prompts, result_type=result_type, deps=deps, model=model
    ) as stream:
        yield stream

Show source on GitHub