Skip to content

codemode_toolset

Class info

Classes

Name Children Inherits
CodeExecutionParams
llmling_models.toolsets.codemode_toolset
Parameters for Python code execution.
    CodeModeToolset
    llmling_models.toolsets.codemode_toolset
    A toolset that wraps other toolsets and provides Python code execution.

      🛈 DocStrings

      CodeModeToolset for pydantic-ai - LLM tool execution via code.

      CodeExecutionParams

      Bases: BaseModel

      Parameters for Python code execution.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      class CodeExecutionParams(BaseModel):
          """Parameters for Python code execution."""
      
          python_code: str = Field(description="Python code to execute with tools available")
      

      CodeModeToolset dataclass

      Bases: AbstractToolset[AgentDepsT]

      A toolset that wraps other toolsets and provides Python code execution.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      @dataclass(kw_only=True)
      class CodeModeToolset[AgentDepsT = None](AbstractToolset[AgentDepsT]):
          """A toolset that wraps other toolsets and provides Python code execution."""
      
          toolsets: list[AbstractToolset[Any]]
          """List of toolsets whose tools should be available in code execution"""
      
          toolset_id: str | None = None
          """Optional unique ID for this toolset"""
      
          include_docstrings: bool = True
          """Include function docstrings in tool documentation"""
      
          usage_notes: str = USAGE_NOTES
          """Usage notes to include in the tool description"""
      
          max_retries: int = 3
          """Maximum number of tool retries."""
      
          _tools_cache: tuple[tuple[str, int], list[dict[str, ToolsetTool[Any]]]] | None = field(
              default=None, init=False, repr=False
          )
      
          @property
          def id(self) -> str | None:
              """Return the toolset ID."""
              return self.toolset_id
      
          @property
          def label(self) -> str:
              """Return a label for error messages."""
              label = "CodeModeToolset"
              if self.id:
                  label += f" {self.id!r}"
              return label
      
          @property
          def tool_name_conflict_hint(self) -> str:
              """Return hint for resolving name conflicts."""
              return "Rename the toolset ID or use a different CodeModeToolset instance."
      
          async def __aenter__(self) -> Self:
              """Enter async context."""
              for toolset in self.toolsets:
                  await toolset.__aenter__()
              return self
      
          async def __aexit__(self, *args: object) -> None:
              """Exit async context."""
              for toolset in self.toolsets:
                  await toolset.__aexit__(*args)
      
          async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
              """Return the single code execution tool."""
              toolset_generator = await self._get_code_generator(ctx)
              description = toolset_generator.generate_tool_description()
              tool_def = ToolDefinition(
                  name=TOOL_NAME,
                  description=description + "\n\n" + self.usage_notes,
                  parameters_json_schema=CodeExecutionParams.model_json_schema(),
              )
              tool = ToolsetTool(
                  toolset=self,
                  tool_def=tool_def,
                  max_retries=self.max_retries,
                  args_validator=SchemaValidator(CodeExecutionParams.__pydantic_core_schema__),
              )
              return {TOOL_NAME: tool}
      
          async def call_tool(
              self,
              name: str,
              tool_args: dict[str, Any],
              ctx: RunContext[Any],
              tool: ToolsetTool[Any],
          ) -> Any:
              """Execute the Python code with all wrapped tools available."""
              if name != TOOL_NAME:
                  msg = f"Unknown tool: {name}"
                  raise ValueError(msg)
              params = CodeExecutionParams.model_validate(tool_args)
              logger.info("Executing Python code: %r", params.python_code)
              validate_code(params.python_code)
              toolset_generator = await self._get_code_generator(ctx)
              namespace = toolset_generator.generate_execution_namespace()
              try:
                  exec(params.python_code, namespace)
                  result = await namespace["main"]()
              except Exception as e:  # noqa: BLE001
                  return f"Error executing code: {e!s}"
              else:
                  return result if result is not None else "Code executed successfully"
      
          def apply(self, visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None:
              """Apply visitor to all wrapped toolsets."""
              for toolset in self.toolsets:
                  toolset.apply(visitor)
      
          def visit_and_replace(
              self,
              visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
          ) -> AbstractToolset[AgentDepsT]:
              """Visit and replace all wrapped toolsets."""
              self.toolsets = [toolset.visit_and_replace(visitor) for toolset in self.toolsets]
              return self
      
          async def _get_wrapped_tools(self, ctx: RunContext[Any]) -> list[dict[str, ToolsetTool[Any]]]:
              """List the wrapped toolsets' tools, once per run step.
      
              Listing an MCP toolset is a round trip; the listing made for the model request
              is reused when the model's code runs in the same step.
              """
              key = (ctx.run_id, ctx.run_step) if ctx.run_id is not None else None
              if key is not None and self._tools_cache is not None and self._tools_cache[0] == key:
                  return self._tools_cache[1]
              tools = list(await asyncio.gather(*(ts.get_tools(ctx) for ts in self.toolsets)))
              if key is not None:
                  self._tools_cache = (key, tools)
              return tools
      
          async def _get_code_generator(self, ctx: RunContext[Any]) -> ToolsetCodeGenerator:
              """Build the toolset code generator, its callables bound to `ctx`."""
              callables = [
                  create_tool_callable(toolset_tool, tool_name, ctx)
                  for tools in await self._get_wrapped_tools(ctx)
                  for tool_name, toolset_tool in tools.items()
              ]
              return ToolsetCodeGenerator.from_callables(callables, self.include_docstrings)
      

      id property

      id: str | None
      

      Return the toolset ID.

      include_docstrings class-attribute instance-attribute

      include_docstrings: bool = True
      

      Include function docstrings in tool documentation

      label property

      label: str
      

      Return a label for error messages.

      max_retries class-attribute instance-attribute

      max_retries: int = 3
      

      Maximum number of tool retries.

      tool_name_conflict_hint property

      tool_name_conflict_hint: str
      

      Return hint for resolving name conflicts.

      toolset_id class-attribute instance-attribute

      toolset_id: str | None = None
      

      Optional unique ID for this toolset

      toolsets instance-attribute

      toolsets: list[AbstractToolset[Any]]
      

      List of toolsets whose tools should be available in code execution

      usage_notes class-attribute instance-attribute

      usage_notes: str = USAGE_NOTES
      

      Usage notes to include in the tool description

      __aenter__ async

      __aenter__() -> Self
      

      Enter async context.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def __aenter__(self) -> Self:
          """Enter async context."""
          for toolset in self.toolsets:
              await toolset.__aenter__()
          return self
      

      __aexit__ async

      __aexit__(*args: object) -> None
      

      Exit async context.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def __aexit__(self, *args: object) -> None:
          """Exit async context."""
          for toolset in self.toolsets:
              await toolset.__aexit__(*args)
      

      apply

      apply(visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None
      

      Apply visitor to all wrapped toolsets.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      def apply(self, visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None:
          """Apply visitor to all wrapped toolsets."""
          for toolset in self.toolsets:
              toolset.apply(visitor)
      

      call_tool async

      call_tool(
          name: str, tool_args: dict[str, Any], ctx: RunContext[Any], tool: ToolsetTool[Any]
      ) -> Any
      

      Execute the Python code with all wrapped tools available.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def call_tool(
          self,
          name: str,
          tool_args: dict[str, Any],
          ctx: RunContext[Any],
          tool: ToolsetTool[Any],
      ) -> Any:
          """Execute the Python code with all wrapped tools available."""
          if name != TOOL_NAME:
              msg = f"Unknown tool: {name}"
              raise ValueError(msg)
          params = CodeExecutionParams.model_validate(tool_args)
          logger.info("Executing Python code: %r", params.python_code)
          validate_code(params.python_code)
          toolset_generator = await self._get_code_generator(ctx)
          namespace = toolset_generator.generate_execution_namespace()
          try:
              exec(params.python_code, namespace)
              result = await namespace["main"]()
          except Exception as e:  # noqa: BLE001
              return f"Error executing code: {e!s}"
          else:
              return result if result is not None else "Code executed successfully"
      

      get_tools async

      get_tools(ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]
      

      Return the single code execution tool.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
          """Return the single code execution tool."""
          toolset_generator = await self._get_code_generator(ctx)
          description = toolset_generator.generate_tool_description()
          tool_def = ToolDefinition(
              name=TOOL_NAME,
              description=description + "\n\n" + self.usage_notes,
              parameters_json_schema=CodeExecutionParams.model_json_schema(),
          )
          tool = ToolsetTool(
              toolset=self,
              tool_def=tool_def,
              max_retries=self.max_retries,
              args_validator=SchemaValidator(CodeExecutionParams.__pydantic_core_schema__),
          )
          return {TOOL_NAME: tool}
      

      visit_and_replace

      visit_and_replace(
          visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
      ) -> AbstractToolset[AgentDepsT]
      

      Visit and replace all wrapped toolsets.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      def visit_and_replace(
          self,
          visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
      ) -> AbstractToolset[AgentDepsT]:
          """Visit and replace all wrapped toolsets."""
          self.toolsets = [toolset.visit_and_replace(visitor) for toolset in self.toolsets]
          return self
      

      complex_return_type async

      complex_return_type() -> dict[str, list[int]]
      

      Test function with complex return type.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def complex_return_type() -> dict[str, list[int]]:
          """Test function with complex return type."""
          return {"numbers": [1, 2, 3]}
      

      get_todays_date async

      get_todays_date() -> str
      

      Get today's date.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def get_todays_date() -> str:
          """Get today's date."""
          return "2024-12-13"
      

      what_happened_on_date async

      what_happened_on_date(date: str) -> str
      

      Get what happened on a date.

      Source code in src/llmling_models/toolsets/codemode_toolset.py
      async def what_happened_on_date(date: str) -> str:
          """Get what happened on a date."""
          return f"On {date}, the great coding session happened!"