Skip to content

Tools

octomate.tentacles.inkling.capabilities.ask

Ask capability: the deferred ask-the-user tool.

A capability rather than a loose toolset entry so the caller decides per run whether a user exists to ask at all — an interactive run mounts it, an accomplice run simply never sees the tool.

AskCapability dataclass

Bases: AbstractCapability[None]

Offers ask_questions — the deferred ask-the-user batch.

Source code in octomate/tentacles/inkling/capabilities/ask.py
@dataclass
class AskCapability(AbstractCapability[None]):
    """Offers `ask_questions` — the deferred ask-the-user batch."""

    toolset: FunctionToolset[None] | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        toolset: FunctionToolset[None] = FunctionToolset(id="ask")

        @toolset.tool(name=ASK_QUESTIONS_TOOL_NAME)
        async def ask_questions(
            ctx: RunContext[None],
            questions: list[QuestionRequest],
        ) -> list[str]:
            """Ask the user several questions and wait for all answers as one batch."""
            if not questions:
                raise ValueError("ask_questions requires at least one question")
            raise CallDeferred(metadata={"kind": ASK_DEFERR_KIND})

        self.toolset = toolset

    def get_toolset(self) -> AbstractToolset[None] | None:
        return self.toolset

toolset class-attribute instance-attribute

toolset: FunctionToolset[None] | None = field(
    default=None, init=False, repr=False
)

get_toolset

get_toolset() -> AbstractToolset[None] | None
Source code in octomate/tentacles/inkling/capabilities/ask.py
def get_toolset(self) -> AbstractToolset[None] | None:
    return self.toolset

octomate.capabilities.history

History capability: the thread ledger of the person a run answers.

Thread history is what people, bots and agents visibly said — ThreadMessage rows, including the ones that did not wake this agent. The model ledger is not offered here: it exists for audit and for rebuilding a conversation's context, not for a model to read.

The scope is the person, not the thread: a run reads every thread the human it is answering has spoken in, on any account the registry links to them — this thread, their direct messages elsewhere, the chat a handoff came from. So the capability is user-scoped, bound per run by for_profile, and no tool takes a conversation id.

The tools are methods with docstrings, as the gateway's spells are, so a runtime that reaches them some other way than pydantic-ai projects the same contracts.

HISTORY_TOOLSET_ID module-attribute

HISTORY_TOOLSET_ID = 'history'

HISTORY_INSTRUCTION_TEMPLATE module-attribute

HISTORY_INSTRUCTION_TEMPLATE = "## Searching history\n\nThread history is what people, bots, and agents visibly said — in this thread, and\nin every other thread the person you are answering has spoken in, on any of their\nlinked accounts. Messages that did not wake you are there too.\n\n- `{search_thread_history}` searches all of it for English terms, requiring every\n  term and ranking the best lexical matches first. It accepts an optional actor\n  kind. Prefer it when the user refers to what was said, here or elsewhere.\n- `{read_thread_history_before}` and `{read_thread_history_after}` page a thread\n  around a search hit, or around a `#msg:<id>` handle a brief cited.\n"

HISTORY_TOOLS module-attribute

HISTORY_TOOLS: tuple[str, ...] = (
    "search_thread_history",
    "read_thread_history_before",
    "read_thread_history_after",
)

HISTORY_INSTRUCTIONS module-attribute

HISTORY_INSTRUCTIONS = history_instructions(
    lambda name: name
)

HistoryCapability dataclass

Bases: AbstractCapability[Any]

Thread-history tools over the history of the person a run answers.

Mounted user-scoped: the tentacle asks for_profile for the copy bound to that run's user and mounts that, so no tool has to ask who is asking.

