Skip to content

CallbackCompleter

Base classes

Name Children Inherits
CompletionProvider
slashed.completion
Base class for completion providers.

⋔ Inheritance diagram

graph TD
  184255684["completers.CallbackCompleter"]
  2851341576["completion.CompletionProvider"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  2851341576 --> 184255684
  925645236 --> 2851341576
  2751680898 --> 925645236

🛈 DocStrings

Bases: CompletionProvider

Completer that calls a function to get completions dynamically.

The callback can return either strings or CompletionItems.

Example

def complete_tools(ctx: CompletionContext) -> Iterator[str]: tools = ["hammer", "screwdriver", "wrench"] return (t for t in tools if t.startswith(ctx.current_word))

command = Command( name="use-tool", description="Use a tool", completer=CallbackCompleter(complete_tools) )

Source code in src/slashed/completers.py
class CallbackCompleter(CompletionProvider):
    """Completer that calls a function to get completions dynamically.

    The callback can return either strings or CompletionItems.

    Example:
        def complete_tools(ctx: CompletionContext) -> Iterator[str]:
            tools = ["hammer", "screwdriver", "wrench"]
            return (t for t in tools if t.startswith(ctx.current_word))

        command = Command(
            name="use-tool",
            description="Use a tool",
            completer=CallbackCompleter(complete_tools)
        )
    """

    def __init__(
        self,
        callback: (
            Callable[[CompletionContext[Any]], Iterable[str | CompletionItem]]
            | Callable[[CompletionContext[Any]], Awaitable[Iterable[str | CompletionItem]]]
        ),
        kind: CompletionKind | None = None,
    ) -> None:
        self._callback = callback
        self._kind = kind
        self._is_async = inspect.iscoroutinefunction(callback)

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        try:
            result = self._callback(context)

            # Narrow type and handle async/sync appropriately
            if is_awaitable(result):
                items = await result
            else:
                items = cast(Iterable[str | CompletionItem], result)

            for item in items:
                if isinstance(item, str):
                    yield CompletionItem(text=item, kind=self._kind)
                else:
                    yield item
        except Exception as e:  # noqa: BLE001
            logger.debug("Completion callback error: %s", e)

:fa-brands-github: Show source on GitHub