pygent 0.1.0__tar.gz
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-0.1.0/LICENSE +21 -0
- pygent-0.1.0/PKG-INFO +15 -0
- pygent-0.1.0/README.md +40 -0
- pygent-0.1.0/pygent/__init__.py +11 -0
- pygent-0.1.0/pygent/agent.py +68 -0
- pygent-0.1.0/pygent/cli.py +5 -0
- pygent-0.1.0/pygent/py.typed +1 -0
- pygent-0.1.0/pygent/runtime.py +53 -0
- pygent-0.1.0/pygent/tools.py +50 -0
- pygent-0.1.0/pygent.egg-info/PKG-INFO +15 -0
- pygent-0.1.0/pygent.egg-info/SOURCES.txt +17 -0
- pygent-0.1.0/pygent.egg-info/dependency_links.txt +1 -0
- pygent-0.1.0/pygent.egg-info/entry_points.txt +2 -0
- pygent-0.1.0/pygent.egg-info/requires.txt +9 -0
- pygent-0.1.0/pygent.egg-info/top_level.txt +1 -0
- pygent-0.1.0/pyproject.toml +25 -0
- pygent-0.1.0/setup.cfg +4 -0
- pygent-0.1.0/tests/test_tools.py +43 -0
- pygent-0.1.0/tests/test_version.py +19 -0
pygent-0.1.0/LICENSE
ADDED
@@ -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.
|
pygent-0.1.0/PKG-INFO
ADDED
@@ -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
|
pygent-0.1.0/README.md
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
# Pygent
|
2
|
+
|
3
|
+
Pygent é um assistente de código minimalista que executa cada tarefa em um
|
4
|
+
container Docker isolado. O objetivo é facilitar execução de comandos de forma
|
5
|
+
segura e reprodutível, mantendo o histórico de mensagens da conversa.
|
6
|
+
|
7
|
+
## Instalação
|
8
|
+
|
9
|
+
Recomendação mais simples é usar `pip`:
|
10
|
+
|
11
|
+
```bash
|
12
|
+
pip install -e .
|
13
|
+
```
|
14
|
+
|
15
|
+
O projeto requer Python ≥ 3.9 e depende de `docker`, `openai` e `rich`.
|
16
|
+
|
17
|
+
## Uso via CLI
|
18
|
+
|
19
|
+
Após instalado, inicie a interface interativa com:
|
20
|
+
|
21
|
+
```bash
|
22
|
+
pygent
|
23
|
+
```
|
24
|
+
|
25
|
+
Digita mensagens normalmente e utilize `/exit` para sair.
|
26
|
+
|
27
|
+
## Uso via API
|
28
|
+
|
29
|
+
Também é possível integrar diretamente com o código Python:
|
30
|
+
|
31
|
+
```python
|
32
|
+
from pygent import Agent
|
33
|
+
|
34
|
+
ag = Agent()
|
35
|
+
ag.step("echo hello") # roda dentro do container
|
36
|
+
ag.runtime.cleanup()
|
37
|
+
```
|
38
|
+
|
39
|
+
Veja a pasta `examples/` para scripts mais completos.
|
40
|
+
|
@@ -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"]
|
@@ -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()
|
@@ -0,0 +1 @@
|
|
1
|
+
"""empty file to indicate PEP-561 typing support"""
|
@@ -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)
|
@@ -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,17 @@
|
|
1
|
+
LICENSE
|
2
|
+
README.md
|
3
|
+
pyproject.toml
|
4
|
+
pygent/__init__.py
|
5
|
+
pygent/agent.py
|
6
|
+
pygent/cli.py
|
7
|
+
pygent/py.typed
|
8
|
+
pygent/runtime.py
|
9
|
+
pygent/tools.py
|
10
|
+
pygent.egg-info/PKG-INFO
|
11
|
+
pygent.egg-info/SOURCES.txt
|
12
|
+
pygent.egg-info/dependency_links.txt
|
13
|
+
pygent.egg-info/entry_points.txt
|
14
|
+
pygent.egg-info/requires.txt
|
15
|
+
pygent.egg-info/top_level.txt
|
16
|
+
tests/test_tools.py
|
17
|
+
tests/test_version.py
|
@@ -0,0 +1 @@
|
|
1
|
+
|
@@ -0,0 +1 @@
|
|
1
|
+
pygent
|
@@ -0,0 +1,25 @@
|
|
1
|
+
[project]
|
2
|
+
name = "pygent"
|
3
|
+
version = "0.1.0"
|
4
|
+
description = "A minimal agentic coding assistant that runs each task in a secure container."
|
5
|
+
authors = [ { name = "Mariano Chaves", email = "mchaves.software@gmail.com" } ]
|
6
|
+
requires-python = ">=3.9"
|
7
|
+
dependencies = [
|
8
|
+
"openai>=1.0.0", # interface com modelos da OpenAI
|
9
|
+
"docker>=7.0.0", # manipular containers
|
10
|
+
"rich>=13.7.0" # saídas coloridas (opcional)
|
11
|
+
]
|
12
|
+
|
13
|
+
[project.scripts]
|
14
|
+
pygent = "pygent.cli:main"
|
15
|
+
|
16
|
+
[project.optional-dependencies]
|
17
|
+
test = ["pytest"]
|
18
|
+
docs = ["mkdocs"]
|
19
|
+
|
20
|
+
[tool.setuptools.package-data]
|
21
|
+
"pygent" = ["py.typed"]
|
22
|
+
|
23
|
+
[build-system]
|
24
|
+
requires = ["setuptools>=64", "wheel"]
|
25
|
+
build-backend = "setuptools.build_meta"
|
pygent-0.1.0/setup.cfg
ADDED
@@ -0,0 +1,43 @@
|
|
1
|
+
import os
|
2
|
+
import sys
|
3
|
+
import types
|
4
|
+
|
5
|
+
sys.modules.setdefault('openai', types.ModuleType('openai'))
|
6
|
+
sys.modules.setdefault('docker', types.ModuleType('docker'))
|
7
|
+
rich_mod = types.ModuleType('rich')
|
8
|
+
console_mod = types.ModuleType('console')
|
9
|
+
console_mod.Console = lambda *a, **k: None
|
10
|
+
panel_mod = types.ModuleType('panel')
|
11
|
+
panel_mod.Panel = lambda *a, **k: None
|
12
|
+
sys.modules.setdefault('rich', rich_mod)
|
13
|
+
sys.modules.setdefault('rich.console', console_mod)
|
14
|
+
sys.modules.setdefault('rich.panel', panel_mod)
|
15
|
+
|
16
|
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
17
|
+
|
18
|
+
from pygent import tools
|
19
|
+
|
20
|
+
class DummyRuntime:
|
21
|
+
def bash(self, cmd: str):
|
22
|
+
return f"ran {cmd}"
|
23
|
+
def write_file(self, path: str, content: str):
|
24
|
+
return f"wrote {path}"
|
25
|
+
|
26
|
+
def test_execute_bash():
|
27
|
+
call = type('Call', (), {
|
28
|
+
'function': type('Func', (), {
|
29
|
+
'name': 'bash',
|
30
|
+
'arguments': '{"cmd": "ls"}'
|
31
|
+
})
|
32
|
+
})()
|
33
|
+
assert tools.execute_tool(call, DummyRuntime()) == 'ran ls'
|
34
|
+
|
35
|
+
|
36
|
+
def test_execute_write_file():
|
37
|
+
call = type('Call', (), {
|
38
|
+
'function': type('Func', (), {
|
39
|
+
'name': 'write_file',
|
40
|
+
'arguments': '{"path": "foo.txt", "content": "bar"}'
|
41
|
+
})
|
42
|
+
})()
|
43
|
+
assert tools.execute_tool(call, DummyRuntime()) == 'wrote foo.txt'
|
@@ -0,0 +1,19 @@
|
|
1
|
+
import importlib
|
2
|
+
import sys
|
3
|
+
import types
|
4
|
+
|
5
|
+
# Stub external dependencies so the package can be imported without network
|
6
|
+
sys.modules.setdefault('openai', types.ModuleType('openai'))
|
7
|
+
sys.modules.setdefault('docker', types.ModuleType('docker'))
|
8
|
+
rich_mod = types.ModuleType('rich')
|
9
|
+
console_mod = types.ModuleType('console')
|
10
|
+
console_mod.Console = lambda *a, **k: None
|
11
|
+
panel_mod = types.ModuleType('panel')
|
12
|
+
panel_mod.Panel = lambda *a, **k: None
|
13
|
+
sys.modules.setdefault('rich', rich_mod)
|
14
|
+
sys.modules.setdefault('rich.console', console_mod)
|
15
|
+
sys.modules.setdefault('rich.panel', panel_mod)
|
16
|
+
|
17
|
+
def test_version_string():
|
18
|
+
pkg = importlib.import_module('pygent')
|
19
|
+
assert isinstance(pkg.__version__, str)
|