Source code in octomate/capabilities/history.py
@dataclass
class HistoryCapability(AbstractCapability[Any]):
    """Thread-history tools over the history of the person a run answers.

    Mounted user-scoped: the tentacle asks `for_profile` for the copy bound to
    that run's user and mounts that, so no tool has to ask who is asking.
    """

    # No default: the capability must read the host's ledger manager, never a
    # private one with its own identity registry.
    thread_manager: ThreadManager
    # The person whose history the tools read. None on the mounted template,
    # which serves no run itself.
    profile: UserProfile | None = None
    toolset: FunctionToolset[Any] | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        toolset: FunctionToolset[Any] = FunctionToolset(id=HISTORY_TOOLSET_ID)
        # No tool takes the run context: the person is bound in, not read off it.
        toolset.add_function(self.search_thread_history, takes_ctx=False)
        toolset.add_function(self.read_thread_history_before, takes_ctx=False)
        toolset.add_function(self.read_thread_history_after, takes_ctx=False)
        self.toolset = toolset

    async def for_profile(self, profile: UserProfile) -> HistoryCapability:
        """This capability bound to one person. Everyone gets one: a visitor's
        history is the threads their one account has spoken in."""
        return replace(self, profile=profile)

    @property
    def reader(self) -> UserProfile:
        if self.profile is None:
            raise RuntimeError(
                "history is read as a run's user: mount the copy `for_profile` gives"
            )
        return self.profile

    async def anchor(self, handle: str) -> ThreadMessage:
        """The message a paging tool is anchored on, with a refusal spoken as a
        retry: a handle outside this person's history is not theirs to page."""
        try:
            return await self.thread_manager.chat_message(self.reader, handle)
        except ValueError as refusal:
            raise ModelRetry(str(refusal)) from refusal

    async def search_thread_history(
        self,
        query: str,
        actor_kind: ChannelActorKind | None = None,
        limit: int = 10,
    ) -> list[ThreadMessage]:
        """Find visible thread messages matching every English term in `query`,
        with related word forms matched by stemming, across every thread the person
        you are answering has spoken in — this one, their direct messages, other
        chats, on any of their linked accounts. Optionally restrict to an actor kind
        such as "human", "agent", "bot", or "system". Best lexical match first,
        newest first when scores tie. Use a hit's id to page its local context."""
        try:
            return await self.thread_manager.search_chat_messages(
                self.reader, query, actor_kind=actor_kind, limit=limit
            )
        except ValueError as refusal:
            raise ModelRetry(str(refusal)) from refusal

    async def read_thread_history_before(
        self, message_id: str, limit: int = 10
    ) -> list[ThreadMessage]:
        """The visible thread messages immediately preceding `message_id` in its
        thread, oldest first. `message_id` is a row id or a `#msg:<id>` handle, as
        a search hit or a brief shows it; a message outside this person's history
        is refused."""
        anchor = await self.anchor(message_id)
        return await self.thread_manager.chat_messages_before(
            anchor.thread_id, anchor.id, limit=limit
        )

    async def read_thread_history_after(
        self, message_id: str, limit: int = 10
    ) -> list[ThreadMessage]:
        """The visible thread messages immediately following `message_id` in its
        thread, oldest first. `message_id` is a row id or a `#msg:<id>` handle, as
        a search hit or a brief shows it; a message outside this person's history
        is refused."""
        anchor = await self.anchor(message_id)
        return await self.thread_manager.chat_messages_after(
            anchor.thread_id, anchor.id, limit=limit
        )

    def get_toolset(self) -> FunctionToolset[Any] | None:
        return self.toolset

    def get_instructions(self) -> AgentInstructions[Any] | None:
        return HISTORY_INSTRUCTIONS

thread_manager instance-attribute

thread_manager: ThreadManager

profile class-attribute instance-attribute

profile: UserProfile | None = None

toolset class-attribute instance-attribute

toolset: FunctionToolset[Any] | None = field(
    default=None, init=False, repr=False
)

reader property

reader: UserProfile

for_profile async

for_profile(profile: UserProfile) -> HistoryCapability

This capability bound to one person. Everyone gets one: a visitor's history is the threads their one account has spoken in.

Source code in octomate/capabilities/history.py
async def for_profile(self, profile: UserProfile) -> HistoryCapability:
    """This capability bound to one person. Everyone gets one: a visitor's
    history is the threads their one account has spoken in."""
    return replace(self, profile=profile)

anchor async

anchor(handle: str) -> ThreadMessage

The message a paging tool is anchored on, with a refusal spoken as a retry: a handle outside this person's history is not theirs to page.

