Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

12.9 KB
Raw Blame
"""Tool registry for dynamic tool management."""

import json
import time
from dataclasses import dataclass
from typing import Any

from loguru import logger

from vikingbot.agent.remote_skills import SkillRuntimeError
from vikingbot.agent.tools.base import MultimodalToolResult, Tool, ToolContext
from vikingbot.config.schema import SessionKey
from vikingbot.hooks import HookContext
from vikingbot.hooks.manager import hook_manager
from vikingbot.integrations.langfuse import LangfuseClient
from vikingbot.sandbox.manager import SandboxManager
from vikingbot.utils.tracing import get_current_response_id


@dataclass(frozen=True)
class ToolExecutionResult:
    """Tool result plus request-scoped Skill resolution metadata."""

    result: Any
    effective_params: dict[str, Any]
    skill_uris: tuple[str, ...] = ()
    preserve_complete_result: bool = False


class ToolRegistry:
    """
    Registry for agent tools.

    Allows dynamic registration and execution of tools.
    """

    def __init__(self, config: Any = None):
        self._tools: dict[str, Tool] = {}
        self.langfuse = LangfuseClient.get_instance()
        self.config = config

    def register(self, tool: Tool) -> None:
        """
        Register a tool in the registry.

        Adds the tool to the internal registry dictionary, using the tool's name
        as the key. If a tool with the same name already exists, it will be
        silently overwritten.

        Args:
            tool: The Tool instance to register. Must have a unique name property.

        Note:
            Currently, duplicate registration silently overwrites the existing tool.
            Consider checking for duplicates if this behavior is not desired.

        Example:
            >>> registry = ToolRegistry()
            >>> tool = MyTool()
            >>> registry.register(tool)
            >>> assert registry.has(tool.name)
        """
        self._tools[tool.name] = tool

    def unregister(self, name: str) -> None:
        """
        Unregister a tool by name.

        Removes the tool with the specified name from the registry. If no tool
        with that name exists, this operation is a no-op (no error is raised).

        Args:
            name: The name of the tool to unregister.

        Example:
            >>> registry.register(my_tool)
            >>> registry.unregister(my_tool.name)
            >>> assert not registry.has(my_tool.name)
        """
        self._tools.pop(name, None)

    def get(self, name: str) -> Tool | None:
        """
        Get a tool by name.

        Retrieves the tool with the specified name from the registry.

        Args:
            name: The name of the tool to retrieve.

        Returns:
            The Tool instance if found, or None if no tool with that name exists.

        Example:
            >>> tool = registry.get("read_file")
            >>> if tool:
            ...     print(f"Found tool: {tool.description}")
        """
        return self._tools.get(name)

    def has(self, name: str) -> bool:
        """
        Check if a tool is registered.

        Args:
            name: The name of the tool to check.

        Returns:
            True if a tool with the given name is registered, False otherwise.

        Example:
            >>> if registry.has("read_file"):
            ...     print("Read file tool is available")
        """
        return name in self._tools

    def get_definitions(
        self,
        ov_tools_enable: bool = True,
        disabled_tools: list[str] | None = None,
        skill_runtime: Any | None = None,
    ) -> list[dict[str, Any]]:
        """
        Get all tool definitions in OpenAI format.

        Converts all registered tools to the OpenAI function schema format,
        suitable for use with OpenAI's function calling API.

        Args:
            ov_tools_enable: Whether to include OpenViking tools. If False,
                tools with names starting with "openviking_" will be excluded.
            disabled_tools: Tool names to hide from the model for this request.

        Returns:
            List of tool schemas in OpenAI format, where each schema contains
            the tool's type, name, description, and parameters.

        Example:
            >>> definitions = registry.get_definitions()
            >>> for defn in definitions:
            ...     print(f"Tool: {defn['function']['name']}")
        """
        tools = self._tools.values()
        if not ov_tools_enable:
            tools = [tool for tool in tools if not tool.name.startswith("openviking_")]
        if disabled_tools:
            disabled = set(disabled_tools)
            tools = [tool for tool in tools if tool.name not in disabled]
        definitions: list[dict[str, Any]] = []
        for tool in tools:
            definition = (
                skill_runtime.prepare_tool_definition(tool)
                if skill_runtime is not None
                else tool.to_schema()
            )
            if definition is not None:
                definitions.append(definition)
        return definitions

    async def execute_detailed(
        self,
        name: str,
        params: dict[str, Any],
        session_key: SessionKey,
        sandbox_manager: SandboxManager | None = None,
        sender_id: str | None = None,
        actor_peer_id: str | None = None,
        memory_peer_ids: list[str] | None = None,
        memory_owner_user_ids: list[str] | None = None,
        memory_user_ids: list[str] | None = None,
        openviking_connection: dict[str, Any] | None = None,
        channel_metadata: dict[str, Any] | None = None,
        skill_runtime: Any | None = None,
    ) -> ToolExecutionResult:
        """
        Execute a tool by name with given parameters.

        Args:
            name: Tool name.
            params: Tool parameters.
            session_key: Session key for the current session.
            sandbox_manager: Sandbox manager for file/shell operations.
            sender_id: Sender id for the current session.
            actor_peer_id: Authenticated OpenViking peer id for tool requests.
            memory_peer_ids: List of peer IDs for memory retrieval.
            memory_owner_user_ids: List of explicit OpenViking user IDs for
                trusted-mode owner-user memory lookup.
            memory_user_ids: Deprecated alias for memory_owner_user_ids.
            openviking_connection: Request-scoped OpenViking identity.
            channel_metadata: Channel-specific metadata from the inbound message.

        Returns:
            Tool execution result as string.

        Raises:
            KeyError: If tool not found.
        """
        tool = self._tools.get(name)
        if not tool:
            return ToolExecutionResult(
                result=f"Error: Tool '{name}' not found", effective_params=dict(params)
            )

        tool_context = ToolContext(
            session_key=session_key,
            sandbox_manager=sandbox_manager,
            sender_id=sender_id,
            actor_peer_id=actor_peer_id or sender_id,
            memory_peer_ids=memory_peer_ids,
            memory_owner_user_ids=memory_owner_user_ids,
            memory_user_ids=memory_user_ids,
            openviking_connection=openviking_connection,
            channel_metadata=dict(channel_metadata or {}),
            skill_runtime=skill_runtime,
        )

        # Langfuse tool call tracing - automatic for all tools
        tool_span = None
        start_time = time.time()
        result = None
        effective_params = dict(params)
        skill_uris: tuple[str, ...] = ()
        response_id = get_current_response_id()
        try:
            if self.langfuse.enabled:
                tool_ctx = self.langfuse.tool_call(
                    name=name,
                    input=params,
                    session_id=session_key.safe_name(),
                    metadata={"response_id": response_id} if response_id else None,
                )
                tool_span = tool_ctx.__enter__()

            validation_params = (
                skill_runtime.tool_params_for_validation(params)
                if skill_runtime is not None
                else params
            )
            errors = tool.validate_params(validation_params)
            if errors:
                result = f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors)
            else:
                if skill_runtime is not None:
                    prepared = await skill_runtime.prepare_tool_call(tool, params)
                    effective_params = prepared.params
                    skill_uris = prepared.skill_uris
                    if effective_params != params:
                        prepared_args = json.dumps(
                            effective_params,
                            ensure_ascii=False,
                            default=str,
                        )
                        logger.info("[TOOL_PREPARED]: {}({})", name, prepared_args[:600])
                result = await tool.execute(tool_context, **effective_params)
                if skill_runtime is not None:
                    skill_uris = skill_runtime.skill_uris_for_tool(
                        name,
                        effective_params,
                        skill_uris,
                    )
        except SkillRuntimeError as e:
            result = e
            logger.warning("Remote Skill tool call rejected: tool={} error={}", name, e)
        except Exception as e:
            result = e
            logger.exception("Tool call failed: {}", e)
        finally:
            # End Langfuse tool call tracing
            duration_ms = (time.time() - start_time) * 1000
            if tool_span is not None:
                try:
                    execute_success = not isinstance(result, Exception) and not (
                        isinstance(result, str) and result.lstrip().startswith("Error:")
                    )
                    output_str = str(result) if result is not None else None
                    self.langfuse.end_tool_call(
                        span=tool_span,
                        output=output_str,
                        success=execute_success,
                        metadata={
                            "duration_ms": duration_ms,
                            **({"response_id": response_id} if response_id else {}),
                        },
                    )
                    if hasattr(tool_span, "__exit__"):
                        tool_span.__exit__(None, None, None)
                    self.langfuse.flush()
                except Exception:
                    pass

        hook_result = await hook_manager.execute_hooks(
            context=HookContext(
                event_type="tool.post_call",
                session_key=session_key,
                workspace_id=(
                    sandbox_manager.to_workspace_id(session_key) if sandbox_manager else "shared"
                ),
                config=self.config,
                openviking_connection=openviking_connection,
            ),
            tool_name=name,
            params=effective_params,
            result=result,
        )
        result = hook_result.get("result")
        if isinstance(result, Exception):
            result = f"Error: executing {name}: {str(result)}"
        return ToolExecutionResult(
            result=result,
            effective_params=effective_params,
            skill_uris=skill_uris,
            preserve_complete_result=getattr(tool, "preserve_complete_result", False),
        )

    async def execute(
        self,
        name: str,
        params: dict[str, Any],
        session_key: SessionKey,
        sandbox_manager: SandboxManager | None = None,
        sender_id: str | None = None,
        actor_peer_id: str | None = None,
        memory_peer_ids: list[str] | None = None,
        memory_owner_user_ids: list[str] | None = None,
        memory_user_ids: list[str] | None = None,
        openviking_connection: dict[str, Any] | None = None,
        channel_metadata: dict[str, Any] | None = None,
        skill_runtime: Any | None = None,
    ) -> str:
        """Execute a tool and return the legacy string result."""
        outcome = await self.execute_detailed(
            name,
            params,
            session_key,
            sandbox_manager=sandbox_manager,
            sender_id=sender_id,
            actor_peer_id=actor_peer_id,
            memory_peer_ids=memory_peer_ids,
            memory_owner_user_ids=memory_owner_user_ids,
            memory_user_ids=memory_user_ids,
            openviking_connection=openviking_connection,
            channel_metadata=channel_metadata,
            skill_runtime=skill_runtime,
        )
        if isinstance(outcome.result, MultimodalToolResult):
            return str(outcome.result)
        return outcome.result

    @property
    def tool_names(self) -> list[str]:
        """Get list of registered tool names."""
        return list(self._tools.keys())

    def __len__(self) -> int:
        return len(self._tools)

    def __contains__(self, name: str) -> bool:
        return name in self._tools