API Reference
This section documents the main classes and helpers exposed by Pygent. The content is generated from the package docstrings.
Agent
              pygent.agent.Agent(runtime: Runtime = Runtime(), model: Model = _default_model(), model_name: str = DEFAULT_MODEL, persona: Persona = (lambda: DEFAULT_PERSONA)(), system_message_builder: Optional[Callable[[Persona, Optional[List[str]]], str]] = None, system_msg: str = '', history: List[Dict[str, Any]] = list(), history_file: Optional[pathlib.Path] = _default_history_file(), disabled_tools: List[str] = list(), log_file: Optional[pathlib.Path] = _default_log_file(), confirm_bash: bool = _default_confirm_bash(), max_non_tool_replies: Optional[int] = None)
  
      dataclass
  
    Interactive assistant handling messages and tool execution.
            runtime: Runtime = field(default_factory=Runtime)
  
      class-attribute
      instance-attribute
  
    
            model: Model = field(default_factory=_default_model)
  
      class-attribute
      instance-attribute
  
    
            model_name: str = DEFAULT_MODEL
  
      class-attribute
      instance-attribute
  
    
            persona: Persona = field(default_factory=(lambda: DEFAULT_PERSONA))
  
      class-attribute
      instance-attribute
  
    
            system_message_builder: Optional[Callable[[Persona, Optional[List[str]]], str]] = None
  
      class-attribute
      instance-attribute
  
    
            system_msg: str = ''
  
      class-attribute
      instance-attribute
  
    
            history: List[Dict[str, Any]] = field(default_factory=list)
  
      class-attribute
      instance-attribute
  
    
            history_file: Optional[pathlib.Path] = field(default_factory=_default_history_file)
  
      class-attribute
      instance-attribute
  
    
            disabled_tools: List[str] = field(default_factory=list)
  
      class-attribute
      instance-attribute
  
    
            log_file: Optional[pathlib.Path] = field(default_factory=_default_log_file)
  
      class-attribute
      instance-attribute
  
    
            confirm_bash: bool = field(default_factory=_default_confirm_bash)
  
      class-attribute
      instance-attribute
  
    
            max_non_tool_replies: Optional[int] = None
  
      class-attribute
      instance-attribute
  
    
            __post_init__() -> None
    Initialize defaults after dataclass construction.
Source code in pygent/agent.py
              78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109  |  | 
            append_history(msg: Any) -> None
    Source code in pygent/agent.py
              127 128 129 130 131 132 133 134 135  |  | 
            refresh_system_message() -> None
    Update the system prompt based on the current tool registry.
Source code in pygent/agent.py
              137 138 139 140 141 142 143 144 145 146  |  | 
            step(user_msg: str = None, role: str = 'user') -> openai_compat.Message
    Execute one round of interaction with the model.
Source code in pygent/agent.py
              148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259  |  | 
            run_until_stop(user_msg: str, max_steps: int = 20, step_timeout: Optional[float] = None, max_time: Optional[float] = None) -> Optional[openai_compat.Message]
    Run steps until stop is called or limits are reached.
The agent also stops if it replies without using a tool more than
max_non_tool_replies times consecutively.
Source code in pygent/agent.py
              261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328  |  | 
            close() -> None
    Close any open resources.
Source code in pygent/agent.py
              330 331 332 333 334 335 336  |  | 
Runtime
              pygent.runtime.Runtime(image: Optional[str] = None, use_docker: Optional[bool] = None, initial_files: Optional[list[str]] = None, workspace: Optional[Union[str, Path]] = None, banned_commands: Optional[list[str]] = None, banned_apps: Optional[list[str]] = None)
    Executes commands in a Docker container or locally if Docker is unavailable.