Source code in octomate/capabilities/history.py
async def anchor(self, handle: str) -> ThreadMessage:
    """The message a paging tool is anchored on, with a refusal spoken as a
    retry: a handle outside this person's history is not theirs to page."""
    try:
        return await self.thread_manager.chat_message(self.reader, handle)
    except ValueError as refusal:
        raise ModelRetry(str(refusal)) from refusal

search_thread_history async

search_thread_history(
    query: str,
    actor_kind: ChannelActorKind | None = None,
    limit: int = 10,
) -> list[ThreadMessage]

Find visible thread messages matching every English term in query, with related word forms matched by stemming, across every thread the person you are answering has spoken in — this one, their direct messages, other chats, on any of their linked accounts. Optionally restrict to an actor kind such as "human", "agent", "bot", or "system". Best lexical match first, newest first when scores tie. Use a hit's id to page its local context.

Source code in octomate/capabilities/history.py
async def search_thread_history(
    self,
    query: str,
    actor_kind: ChannelActorKind | None = None,
    limit: int = 10,
) -> list[ThreadMessage]:
    """Find visible thread messages matching every English term in `query`,
    with related word forms matched by stemming, across every thread the person
    you are answering has spoken in — this one, their direct messages, other
    chats, on any of their linked accounts. Optionally restrict to an actor kind
    such as "human", "agent", "bot", or "system". Best lexical match first,
    newest first when scores tie. Use a hit's id to page its local context."""
    try:
        return await self.thread_manager.search_chat_messages(
            self.reader, query, actor_kind=actor_kind, limit=limit
        )
    except ValueError as refusal:
        raise ModelRetry(str(refusal)) from refusal

read_thread_history_before async

read_thread_history_before(
    message_id: str, limit: int = 10
) -> list[ThreadMessage]

The visible thread messages immediately preceding message_id in its thread, oldest first. message_id is a row id or a #msg:<id> handle, as a search hit or a brief shows it; a message outside this person's history is refused.

Source code in octomate/capabilities/history.py
async def read_thread_history_before(
    self, message_id: str, limit: int = 10
) -> list[ThreadMessage]:
    """The visible thread messages immediately preceding `message_id` in its
    thread, oldest first. `message_id` is a row id or a `#msg:<id>` handle, as
    a search hit or a brief shows it; a message outside this person's history
    is refused."""
    anchor = await self.anchor(message_id)
    return await self.thread_manager.chat_messages_before(
        anchor.thread_id, anchor.id, limit=limit
    )

read_thread_history_after async

read_thread_history_after(
    message_id: str, limit: int = 10
) -> list[ThreadMessage]

The visible thread messages immediately following message_id in its thread, oldest first. message_id is a row id or a #msg:<id> handle, as a search hit or a brief shows it; a message outside this person's history is refused.

Source code in octomate/capabilities/history.py
async def read_thread_history_after(
    self, message_id: str, limit: int = 10
) -> list[ThreadMessage]:
    """The visible thread messages immediately following `message_id` in its
    thread, oldest first. `message_id` is a row id or a `#msg:<id>` handle, as
    a search hit or a brief shows it; a message outside this person's history
    is refused."""
    anchor = await self.anchor(message_id)
    return await self.thread_manager.chat_messages_after(
        anchor.thread_id, anchor.id, limit=limit
    )

get_toolset

get_toolset() -> FunctionToolset[Any] | None
Source code in octomate/capabilities/history.py
def get_toolset(self) -> FunctionToolset[Any] | None:
    return self.toolset

get_instructions

get_instructions() -> AgentInstructions[Any] | None
Source code in octomate/capabilities/history.py
def get_instructions(self) -> AgentInstructions[Any] | None:
    return HISTORY_INSTRUCTIONS

history_instructions

history_instructions(
    tool_name: Callable[[str], str],
) -> str

The history instruction, each tool rendered by the caller's own naming.

Source code in octomate/capabilities/history.py
def history_instructions(tool_name: Callable[[str], str]) -> str:
    """The history instruction, each tool rendered by the caller's own naming."""
    return HISTORY_INSTRUCTION_TEMPLATE.format(
        **{name: tool_name(name) for name in HISTORY_TOOLS}
    )

conversation_id

