pygent 0.1.1__py3-none-any.whl → 0.1.3__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 CHANGED
@@ -1,4 +1,4 @@
1
- """Pacote Pygent."""
1
+ """Pygent package."""
2
2
  from importlib import metadata as _metadata
3
3
 
4
4
  try:
pygent/agent.py CHANGED
@@ -1,4 +1,4 @@
1
- """Camada de orquestração: recebe mensagens, chama OpenAI, delega ferramentas."""
1
+ """Orchestration layer: receives messages, calls the OpenAI-compatible backend and dispatches tools."""
2
2
 
3
3
  import json
4
4
  import os
@@ -8,14 +8,17 @@ import time
8
8
  from dataclasses import dataclass, field
9
9
  from typing import Any, Dict, List
10
10
 
11
- import openai
11
+ try:
12
+ import openai # type: ignore
13
+ except ModuleNotFoundError: # pragma: no cover - fallback to bundled client
14
+ from . import openai_compat as openai
12
15
  from rich.console import Console
13
16
  from rich.panel import Panel
14
17
 
15
18
  from .runtime import Runtime
16
19
  from .tools import TOOL_SCHEMAS, execute_tool
17
20
 
18
- MODEL = os.getenv("PYGENT_MODEL", "gpt-4o-mini-preview")
21
+ MODEL = os.getenv("PYGENT_MODEL", "gpt-4.1-mini")
19
22
  SYSTEM_MSG = (
20
23
  "You are Pygent, a sandboxed coding assistant.\n"
21
24
  "Respond with JSON when you need to use a tool."
pygent/cli.py CHANGED
@@ -1,12 +1,12 @@
1
- """Ponto de entrada da CLI do Pygent."""
1
+ """Command-line entry point for Pygent."""
2
2
  import argparse
3
3
 
4
4
  from .agent import run_interactive
5
5
 
6
6
  def main() -> None: # pragma: no cover
7
7
  parser = argparse.ArgumentParser(prog="pygent")
8
- parser.add_argument("--docker", dest="use_docker", action="store_true", help="executar em container Docker")
9
- parser.add_argument("--no-docker", dest="use_docker", action="store_false", help="executar localmente")
8
+ parser.add_argument("--docker", dest="use_docker", action="store_true", help="run commands in a Docker container")
9
+ parser.add_argument("--no-docker", dest="use_docker", action="store_false", help="run locally")
10
10
  parser.set_defaults(use_docker=None)
11
11
  args = parser.parse_args()
12
12
  run_interactive(use_docker=args.use_docker)
@@ -0,0 +1,71 @@
1
+ import os
2
+ import json
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List
5
+ from urllib import request
6
+
7
+ OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
9
+
10
+ @dataclass
11
+ class ToolCallFunction:
12
+ name: str
13
+ arguments: str
14
+
15
+ @dataclass
16
+ class ToolCall:
17
+ id: str
18
+ type: str
19
+ function: ToolCallFunction
20
+
21
+ @dataclass
22
+ class Message:
23
+ role: str
24
+ content: str | None = None
25
+ tool_calls: List[ToolCall] | None = None
26
+
27
+ @dataclass
28
+ class Choice:
29
+ message: Message
30
+
31
+ @dataclass
32
+ class ChatCompletion:
33
+ choices: List[Choice]
34
+
35
+
36
+ def _post(path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
37
+ data = json.dumps(payload).encode()
38
+ headers = {"Content-Type": "application/json"}
39
+ if OPENAI_API_KEY:
40
+ headers["Authorization"] = f"Bearer {OPENAI_API_KEY}"
41
+ req = request.Request(f"{OPENAI_BASE_URL}{path}", data=data, headers=headers)
42
+ with request.urlopen(req) as resp:
43
+ return json.loads(resp.read().decode())
44
+
45
+
46
+ class _ChatCompletions:
47
+ def create(self, model: str, messages: List[Dict[str, Any]], tools: Any = None, tool_choice: str | None = "auto") -> ChatCompletion:
48
+ payload: Dict[str, Any] = {"model": model, "messages": messages}
49
+ if tools is not None:
50
+ payload["tools"] = tools
51
+ if tool_choice is not None:
52
+ payload["tool_choice"] = tool_choice
53
+ raw = _post("/chat/completions", payload)
54
+ choices: List[Choice] = []
55
+ for ch in raw.get("choices", []):
56
+ msg_data = ch.get("message", {})
57
+ tool_calls = []
58
+ for tc in msg_data.get("tool_calls", []):
59
+ func = ToolCallFunction(**tc.get("function", {}))
60
+ tool_calls.append(ToolCall(id=tc.get("id", ""), type=tc.get("type", ""), function=func))
61
+ msg = Message(role=msg_data.get("role", ""), content=msg_data.get("content"), tool_calls=tool_calls or None)
62
+ choices.append(Choice(message=msg))
63
+ return ChatCompletion(choices=choices)
64
+
65
+
66
+ class _Chat:
67
+ def __init__(self) -> None:
68
+ self.completions = _ChatCompletions()
69
+
70
+
71
+ chat = _Chat()
pygent/runtime.py CHANGED
@@ -1,4 +1,4 @@
1
- """Executa comandos em um container Docker, caindo para execução local se necessário."""
1
+ """Run commands in a Docker container, falling back to local execution if needed."""
2
2
  from __future__ import annotations
3
3
 
4
4
  import os
@@ -16,7 +16,7 @@ except Exception: # pragma: no cover - optional dependency
16
16
 
17
17
 
18
18
  class Runtime:
19
- """Executa comandos em um container Docker ou localmente se Docker faltar."""
19
+ """Executes commands in a Docker container or locally if Docker is unavailable."""
20
20
 
21
21
  def __init__(self, image: str | None = None, use_docker: bool | None = None) -> None:
22
22
  self.base_dir = Path(tempfile.mkdtemp(prefix="pygent_"))
@@ -48,7 +48,7 @@ class Runtime:
48
48
 
49
49
  # ---------------- public API ----------------
50
50
  def bash(self, cmd: str, timeout: int = 30) -> str:
51
- """Roda comando no container ou localmente e devolve a saída."""
51
+ """Run a command in the container or locally and return the output."""
52
52
  if self._use_docker and self.container is not None:
53
53
  res = self.container.exec_run(
54
54
  cmd,
pygent/tools.py CHANGED
@@ -1,4 +1,4 @@
1
- """Mapa de ferramentas disponíveis para o agente."""
1
+ """Map of tools available to the agent."""
2
2
  from __future__ import annotations
3
3
  import json
4
4
  from typing import Any, Dict
pygent/ui.py ADDED
@@ -0,0 +1,36 @@
1
+ from .agent import Agent, _chat
2
+ from .runtime import Runtime
3
+ from .tools import execute_tool
4
+
5
+
6
+ def run_gui(use_docker: bool | None = None) -> None:
7
+ """Launch a simple Gradio chat interface."""
8
+ try:
9
+ import gradio as gr
10
+ except ModuleNotFoundError as exc: # pragma: no cover - optional
11
+ raise SystemExit(
12
+ "Gradio is required for the GUI. Install with 'pip install pygent[ui]'"
13
+ ) from exc
14
+
15
+ agent = Agent(runtime=Runtime(use_docker=use_docker))
16
+
17
+ def _respond(message: str, history: list[tuple[str, str]] | None) -> str:
18
+ agent.history.append({"role": "user", "content": message})
19
+ assistant_msg = _chat(agent.history)
20
+ agent.history.append(assistant_msg)
21
+ reply = assistant_msg.content or ""
22
+ if assistant_msg.tool_calls:
23
+ for call in assistant_msg.tool_calls:
24
+ output = execute_tool(call, agent.runtime)
25
+ agent.history.append({"role": "tool", "content": output, "tool_call_id": call.id})
26
+ reply += f"\n\n[tool:{call.function.name}]\n{output}"
27
+ return reply
28
+
29
+ try:
30
+ gr.ChatInterface(_respond, title="Pygent").launch()
31
+ finally:
32
+ agent.runtime.cleanup()
33
+
34
+
35
+ def main() -> None: # pragma: no cover
36
+ run_gui()
@@ -1,18 +1,21 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pygent
3
- Version: 0.1.1
4
- Summary: Pygent é um assistente de código minimalista que executa comandos em contêiner Docker quando disponível, com fallback para execução local. Veja https://marianochaves.github.io/pygent para a documentação e https://github.com/marianochaves/pygent para o código-fonte.
3
+ Version: 0.1.3
4
+ Summary: Pygent is a minimalist coding assistant that runs commands in a Docker container when available and falls back to local execution. See https://marianochaves.github.io/pygent for documentation and https://github.com/marianochaves/pygent for the source code.
5
5
  Author-email: Mariano Chaves <mchaves.software@gmail.com>
6
6
  Project-URL: Documentation, https://marianochaves.github.io/pygent
7
7
  Project-URL: Repository, https://github.com/marianochaves/pygent
8
8
  Requires-Python: >=3.9
9
9
  License-File: LICENSE
10
- Requires-Dist: openai>=1.0.0
11
10
  Requires-Dist: rich>=13.7.0
11
+ Provides-Extra: llm
12
+ Requires-Dist: openai>=1.0.0; extra == "llm"
12
13
  Provides-Extra: test
13
14
  Requires-Dist: pytest; extra == "test"
14
15
  Provides-Extra: docs
15
16
  Requires-Dist: mkdocs; extra == "docs"
16
17
  Provides-Extra: docker
17
18
  Requires-Dist: docker>=7.0.0; extra == "docker"
19
+ Provides-Extra: ui
20
+ Requires-Dist: gradio; extra == "ui"
18
21
  Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ pygent/__init__.py,sha256=3YOE3tjTGEc987Vz-TqmYwQ4ogLwTmue642Enf4NVBg,360
2
+ pygent/agent.py,sha256=1CGNB0rUmn-oiZ6HGfbr7fBwB_VtIVMR4xP3fISy_YM,2228
3
+ pygent/cli.py,sha256=Hz2FZeNMVhxoT5DjCqphXla3TisGJtPEz921LEcpxrA,527
4
+ pygent/openai_compat.py,sha256=mS6ntl70jpVH3JzfNYEDhg-z7QIQcMqQTuEV5ja7VOo,2173
5
+ pygent/py.typed,sha256=0Wh72UpGSn4lSGW-u3xMV9kxcBHMdwE15IGUqiJTwqo,52
6
+ pygent/runtime.py,sha256=33y4jieNeyZ-9nxtVlOmO236u2fDAAv2GaaEWTQDdm8,3173
7
+ pygent/tools.py,sha256=Ru2_voFgPUVc6YgBTRVByn7vWTxXAXT-loAWFMkXHno,1460
8
+ pygent/ui.py,sha256=DSW1o3gdhuEdJkyBkJmPE_NUHgvowzMjW2Hs2kGh_4A,1278
9
+ pygent-0.1.3.dist-info/licenses/LICENSE,sha256=rIktBU2VR4kHzsWul64cbom2zHIgGqYmABoZwSur6T8,1071
10
+ pygent-0.1.3.dist-info/METADATA,sha256=tyOn6Jgwd70ALAlVa21m7XulzU4nnGCC_KKquKNKsWg,913
11
+ pygent-0.1.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ pygent-0.1.3.dist-info/entry_points.txt,sha256=b9j216E5UpuMrQWRZrwyEmacNEAYvw1tCKkZqdIVIOc,70
13
+ pygent-0.1.3.dist-info/top_level.txt,sha256=P26IYsb-ThK5IkGP_bRuGJQ0Q_Y8JCcbYqVpvULdxDw,7
14
+ pygent-0.1.3.dist-info/RECORD,,
@@ -1,2 +1,3 @@
1
1
  [console_scripts]
2
2
  pygent = pygent.cli:main
3
+ pygent-ui = pygent.ui:main
@@ -1,12 +0,0 @@
1
- pygent/__init__.py,sha256=25N0WIIaSg0e3XXoDGl_OSBN2ADl-8cHm0C0EOR_opw,359
2
- pygent/agent.py,sha256=-cQnN5X_srm_rCo33GTpHjaieJ_ogsCbRyYVuy3HGlA,2071
3
- pygent/cli.py,sha256=P7N9nRRzJ64oMlWY_6sGytjVA1rBA37SYBiQzq4ey4I,527
4
- pygent/py.typed,sha256=0Wh72UpGSn4lSGW-u3xMV9kxcBHMdwE15IGUqiJTwqo,52
5
- pygent/runtime.py,sha256=1VaYyRXaRGKc6UkMpQTZJp-XIHItwp1HLZRU79-h-l8,3170
6
- pygent/tools.py,sha256=1mXaPHFtZwT9w8thDeneH-Ryd9CjViiWOeDE1BtRF6I,1471
7
- pygent-0.1.1.dist-info/licenses/LICENSE,sha256=rIktBU2VR4kHzsWul64cbom2zHIgGqYmABoZwSur6T8,1071
8
- pygent-0.1.1.dist-info/METADATA,sha256=cQlQp5YpfbF3td0GAxZxyDcNNwmPZhpt-mxA6Cwn79w,839
9
- pygent-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
- pygent-0.1.1.dist-info/entry_points.txt,sha256=ivw-s2f1abmFsbL4173DP1IuMS7sNxQ6gZuDLdu_jKQ,43
11
- pygent-0.1.1.dist-info/top_level.txt,sha256=P26IYsb-ThK5IkGP_bRuGJQ0Q_Y8JCcbYqVpvULdxDw,7
12
- pygent-0.1.1.dist-info/RECORD,,
File without changes