pygent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pygent/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Pacote Pygent."""
2
+ from importlib import metadata as _metadata
3
+
4
+ try:
5
+ __version__: str = _metadata.version(__name__)
6
+ except _metadata.PackageNotFoundError: # pragma: no cover - fallback for tests
7
+ __version__ = "0.0.0"
8
+
9
+ from .agent import Agent, run_interactive # noqa: E402,F401, must come after __version__
10
+
11
+ __all__ = ["Agent", "run_interactive"]
pygent/agent.py ADDED
@@ -0,0 +1,68 @@
1
+ """Camada de orquestração: recebe mensagens, chama OpenAI, delega ferramentas."""
2
+
3
+ import json
4
+ import os
5
+ import pathlib
6
+ import uuid
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Dict, List
10
+
11
+ import openai
12
+ from rich.console import Console
13
+ from rich.panel import Panel
14
+
15
+ from .runtime import Runtime
16
+ from .tools import TOOL_SCHEMAS, execute_tool
17
+
18
+ MODEL = os.getenv("PYGENT_MODEL", "gpt-4o-mini-preview")
19
+ SYSTEM_MSG = (
20
+ "You are Pygent, a sandboxed coding assistant.\n"
21
+ "Respond with JSON when you need to use a tool."
22
+ )
23
+
24
+ console = Console()
25
+
26
+
27
+ def _chat(messages: List[Dict[str, str]]) -> str:
28
+ resp = openai.chat.completions.create(
29
+ model=MODEL,
30
+ messages=messages,
31
+ tools=TOOL_SCHEMAS,
32
+ tool_choice="auto",
33
+ )
34
+ return resp.choices[0].message
35
+
36
+
37
+ @dataclass
38
+ class Agent:
39
+ runtime: Runtime = field(default_factory=Runtime)
40
+ history: List[Dict[str, Any]] = field(default_factory=lambda: [
41
+ {"role": "system", "content": SYSTEM_MSG}
42
+ ])
43
+
44
+ def step(self, user_msg: str) -> None:
45
+ self.history.append({"role": "user", "content": user_msg})
46
+ assistant_msg = _chat(self.history)
47
+ self.history.append(assistant_msg)
48
+
49
+ if assistant_msg.tool_calls:
50
+ for call in assistant_msg.tool_calls:
51
+ output = execute_tool(call, self.runtime)
52
+ self.history.append({"role": "tool", "content": output, "tool_call_id": call.id})
53
+ console.print(Panel(output, title=f"tool:{call.function.name}"))
54
+ else:
55
+ console.print(assistant_msg.content)
56
+
57
+
58
+ def run_interactive() -> None: # pragma: no cover
59
+ agent = Agent()
60
+ console.print("[bold green]Pygent[/] iniciado. (digite /exit para sair)")
61
+ try:
62
+ while True:
63
+ user_msg = console.input("[cyan]vc> [/]" )
64
+ if user_msg.strip() in {"/exit", "quit", "q"}:
65
+ break
66
+ agent.step(user_msg)
67
+ finally:
68
+ agent.runtime.cleanup()
pygent/cli.py ADDED
@@ -0,0 +1,5 @@
1
+ """Ponto de entrada da CLI do Pygent."""
2
+ from .agent import run_interactive
3
+
4
+ def main() -> None: # pragma: no cover
5
+ run_interactive()
pygent/py.typed ADDED
@@ -0,0 +1 @@
1
+ """empty file to indicate PEP-561 typing support"""
pygent/runtime.py ADDED
@@ -0,0 +1,53 @@
1
+ """Isola as execuções num container Docker efêmero."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import tempfile
7
+ import subprocess
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import Union
11
+
12
+ import docker
13
+
14
+
15
+ class Runtime:
16
+ """Cada instância corresponde a um diretório + container dedicados."""
17
+
18
+ def __init__(self, image: str | None = None) -> None:
19
+ self.base_dir = Path(tempfile.mkdtemp(prefix="pygent_"))
20
+ self.image = image or os.getenv("PYGENT_IMAGE", "python:3.12-slim")
21
+ self.client = docker.from_env()
22
+ self.container = self.client.containers.run(
23
+ self.image,
24
+ name=f"pygent-{uuid.uuid4().hex[:8]}",
25
+ command="sleep infinity",
26
+ volumes={str(self.base_dir): {"bind": "/workspace", "mode": "rw"}},
27
+ working_dir="/workspace",
28
+ detach=True,
29
+ tty=True,
30
+ network_disabled=True,
31
+ mem_limit="512m",
32
+ pids_limit=256,
33
+ )
34
+
35
+ # ---------------- public API ----------------
36
+ def bash(self, cmd: str, timeout: int = 30) -> str:
37
+ """Roda comando dentro do container e devolve saída combinada."""
38
+ res = self.container.exec_run(cmd, workdir="/workspace", demux=True, tty=False, timeout=timeout)
39
+ stdout, stderr = res.output if isinstance(res.output, tuple) else (res.output, b"")
40
+ return (stdout or b"").decode() + (stderr or b"").decode()
41
+
42
+ def write_file(self, rel_path: Union[str, Path], content: str) -> str:
43
+ p = self.base_dir / rel_path
44
+ p.parent.mkdir(parents=True, exist_ok=True)
45
+ p.write_text(content)
46
+ return f"Wrote {p.relative_to(self.base_dir)}"
47
+
48
+ def cleanup(self) -> None:
49
+ try:
50
+ self.container.kill()
51
+ finally:
52
+ self.container.remove(force=True)
53
+ shutil.rmtree(self.base_dir, ignore_errors=True)
pygent/tools.py ADDED
@@ -0,0 +1,50 @@
1
+ """Mapa de ferramentas disponíveis para o agente."""
2
+ from __future__ import annotations
3
+ import json
4
+ from typing import Any, Dict
5
+
6
+ from .runtime import Runtime
7
+
8
+ TOOL_SCHEMAS = [
9
+ {
10
+ "type": "function",
11
+ "function": {
12
+ "name": "bash",
13
+ "description": "Run a shell command inside the sandboxed container.",
14
+ "parameters": {
15
+ "type": "object",
16
+ "properties": {
17
+ "cmd": {"type": "string", "description": "Command to execute"}
18
+ },
19
+ "required": ["cmd"],
20
+ },
21
+ },
22
+ },
23
+ {
24
+ "type": "function",
25
+ "function": {
26
+ "name": "write_file",
27
+ "description": "Create or overwrite a file in the workspace.",
28
+ "parameters": {
29
+ "type": "object",
30
+ "properties": {
31
+ "path": {"type": "string"},
32
+ "content": {"type": "string"},
33
+ },
34
+ "required": ["path", "content"],
35
+ },
36
+ },
37
+ },
38
+ ]
39
+
40
+ # --------------- dispatcher ---------------
41
+
42
+ def execute_tool(call: Any, rt: Runtime) -> str: # pragma: no cover, Any→openai.types.ToolCall
43
+ name = call.function.name
44
+ args: Dict[str, Any] = json.loads(call.function.arguments)
45
+
46
+ if name == "bash":
47
+ return rt.bash(**args)
48
+ if name == "write_file":
49
+ return rt.write_file(**args)
50
+ return f"⚠️ unknown tool {name}"
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: pygent
3
+ Version: 0.1.0
4
+ Summary: A minimal agentic coding assistant that runs each task in a secure container.
5
+ Author-email: Mariano Chaves <mchaves.software@gmail.com>
6
+ Requires-Python: >=3.9
7
+ License-File: LICENSE
8
+ Requires-Dist: openai>=1.0.0
9
+ Requires-Dist: docker>=7.0.0
10
+ Requires-Dist: rich>=13.7.0
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest; extra == "test"
13
+ Provides-Extra: docs
14
+ Requires-Dist: mkdocs; extra == "docs"
15
+ Dynamic: license-file
@@ -0,0 +1,12 @@
1
+ pygent/__init__.py,sha256=25N0WIIaSg0e3XXoDGl_OSBN2ADl-8cHm0C0EOR_opw,359
2
+ pygent/agent.py,sha256=vOV0Zx3JzeRtJb-QRdBr-DzFIPVIt2bcZb8xeHlOxI0,2003
3
+ pygent/cli.py,sha256=qOuIHAtt--NFbPRl-RuGSK7mfFj-4CtU4rRr6KYPgKc,139
4
+ pygent/py.typed,sha256=0Wh72UpGSn4lSGW-u3xMV9kxcBHMdwE15IGUqiJTwqo,52
5
+ pygent/runtime.py,sha256=jaLhAT-2Wo6DxmPksFyHvVaCNOOu_c7BgrENsIuwTlI,1897
6
+ pygent/tools.py,sha256=1mXaPHFtZwT9w8thDeneH-Ryd9CjViiWOeDE1BtRF6I,1471
7
+ pygent-0.1.0.dist-info/licenses/LICENSE,sha256=rIktBU2VR4kHzsWul64cbom2zHIgGqYmABoZwSur6T8,1071
8
+ pygent-0.1.0.dist-info/METADATA,sha256=Rjva3PKq9hN83Piv8w7ppyNZpgzOnWOjGOYXh7BI7v4,468
9
+ pygent-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ pygent-0.1.0.dist-info/entry_points.txt,sha256=ivw-s2f1abmFsbL4173DP1IuMS7sNxQ6gZuDLdu_jKQ,43
11
+ pygent-0.1.0.dist-info/top_level.txt,sha256=P26IYsb-ThK5IkGP_bRuGJQ0Q_Y8JCcbYqVpvULdxDw,7
12
+ pygent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pygent = pygent.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mariano Chaves
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pygent