If workspace or the environment variable PYGENT_WORKSPACE is set,
the given directory is used as the base workspace and kept across sessions.
Create a new execution runtime.
banned_commands and banned_apps can be used to restrict what
can be run. Environment variables PYGENT_BANNED_COMMANDS and
PYGENT_BANNED_APPS extend these lists using os.pathsep as the
delimiter.
Source code in pygent/runtime.py
                    27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101  |  | 
            base_dir = Path.cwd() / f'agent_{uuid.uuid4().hex[:8]}'
  
      instance-attribute
  
    
            image = image or os.getenv('PYGENT_IMAGE', 'python:3.12-slim')
  
      instance-attribute
  
    
            client = docker.from_env()
  
      instance-attribute
  
    
            container = self.client.containers.run(self.image, name=f'pygent-{uuid.uuid4().hex[:8]}', command='sleep infinity', volumes={str(self.base_dir): {'bind': '/workspace', 'mode': 'rw'}}, working_dir='/workspace', detach=True, tty=True, network_disabled=True, mem_limit='512m', pids_limit=256)
  
      instance-attribute
  
    
            banned_commands = set(banned_commands or [])
  
      instance-attribute
  
    
            banned_apps = set(banned_apps or [])
  
      instance-attribute
  
    
            use_docker: bool
  
      property
  
    Return True if commands run inside a Docker container.
            bash(cmd: str, timeout: int = 600, stream: Optional[Callable[[str], None]] = None) -> str
    Run cmd in the sandbox and return its captured output.
If stream is provided, lines are forwarded to it as they are
produced. The returned value still contains the full output prefixed
with $ cmd just like before.
Source code in pygent/runtime.py
              109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221  |  | 
            write_file(path: Union[str, Path], content: str) -> str
    Source code in pygent/runtime.py
              223 224 225 226 227  |  | 
            read_file(path: Union[str, Path], binary: bool = False) -> str
    Return the contents of a file relative to the workspace.
Source code in pygent/runtime.py
              229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245  |  | 
            upload_file(src: Union[str, Path], dest: Optional[Union[str, Path]] = None) -> str
    Copy a local file or directory into the workspace.
Source code in pygent/runtime.py
              247 248 249 250 251 252 253 254 255 256 257 258 259  |  | 
            export_file(path: Union[str, Path], dest: Union[str, Path]) -> str
    Copy a file or directory from the workspace to a local path.
Source code in pygent/runtime.py
              261 262 263 264 265 266 267 268 269 270 271 272 273  |  | 
            cleanup() -> None
    Source code in pygent/runtime.py
              275 276 277 278 279 280 281 282  |  | 
TaskManager
              pygent.task_manager.TaskManager(agent_factory: Optional[Callable[..., 'Agent']] = None, max_tasks: Optional[int] = None, personas: Optional[list[Persona]] = None)
    Launch agents asynchronously and track their progress.
Source code in pygent/task_manager.py
                    34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  |  | 
            max_tasks = max_tasks if max_tasks is not None else int(env_max or '3')
  
      instance-attribute
  
    
            agent_factory = lambda p=None: Agent(persona=p)
  
      instance-attribute
  
    
            personas = personas
  
      instance-attribute
  
    
            tasks: Dict[str, Task] = {}
  
      instance-attribute
  
    
            start_task(prompt: str, parent_rt: Runtime, files: Optional[list[str]] = None, parent_depth: int = 0, step_timeout: Optional[float] = None, task_timeout: Optional[float] = None, persona: Union[Persona, str, None] = None) -> str
    Create a new agent and run prompt asynchronously.
persona overrides the default rotation used for delegated tasks.
Source code in pygent/task_manager.py
              79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165  |  | 
            status(task_id: str) -> str
    Source code in pygent/task_manager.py
              167 168 169 170 171 172  |  | 
            collect_file(rt: Runtime, task_id: str, path: str, dest: Optional[str] = None) -> str
    Copy a file or directory from a task workspace into rt.
Source code in pygent/task_manager.py
              174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192  |  | 
Tools
            pygent.tools
    Tool registry and helper utilities.
            TOOLS: Dict[str, Callable[..., str]] = {}
  
      module-attribute
  
    
            TOOL_SCHEMAS: List[Dict[str, Any]] = []
  
      module-attribute
  
    
            BUILTIN_TOOLS = TOOLS.copy()
  
      module-attribute
  
    
            BUILTIN_TOOL_SCHEMAS = deepcopy(TOOL_SCHEMAS)
  
      module-attribute
  
    
            register_tool(name: str, description: str, parameters: Dict[str, Any], func: Callable[..., str]) -> None
    Register a new callable tool.