conversation_id(ctx: object) -> UUID7
Source code in octomate/capabilities/history.py
def conversation_id(ctx: object) -> UUID7:
    value = getattr(ctx, "conversation_id", None)
    if isinstance(value, uuid.UUID):
        return value
    if isinstance(value, str):
        return uuid.UUID(value)
    if value is None:
        raise ValueError("history tools require a conversation_id on the run")
    raise TypeError("history tools require a UUID conversation_id")

thread_id async

thread_id(
    ctx: object, conversation_manager: ConversationManager
) -> UUID7
Source code in octomate/capabilities/history.py
async def thread_id(ctx: object, conversation_manager: ConversationManager) -> UUID7:
    value = await conversation_manager.thread_id(conversation_id(ctx))
    if value is not None:
        return value
    raise ValueError("thread history tools require a thread-backed conversation")

octomate.tentacles.inkling.capabilities.tools

Tool-level capabilities: reporting a failed tool call to the model instead of ending the turn.

ToolFailureCapability dataclass

Bases: AbstractCapability[None]

Report a failed tool to the model instead of ending the turn.

Pydantic AI ends a run when a tool raises anything but its own control-flow signals, so one broken call — a bad argument, a provider that blinked, a spell used out of order — costs the whole answer: the stream stops mid-way, whatever had already been drawn is abandoned, and the person is left with a trace id instead of a reply. The model is the one that can work around a failed call, and the one that can say what went wrong, so it is told.

ToolFailed rather than ModelRetry: a call that failed for reasons the model did not cause is not a call to make again, and a retry spends a budget that ends the run when it runs out — which is the same lost turn, one attempt later. A failure it can read leaves it free to try another way or explain. Runs stay bounded by Inkling's configured UsageLimits.request_limit, not by how many times one tool may break.

Source code in octomate/tentacles/inkling/capabilities/tools.py
@dataclass
class ToolFailureCapability(AbstractCapability[None]):
    """Report a failed tool to the model instead of ending the turn.

    Pydantic AI ends a run when a tool raises anything but its own control-flow
    signals, so one broken call — a bad argument, a provider that blinked, a
    spell used out of order — costs the whole answer: the stream stops mid-way,
    whatever had already been drawn is abandoned, and the person is left with a
    trace id instead of a reply. The model is the one that can work around a
    failed call, and the one that can say what went wrong, so it is told.

    `ToolFailed` rather than `ModelRetry`: a call that failed for reasons the
    model did not cause is not a call to make again, and a retry spends a budget
    that ends the run when it runs out — which is the same lost turn, one attempt
    later. A failure it can read leaves it free to try another way or explain.
    Runs stay bounded by Inkling's configured `UsageLimits.request_limit`, not by
    how many times one tool may break.
    """

    async def on_tool_execute_error(
        self,
        ctx: RunContext[None],
        *,
        call: ToolCallPart,
        tool_def: ToolDefinition,
        args: ValidatedToolArgs,
        error: Exception,
    ) -> Never:
        # The model is told a sentence; the traceback is only ever seen here, so it
        # carries the exception itself and the ids to find the run it belongs to.
        react_logfire.exception(
            "tool {tool_name} failed; reported to the model",
            tool_name=call.tool_name,
            tool_call_id=call.tool_call_id,
            run_id=ctx.run_id,
            _exc_info=error,
        )
        raise ToolFailed(f"`{call.tool_name}` failed: {error}") from error

on_tool_execute_error async

on_tool_execute_error(
    ctx: RunContext[None],
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
    error: Exception,
) -> Never
Source code in octomate/tentacles/inkling/capabilities/tools.py
async def on_tool_execute_error(
    self,
    ctx: RunContext[None],
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
    error: Exception,
) -> Never:
    # The model is told a sentence; the traceback is only ever seen here, so it
    # carries the exception itself and the ids to find the run it belongs to.
    react_logfire.exception(
        "tool {tool_name} failed; reported to the model",
        tool_name=call.tool_name,
        tool_call_id=call.tool_call_id,
        run_id=ctx.run_id,
        _exc_info=error,
    )
    raise ToolFailed(f"`{call.tool_name}` failed: {error}") from error