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_msg: str = lambda: build_system_msg(DEFAULT_PERSONA)(), 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())
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_msg: str = field(default_factory=lambda: build_system_msg(DEFAULT_PERSONA))
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
__post_init__() -> None
Initialize defaults after dataclass construction.
Source code in pygent/agent.py
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 |
|
append_history(msg: Any) -> None
Source code in pygent/agent.py
231 232 233 234 235 236 237 238 239 |
|
refresh_system_message() -> None
Update the system prompt based on the current tool registry.
Source code in pygent/agent.py
241 242 243 244 245 |
|
step(user_msg: str)
Execute one round of interaction with the model.
Source code in pygent/agent.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
|
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.
Source code in pygent/agent.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
|
close() -> None
Close any open resources.
Source code in pygent/agent.py
392 393 394 395 396 397 398 |
|
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
25 26 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 |
|
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) -> str
Run a command in the container or locally and return the output.
The executed command is always included in the returned string so the caller can display what was run.
Source code in pygent/runtime.py
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 |
|
write_file(path: Union[str, Path], content: str) -> str
Source code in pygent/runtime.py
155 156 157 158 159 |
|
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
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
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
179 180 181 182 183 184 185 186 187 188 189 190 191 |
|
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
193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
cleanup() -> None
Source code in pygent/runtime.py
207 208 209 210 211 212 213 214 |
|
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
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
tool(name: str, description: str, parameters: Dict[str, Any])
Decorator for registering a tool.
Source code in pygent/tools.py
47 48 49 50 51 52 53 54 |
|
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
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
|
clear_tools() -> None
Remove all registered tools globally.
Source code in pygent/tools.py
247 248 249 250 |
|
reset_tools() -> None
Restore the default built-in tools.
Source code in pygent/tools.py
253 254 255 256 257 |
|
remove_tool(name: str) -> None
Unregister a specific tool.
Source code in pygent/tools.py
260 261 262 263 264 265 266 267 268 269 |
|
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 |
|
cmd_cp(agent: Agent, arg: str) -> None
Copy a file into the workspace.
Source code in pygent/commands.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
|
cmd_new(agent: Agent, arg: str) -> Agent
Restart the conversation with a fresh history.
Source code in pygent/commands.py
66 67 68 69 70 71 72 73 74 |
|
cmd_help(agent: Agent, arg: str) -> None
Display available commands.
Source code in pygent/commands.py
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 112 113 114 115 116 117 |
|
cmd_save(agent: Agent, arg: str) -> None
Save workspace and environment to DIR
for later use.
Source code in pygent/commands.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
cmd_tools(agent: Agent, arg: str) -> None
Enable/disable tools at runtime or list them.
Source code in pygent/commands.py
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 |
|
cmd_banned(agent: Agent, arg: str) -> None
List or modify banned commands.
Source code in pygent/commands.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
|
cmd_confirm_bash(agent: Agent, arg: str) -> None
Show or toggle confirmation for bash commands.
Source code in pygent/commands.py
187 188 189 190 191 192 193 194 195 196 197 198 |
|
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
201 202 203 204 205 206 207 208 209 210 |
|