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)
|