nanoPyCodeAgent 0.1.0__py3-none-any.whl → 0.3.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.
@@ -1,2 +1,5 @@
1
+ from nanopycodeagent.agent import run
2
+
3
+
1
4
  def main() -> None:
2
- print("hello nanoPyCodeAgent")
5
+ run()
@@ -0,0 +1,181 @@
1
+ """A minimal agent loop built on the Anthropic Python SDK.
2
+
3
+ Run the program, type a message, and Agent replies. The full conversation is
4
+ kept in memory so each turn has context. Type ``/exit`` to quit.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+
11
+ import anthropic
12
+ import httpx
13
+ from anthropic.types import MessageParam
14
+
15
+ # The model used when ANTHROPIC_MODEL is set in neither the environment nor the
16
+ # config file.
17
+ DEFAULT_MODEL = "claude-sonnet-4-6"
18
+ MAX_TOKENS = 8192
19
+ SYSTEM_PROMPT = "You are nanoPyCodeAgent, a concise and helpful coding assistant."
20
+
21
+
22
+ # User-level config file. Its ``env`` mapping supplies ANTHROPIC_* values for
23
+ # keys that are not already set in the environment (environment variables win).
24
+ def _default_settings_path() -> Path | None:
25
+ """Resolve the user-level config path, or ``None`` if home is unknown.
26
+
27
+ ``Path.home()`` raises ``RuntimeError`` when the home directory cannot be
28
+ determined (e.g. ``$HOME`` unset and no passwd entry, common in minimal
29
+ containers). Guarding it here keeps ``import nanopycodeagent`` — which runs
30
+ eagerly behind the console script — from crashing at import; a ``None`` path
31
+ simply means "no user config file".
32
+ """
33
+ try:
34
+ return Path.home() / ".nanoPyCodeAgent" / "settings.json"
35
+ except RuntimeError:
36
+ return None
37
+
38
+
39
+ SETTINGS_PATH = _default_settings_path()
40
+
41
+
42
+ def load_settings_env(path: Path | None = None) -> None:
43
+ """Apply the ``env`` mapping from the config file into ``os.environ``.
44
+
45
+ ``path`` defaults to the module-level ``SETTINGS_PATH`` (resolved at call
46
+ time, so it stays overridable). Only ``ANTHROPIC_*`` keys that are not
47
+ already present are set, so environment variables take precedence over the
48
+ config file and unrelated variables are never injected. Behaviour by case:
49
+
50
+ - Missing file, or a home directory that cannot be resolved: silently
51
+ ignored (running without a config file is normal).
52
+ - Unreadable / non-UTF-8 file, malformed JSON, non-object top level, or a
53
+ non-object ``env``: a warning is printed and the file is otherwise
54
+ ignored — a bad config never blocks startup.
55
+ - Empty, whitespace-only, or non-string values, and values the OS rejects
56
+ (e.g. an embedded NUL): skipped (the documented example ships these keys
57
+ as empty-string placeholders).
58
+ """
59
+ if path is None:
60
+ path = SETTINGS_PATH
61
+ if path is None:
62
+ return # home dir unresolvable → behave as if no config file exists
63
+ try:
64
+ raw = path.read_text(encoding="utf-8")
65
+ except FileNotFoundError:
66
+ return
67
+ except (OSError, UnicodeDecodeError) as exc:
68
+ print(f"Warning: could not read config file {path}: {exc}")
69
+ return
70
+
71
+ try:
72
+ data = json.loads(raw)
73
+ except json.JSONDecodeError as exc:
74
+ print(f"Warning: ignoring malformed config file {path}: {exc}")
75
+ return
76
+
77
+ if not isinstance(data, dict):
78
+ print(f"Warning: ignoring config file {path}: top level must be an object.")
79
+ return
80
+
81
+ env = data.get("env", {})
82
+ if not isinstance(env, dict):
83
+ print(f"Warning: ignoring 'env' in config file {path}: it must be an object.")
84
+ return
85
+
86
+ for key, value in env.items():
87
+ # Only honor ANTHROPIC_* keys (the config's documented purpose) so a
88
+ # shared settings.json cannot silently inject unrelated variables such
89
+ # as HTTPS_PROXY into the process environment.
90
+ if not key.startswith("ANTHROPIC_"):
91
+ continue
92
+ if not (isinstance(value, str) and value.strip()):
93
+ continue
94
+ try:
95
+ os.environ.setdefault(key, value.strip())
96
+ except ValueError as exc:
97
+ # e.g. an embedded NUL in the value or '=' in the key name.
98
+ print(f"Warning: ignoring invalid config entry {key!r}: {exc}")
99
+
100
+
101
+ def run() -> None:
102
+ """Start the read → ask → answer loop until the user types ``/exit``."""
103
+ # Fill any unset ANTHROPIC_* keys from the config file (environment variables
104
+ # take precedence), then let the SDK read credentials from os.environ.
105
+ load_settings_env()
106
+ client = anthropic.Anthropic()
107
+ if client.api_key is None and client.auth_token is None:
108
+ print(
109
+ "No API credentials found. Set the ANTHROPIC_API_KEY environment variable."
110
+ )
111
+ print(
112
+ "If you use a third-party / proxy service, also set ANTHROPIC_BASE_URL "
113
+ "to point at its endpoint."
114
+ )
115
+ return
116
+
117
+ # Resolve the model after load_settings_env() so a config-file ANTHROPIC_MODEL
118
+ # is honored. An empty or whitespace-only value falls back to the default.
119
+ configured_model = os.environ.get("ANTHROPIC_MODEL", "").strip()
120
+ model = configured_model or DEFAULT_MODEL
121
+
122
+ messages: list[MessageParam] = []
123
+ if configured_model:
124
+ print(f"nanoPyCodeAgent — using model {model} (from ANTHROPIC_MODEL).")
125
+ else:
126
+ print(
127
+ f"nanoPyCodeAgent — using default model {model} "
128
+ "(set ANTHROPIC_MODEL to override)."
129
+ )
130
+ print("Type a message to chat, or /exit to quit.")
131
+
132
+ while True:
133
+ try:
134
+ user_input = input("\nYou> ").strip()
135
+ except (EOFError, KeyboardInterrupt):
136
+ print()
137
+ break
138
+
139
+ if not user_input:
140
+ continue
141
+ if user_input == "/exit":
142
+ break
143
+
144
+ messages.append({"role": "user", "content": user_input})
145
+
146
+ try:
147
+ print("\nAgent> ", end="", flush=True)
148
+ # Stream the reply so text shows up as it is generated, then grab
149
+ # the accumulated message for the conversation history.
150
+ with client.messages.stream(
151
+ model=model,
152
+ max_tokens=MAX_TOKENS,
153
+ system=SYSTEM_PROMPT,
154
+ messages=messages,
155
+ ) as stream:
156
+ for text in stream.text_stream:
157
+ print(text, end="", flush=True)
158
+ message = stream.get_final_message()
159
+ print()
160
+ except KeyboardInterrupt:
161
+ # Ctrl-C while streaming the reply cancels cleanly, mirroring the
162
+ # graceful quit offered at the input prompt.
163
+ print()
164
+ break
165
+ except anthropic.AuthenticationError:
166
+ print(
167
+ "\nAuthentication failed. Check that ANTHROPIC_API_KEY is set correctly."
168
+ )
169
+ break
170
+ except (anthropic.APIError, httpx.HTTPError) as exc:
171
+ # httpx.HTTPError: the SDK wraps transport errors only around the
172
+ # initial send, so a network failure mid-stream surfaces as a raw
173
+ # httpx error during iteration rather than an anthropic.APIError.
174
+ print(f"\nRequest failed: {exc}")
175
+ messages.pop() # drop the unanswered user turn so history stays valid
176
+ continue
177
+
178
+ # Append the full content blocks so the next turn carries complete context.
179
+ messages.append({"role": "assistant", "content": message.content})
180
+
181
+ print("Bye!")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nanoPyCodeAgent
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: A nano code agent built from scratch in pure Python.
5
5
  Project-URL: Homepage, https://github.com/minixalpha/nanoPyCodeAgent
6
6
  Project-URL: Repository, https://github.com/minixalpha/nanoPyCodeAgent
@@ -13,6 +13,7 @@ Classifier: Intended Audience :: Developers
13
13
  Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3.13
15
15
  Requires-Python: >=3.13
16
+ Requires-Dist: anthropic>=0.112.0
16
17
  Description-Content-Type: text/markdown
17
18
 
18
19
  # nanoPyCodeAgent
@@ -60,6 +61,32 @@ uvx --from "git+https://github.com/minixalpha/nanoPyCodeAgent@main" nanoPyCodeAg
60
61
  uvx --from "git+https://github.com/minixalpha/nanoPyCodeAgent@v0.1.0" nanoPyCodeAgent
61
62
  ```
62
63
 
64
+ ### Configuration
65
+
66
+ Credentials and the model come from two sources: **environment variables** and
67
+ an optional user-level config file at `~/.nanoPyCodeAgent/settings.json`.
68
+ Environment variables take precedence — the config file only fills in keys you
69
+ have not set in the environment.
70
+
71
+ The config file mirrors [Claude Code's settings](https://code.claude.com/docs/en/settings):
72
+ put the values under an `env` object. Empty or whitespace-only values are ignored.
73
+
74
+ ```json
75
+ {
76
+ "env": {
77
+ "ANTHROPIC_API_KEY": "",
78
+ "ANTHROPIC_BASE_URL": "",
79
+ "ANTHROPIC_MODEL": ""
80
+ }
81
+ }
82
+ ```
83
+
84
+ | Variable | Required | Default | Description |
85
+ | --- | --- | --- | --- |
86
+ | `ANTHROPIC_API_KEY` | Yes | — | Your Anthropic API key, or the key for a third-party / proxy service. |
87
+ | `ANTHROPIC_BASE_URL` | No | `https://api.anthropic.com` | Point the SDK at a non-official / proxy endpoint. Leave it unset to use the official API — an empty value breaks requests. |
88
+ | `ANTHROPIC_MODEL` | No | `claude-sonnet-4-6` | Override the model. An empty or whitespace-only value falls back to the default. |
89
+
63
90
  ### How to Update
64
91
 
65
92
  Upgrade an installed tool to the latest release:
@@ -67,3 +94,7 @@ Upgrade an installed tool to the latest release:
67
94
  ```bash
68
95
  uv tool upgrade nanoPyCodeAgent # or: pipx upgrade nanoPyCodeAgent
69
96
  ```
97
+
98
+ ## Releasing
99
+
100
+ For maintainers: see [docs/RELEASING.md](docs/RELEASING.md) for the release process and prerequisites.
@@ -0,0 +1,7 @@
1
+ nanopycodeagent/__init__.py,sha256=pYFCw7WNkZsGXbqNLkXituX4iBy86RJ4LKKAr78XwM8,70
2
+ nanopycodeagent/agent.py,sha256=ceIw3HuZD3UHPtyxS3eGbfOE6FrKABcGybFIyOMrcmU,7074
3
+ nanopycodeagent-0.3.0.dist-info/METADATA,sha256=BJqRCUQaABx8q8-MKeMKKkBqUgx-CS6KGvvguADFcPY,3028
4
+ nanopycodeagent-0.3.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
5
+ nanopycodeagent-0.3.0.dist-info/entry_points.txt,sha256=4gU7YNzQaf2RKlOdfebOWYNYIUk2LDoyhu3G4Vgole8,57
6
+ nanopycodeagent-0.3.0.dist-info/licenses/LICENSE,sha256=g24TppoiLdeF_1_-Y7H2H_eOavKseWA5utuK83Vq1sA,1067
7
+ nanopycodeagent-0.3.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.30.1
2
+ Generator: hatchling 1.31.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,6 +0,0 @@
1
- nanopycodeagent/__init__.py,sha256=Id0gZ5s6aGlqx-V_x3Eq8ndB99ltn7lN_f-MWHC6kfU,55
2
- nanopycodeagent-0.1.0.dist-info/METADATA,sha256=LIT9891DoSO6N6OpC8gvn4SNYFkdlXkP7f5Kt9yCuoI,1794
3
- nanopycodeagent-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
4
- nanopycodeagent-0.1.0.dist-info/entry_points.txt,sha256=4gU7YNzQaf2RKlOdfebOWYNYIUk2LDoyhu3G4Vgole8,57
5
- nanopycodeagent-0.1.0.dist-info/licenses/LICENSE,sha256=g24TppoiLdeF_1_-Y7H2H_eOavKseWA5utuK83Vq1sA,1067
6
- nanopycodeagent-0.1.0.dist-info/RECORD,,