Source code in pygent/tools.py
              29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  |  | 
            tool(name: str, description: str, parameters: Dict[str, Any])
    Decorator for registering a tool.
Source code in pygent/tools.py
              48 49 50 51 52 53 54 55  |  | 
            execute_tool(call: Any, rt: Runtime) -> str
    Dispatch a tool call.
Any exception raised by the tool is caught and returned as an error string so callers don't crash the CLI.
Source code in pygent/tools.py
              58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78  |  | 
            clear_tools() -> None
    Remove all registered tools globally.
Source code in pygent/tools.py
              252 253 254 255  |  | 
            reset_tools() -> None
    Restore the default built-in tools.
Source code in pygent/tools.py
              258 259 260 261 262  |  | 
            remove_tool(name: str) -> None
    Unregister a specific tool.
Source code in pygent/tools.py
              265 266 267 268 269 270 271 272 273 274  |  | 
Models
            pygent.models
    
            CUSTOM_MODEL: Optional[Model] = None
  
      module-attribute
  
    
            Model
    
              Bases: Protocol
Protocol for chat models used by :class:~pygent.agent.Agent.
            chat(messages: List[Dict[str, Any]], model: str, tools: Any) -> Message
    Return the assistant message for the given prompt.
Source code in pygent/models.py
              20 21 22  |  | 
            OpenAIModel
    Default model using the OpenAI-compatible API.
            chat(messages: List[Dict[str, Any]], model: str, tools: Any) -> Message
    Source code in pygent/models.py
              28 29 30 31 32 33 34 35 36 37 38 39 40 41 42  |  | 
            set_custom_model(model: Optional[Model]) -> None
    Set a global custom model used by :class:~pygent.agent.Agent.
Source code in pygent/models.py
              49 50 51 52 53  |  | 
Config
            pygent.config
    Utilities for loading configuration files.
            DEFAULT_CONFIG_FILES = [Path('pygent.toml'), Path.home() / '.pygent.toml']
  
      module-attribute
  
    
            load_snapshot(path: Union[str, os.PathLike[str]]) -> Path
    Load environment variables and history from a snapshot directory.
Source code in pygent/config.py
              21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41  |  | 
            run_py_config(path: Union[str, os.PathLike[str]] = 'config.py') -> None
    Execute a Python configuration file if it exists.
Source code in pygent/config.py
              44 45 46 47 48 49 50 51 52  |  | 
            load_config(path: Optional[Union[str, os.PathLike[str]]] = None) -> Dict[str, Any]
    Load configuration from a TOML file and set environment variables.
Environment variables already set take precedence over file values. Returns the configuration dictionary.
Source code in pygent/config.py
              55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111  |  | 
Errors
            pygent.errors
    
            PygentError
    
              Bases: Exception
Base error for the Pygent package.
            APIError
    
              Bases: PygentError
Raised when the OpenAI API call fails.
OpenAI Compatibility (openai_compat)
            pygent.openai_compat
    Lightweight client compatible with the OpenAI HTTP API.
            OPENAI_BASE_URL = os.getenv('OPENAI_BASE_URL', 'https://api.openai.com/v1')
  
      module-attribute
  
    
            OPENAI_API_KEY = os.getenv('OPENAI_API_KEY', '')
  
      module-attribute
  
    
            chat = _Chat()
  
      module-attribute
  
    
              ToolCallFunction(name: str, arguments: str)
  
      dataclass
  
    
            name: str
  
      instance-attribute
  
    
            arguments: str
  
      instance-attribute
  
    
              ToolCall(id: str, type: str, function: ToolCallFunction)
  
      dataclass
  
    
            id: str
  
      instance-attribute
  
    
            type: str
  
      instance-attribute
  
    
            function: ToolCallFunction
  
      instance-attribute
  
    
              Message(role: str, content: Optional[str] = None, tool_calls: Optional[List[ToolCall]] = None)
  
      dataclass
  
    
            role: str
  
      instance-attribute
  
    
            content: Optional[str] = None
  
      class-attribute
      instance-attribute
  
    
            tool_calls: Optional[List[ToolCall]] = None
  
      class-attribute
      instance-attribute
  
    
              Choice(message: Message)
  
      dataclass
  
    
            message: Message
  
      instance-attribute
  
    
              ChatCompletion(choices: List[Choice])
  
      dataclass
  
    
            choices: List[Choice]
  
      instance-attribute
  
    
            parse_message(raw: Any) -> Message
    Return a :class:Message from raw data.
Accepts dictionaries and objects from the official OpenAI client.
Source code in pygent/openai_compat.py
              104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135  |  | 
Commands
            pygent.commands
    
            COMMANDS: Dict[str, Command] = {'/cmd': Command(cmd_cmd, description='Run a raw shell command in the sandbox.', usage='/cmd <command>'), '/cp': Command(cmd_cp, description='Copy a file into the workspace.', usage='/cp SRC [DEST]'), '/new': Command(cmd_new, description='Restart the conversation with a fresh history.', usage='/new'), '/help': Command(cmd_help, description='Display available commands.', usage='/help [command]'), '/save': Command(cmd_save, description='Save workspace and environment to DIR for later use.', usage='/save DIR'), '/tools': Command(cmd_tools, description='Enable/disable tools at runtime or list them.', usage='/tools [list|enable NAME|disable NAME]'), '/banned': Command(cmd_banned, description='List or modify banned commands.', usage='/banned [list|add CMD|remove CMD]'), '/confirm-bash': Command(cmd_confirm_bash, description='Toggle confirmation before running bash commands.', usage='/confirm-bash [on|off]')}
  
      module-attribute
  
    
              Command(handler: Callable[[Agent, str], Optional[Agent]], description: str | None = None, usage: str | None = None)
    CLI command definition.
Source code in pygent/commands.py
                    34 35 36 37  |  | 
            handler = handler
  
      instance-attribute
  
    
            description = description or (handler.__doc__ or '')
  
      instance-attribute
  
    
            usage = usage
  
      instance-attribute
  
    
            __call__(agent: Agent, arg: str) -> Optional[Agent]
    Source code in pygent/commands.py
              39 40  |  | 
            cmd_cmd(agent: Agent, arg: str) -> None
    Run a raw shell command in the sandbox.
Source code in pygent/commands.py
              43 44 45 46 47 48 49 50  |  | 
            cmd_cp(agent: Agent, arg: str) -> None
    Copy a file into the workspace.
Source code in pygent/commands.py
              53 54 55 56 57 58 59 60 61 62 63 64 65 66  |  | 
            cmd_new(agent: Agent, arg: str) -> Agent
    Restart the conversation with a fresh history.
Source code in pygent/commands.py
              69 70 71 72 73 74 75 76 77  |  | 
            cmd_help(agent: Agent, arg: str) -> None
    Display available commands.
Source code in pygent/commands.py
              80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120  |  | 
            cmd_save(agent: Agent, arg: str) -> None
    Save workspace and environment to DIR for later use.
Source code in pygent/commands.py
              123 124 125 126 127 128 129 130 131 132 133 134 135 136 137  |  | 
            cmd_tools(agent: Agent, arg: str) -> None
    Enable/disable tools at runtime or list them.
Source code in pygent/commands.py
              140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165  |  | 
            cmd_banned(agent: Agent, arg: str) -> None
    List or modify banned commands.
Source code in pygent/commands.py
              168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187  |  | 
            cmd_confirm_bash(agent: Agent, arg: str) -> None
    Show or toggle confirmation for bash commands.
Source code in pygent/commands.py
              190 191 192 193 194 195 196 197 198 199 200 201  |  | 
            register_command(name: str, handler: Callable[[Agent, str], Optional[Agent]], description: str | None = None, usage: str | None = None) -> None
    Register a custom CLI command.
Source code in pygent/commands.py
              204 205 206 207 208 209 210 211 212 213  |  |