abstractagent 0.2.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.
@@ -0,0 +1,56 @@
1
+ """Self-improvement logging tool.
2
+
3
+ This tool intentionally writes to a user-local JSONL file (not the source tree)
4
+ so it works both in monorepo dev and in installed environments.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Optional
14
+
15
+ from abstractcore.tools import tool
16
+
17
+
18
+ def _default_improvements_path() -> Path:
19
+ configured = os.getenv("ABSTRACTFRAMEWORK_IMPROVEMENTS_PATH")
20
+ if configured:
21
+ return Path(configured).expanduser()
22
+ return Path.home() / ".abstractframework" / "improvements.jsonl"
23
+
24
+
25
+ @tool(
26
+ name="self_improve",
27
+ description="Log an improvement suggestion (JSONL) for later review and prioritization.",
28
+ when_to_use="When you notice a bug, UX issue, missing feature, or an idea that should be tracked for future work",
29
+ )
30
+ def self_improve(
31
+ suggestion: str,
32
+ target: str = "unknown",
33
+ category: str = "general",
34
+ tags: Optional[Dict[str, str]] = None,
35
+ ) -> str:
36
+ """Append a self-improvement entry to a local JSONL file."""
37
+ try:
38
+ out_path = _default_improvements_path()
39
+ out_path.parent.mkdir(parents=True, exist_ok=True)
40
+
41
+ entry: Dict[str, Any] = {
42
+ "timestamp": datetime.now(timezone.utc).isoformat(),
43
+ "category": category,
44
+ "target": target,
45
+ "suggestion": suggestion,
46
+ "tags": tags or {},
47
+ "cwd": os.getcwd(),
48
+ }
49
+
50
+ with out_path.open("a", encoding="utf-8") as f:
51
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
52
+
53
+ return f"Logged improvement suggestion to {str(out_path)}"
54
+ except Exception as e:
55
+ return f"Error: {e}"
56
+
@@ -0,0 +1,5 @@
1
+ """UI components for AbstractAgent."""
2
+
3
+ from .question import QuestionUI, render_question, get_user_response
4
+
5
+ __all__ = ["QuestionUI", "render_question", "get_user_response"]
@@ -0,0 +1,197 @@
1
+ """Interactive question UI for agent-user interaction.
2
+
3
+ Provides a clean terminal UI for:
4
+ - Multiple choice questions
5
+ - Free text input
6
+ - Combined choice + free text
7
+ """
8
+
9
+ import sys
10
+ from typing import List, Optional, Dict, Any
11
+
12
+
13
+ # ANSI color codes
14
+ class Colors:
15
+ RESET = "\033[0m"
16
+ BOLD = "\033[1m"
17
+ DIM = "\033[2m"
18
+
19
+ CYAN = "\033[36m"
20
+ GREEN = "\033[32m"
21
+ YELLOW = "\033[33m"
22
+ BLUE = "\033[34m"
23
+ MAGENTA = "\033[35m"
24
+ WHITE = "\033[37m"
25
+
26
+ BG_BLUE = "\033[44m"
27
+ BG_CYAN = "\033[46m"
28
+
29
+
30
+ def _supports_color() -> bool:
31
+ """Check if terminal supports colors."""
32
+ if not hasattr(sys.stdout, "isatty"):
33
+ return False
34
+ if not sys.stdout.isatty():
35
+ return False
36
+ return True
37
+
38
+
39
+ def _c(text: str, *codes: str) -> str:
40
+ """Apply color codes if supported."""
41
+ if not _supports_color():
42
+ return text
43
+ return "".join(codes) + text + Colors.RESET
44
+
45
+
46
+ class QuestionUI:
47
+ """Interactive question UI component."""
48
+
49
+ def __init__(
50
+ self,
51
+ prompt: str,
52
+ choices: Optional[List[str]] = None,
53
+ allow_free_text: bool = True,
54
+ ):
55
+ self.prompt = prompt
56
+ self.choices = choices or []
57
+ self.allow_free_text = allow_free_text
58
+
59
+ def render(self) -> None:
60
+ """Render the question UI to terminal."""
61
+ print()
62
+ print(_c("┌" + "─" * 58 + "┐", Colors.CYAN))
63
+ print(_c("│", Colors.CYAN) + _c(" 🤖 Agent Question", Colors.BOLD, Colors.YELLOW) + " " * 39 + _c("│", Colors.CYAN))
64
+ print(_c("├" + "─" * 58 + "┤", Colors.CYAN))
65
+
66
+ # Word wrap the prompt
67
+ words = self.prompt.split()
68
+ lines = []
69
+ current_line = ""
70
+ for word in words:
71
+ if len(current_line) + len(word) + 1 <= 56:
72
+ current_line += (" " if current_line else "") + word
73
+ else:
74
+ if current_line:
75
+ lines.append(current_line)
76
+ current_line = word
77
+ if current_line:
78
+ lines.append(current_line)
79
+
80
+ for line in lines:
81
+ padding = 56 - len(line)
82
+ print(_c("│", Colors.CYAN) + f" {line}" + " " * padding + _c("│", Colors.CYAN))
83
+
84
+ print(_c("├" + "─" * 58 + "┤", Colors.CYAN))
85
+
86
+ # Render choices if any
87
+ if self.choices:
88
+ print(_c("│", Colors.CYAN) + _c(" Options:", Colors.DIM) + " " * 48 + _c("│", Colors.CYAN))
89
+ for i, choice in enumerate(self.choices, 1):
90
+ choice_text = f" [{i}] {choice}"
91
+ if len(choice_text) > 56:
92
+ choice_text = choice_text[:53] + "..."
93
+ padding = 56 - len(choice_text)
94
+ print(_c("│", Colors.CYAN) + _c(f" [{i}]", Colors.GREEN, Colors.BOLD) + f" {choice}" + " " * (padding - 4) + _c("│", Colors.CYAN))
95
+
96
+ if self.allow_free_text:
97
+ print(_c("│", Colors.CYAN) + " " * 57 + _c("│", Colors.CYAN))
98
+ free_text = f" [0] Type your own response..."
99
+ padding = 56 - len(free_text)
100
+ print(_c("│", Colors.CYAN) + _c(" [0]", Colors.MAGENTA, Colors.BOLD) + " Type your own response..." + " " * (padding - 5) + _c("│", Colors.CYAN))
101
+
102
+ print(_c("└" + "─" * 58 + "┘", Colors.CYAN))
103
+ print()
104
+
105
+ def get_input(self) -> str:
106
+ """Get user input with validation."""
107
+ while True:
108
+ if self.choices:
109
+ prompt_text = _c("Enter choice (1-" + str(len(self.choices)) + ") or 0 for custom: ", Colors.CYAN)
110
+ else:
111
+ prompt_text = _c("Your response: ", Colors.CYAN)
112
+
113
+ try:
114
+ user_input = input(prompt_text).strip()
115
+ except (EOFError, KeyboardInterrupt):
116
+ print()
117
+ return ""
118
+
119
+ if not user_input:
120
+ continue
121
+
122
+ # Handle choice selection
123
+ if self.choices:
124
+ try:
125
+ choice_num = int(user_input)
126
+ if choice_num == 0 and self.allow_free_text:
127
+ # Free text mode
128
+ print()
129
+ custom_input = input(_c("Type your response: ", Colors.MAGENTA)).strip()
130
+ if custom_input:
131
+ return custom_input
132
+ continue
133
+ elif 1 <= choice_num <= len(self.choices):
134
+ return self.choices[choice_num - 1]
135
+ else:
136
+ print(_c(f"Please enter 1-{len(self.choices)}" + (" or 0" if self.allow_free_text else ""), Colors.YELLOW))
137
+ continue
138
+ except ValueError:
139
+ # Not a number - treat as free text if allowed
140
+ if self.allow_free_text:
141
+ return user_input
142
+ print(_c("Please enter a number.", Colors.YELLOW))
143
+ continue
144
+ else:
145
+ # No choices - just return the input
146
+ return user_input
147
+
148
+ def ask(self) -> str:
149
+ """Render and get response in one call."""
150
+ self.render()
151
+ return self.get_input()
152
+
153
+
154
+ def render_question(
155
+ prompt: str,
156
+ choices: Optional[List[str]] = None,
157
+ allow_free_text: bool = True,
158
+ ) -> None:
159
+ """Render a question UI without getting input."""
160
+ ui = QuestionUI(prompt, choices, allow_free_text)
161
+ ui.render()
162
+
163
+
164
+ def get_user_response(
165
+ prompt: str,
166
+ choices: Optional[List[str]] = None,
167
+ allow_free_text: bool = True,
168
+ ) -> str:
169
+ """Show question UI and get user response.
170
+
171
+ Args:
172
+ prompt: The question to ask
173
+ choices: Optional list of choices
174
+ allow_free_text: Whether to allow free text input (always True for option 0)
175
+
176
+ Returns:
177
+ User's response string
178
+ """
179
+ ui = QuestionUI(prompt, choices, allow_free_text)
180
+ return ui.ask()
181
+
182
+
183
+ # Async version for use with asyncio
184
+ async def get_user_response_async(
185
+ prompt: str,
186
+ choices: Optional[List[str]] = None,
187
+ allow_free_text: bool = True,
188
+ ) -> str:
189
+ """Async version of get_user_response."""
190
+ import asyncio
191
+
192
+ ui = QuestionUI(prompt, choices, allow_free_text)
193
+ ui.render()
194
+
195
+ # Run input in executor to not block event loop
196
+ loop = asyncio.get_event_loop()
197
+ return await loop.run_in_executor(None, ui.get_input)
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: abstractagent
3
+ Version: 0.2.0
4
+ Summary: Agent implementations using AbstractRuntime and AbstractCore
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: abstractcore
9
+ Requires-Dist: abstractruntime
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=7.0; extra == "dev"
12
+ Dynamic: license-file
13
+
14
+ # AbstractAgent
15
+
16
+ Agent implementations using AbstractRuntime and AbstractCore.
17
+
18
+ ## Features
19
+
20
+ - **ReAct Agent**: Reason-Act-Observe loop with tool calling
21
+ - **Async REPL**: Interactive agent with real-time step visibility
22
+ - **Pause/Resume**: Durable agent state with interrupt/resume capability
23
+ - **Ask User**: Agent can ask questions with multiple choice + free text
24
+ - **Ledger Recording**: All tool calls recorded for auditability
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install -e .
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ### Simple (Factory)
35
+
36
+ ```python
37
+ from abstractagent import create_react_agent
38
+
39
+ # One-liner agent creation
40
+ agent = create_react_agent()
41
+ agent.start("List the files in the current directory")
42
+ state = agent.run_to_completion()
43
+ print(state.output["answer"])
44
+ ```
45
+
46
+ ### With Custom Tools
47
+
48
+ ```python
49
+ from abstractagent import create_react_agent
50
+ from abstractcore.tools import tool
51
+
52
+ @tool(name="my_tool", description="My custom tool")
53
+ def my_tool(query: str) -> str:
54
+ """My custom tool."""
55
+ return f"Result for {query}"
56
+
57
+ agent = create_react_agent(tools=[my_tool])
58
+ ```
59
+
60
+ ### Full Control
61
+
62
+ ```python
63
+ from abstractruntime.integrations.abstractcore import create_local_runtime
64
+ from abstractagent import ReactAgent, list_files, read_file
65
+
66
+ # Create runtime
67
+ runtime = create_local_runtime(
68
+ provider="ollama",
69
+ model="qwen3:4b-instruct-2507-q4_K_M",
70
+ )
71
+
72
+ # Create agent with specific tools
73
+ agent = ReactAgent(
74
+ runtime=runtime,
75
+ tools=[list_files, read_file],
76
+ )
77
+
78
+ agent.start("List the files in the current directory")
79
+ state = agent.run_to_completion()
80
+ print(state.output["answer"])
81
+ ```
82
+
83
+ ## State Persistence
84
+
85
+ Resume agents across process restarts:
86
+
87
+ ```python
88
+ agent = create_react_agent()
89
+ agent.start("Long running task")
90
+
91
+ # Save state before exit
92
+ agent.save_state("agent_state.json")
93
+
94
+ # ... process restarts ...
95
+
96
+ # Load and resume
97
+ agent = create_react_agent()
98
+ agent.load_state("agent_state.json")
99
+ state = agent.run_to_completion()
100
+
101
+ # Cleanup
102
+ agent.clear_state("agent_state.json")
103
+ ```
104
+
105
+ ## REPL Usage
106
+
107
+ ```bash
108
+ # Start the ReAct agent REPL
109
+ python -m abstractagent.repl --provider ollama --model qwen3:4b-instruct-2507-q4_K_M
110
+ ```
111
+
112
+ ## Architecture
113
+
114
+ ```
115
+ AbstractAgent
116
+
117
+ ├── Uses AbstractRuntime for durable execution
118
+ │ - Workflows survive crashes
119
+ │ - Pause/resume capability
120
+ │ - Ledger tracks all actions (LLM calls, tool calls)
121
+
122
+ └── Uses AbstractCore for LLM/tools
123
+ - Provider-agnostic LLM calls
124
+ - Tool registration and execution
125
+ - Tool call parsing for all model architectures
126
+ ```
127
+
128
+ ## Available Tools
129
+
130
+ - `list_files(path)` - List files and directories
131
+ - `read_file(path)` - Read file contents
132
+ - `search_files(pattern, path)` - Search for files matching a glob pattern
133
+ - `execute_command(command)` - Execute a shell command (with safety restrictions)
134
+ - `ask_user(question, choices)` - Ask the user a question (built-in)
@@ -0,0 +1,28 @@
1
+ abstractagent/__init__.py,sha256=-o1xKOyT3rhA67Iey2RCeZzU5SiFLB1mX4F2tAKH98Y,948
2
+ abstractagent/repl.py,sha256=1p5Nz-Is7_VrQaNwknAGC6rNteKiog0EmL7S2Vs-CVU,17342
3
+ abstractagent/adapters/__init__.py,sha256=yJnlyihixq71XseNzTVpOCYAGyDRu_ZJuT0qakUSpZQ,207
4
+ abstractagent/adapters/codeact_runtime.py,sha256=au4rBkr_GCqaegO9a6MVvw0O3xb9GkyST11Pd1ti5ow,14993
5
+ abstractagent/adapters/react_runtime.py,sha256=OaQzQVyumVLDa-IXu7AikKwdJ3Xcga0t099AfSQIDSs,14264
6
+ abstractagent/agents/__init__.py,sha256=7KUOj0mSa3M9JJMcXKlmw4vKbAc4fwaKpsjd8yryhKc,395
7
+ abstractagent/agents/base.py,sha256=r6psm20TVzzCvc3JG6Tp4pv-3iZ08ALK3XpCe6Gs_bE,13907
8
+ abstractagent/agents/codeact.py,sha256=87eb-1E1rtAAkOf-Y9xRg4mKoiwEh6ovXunVgFgBh-8,6657
9
+ abstractagent/agents/react.py,sha256=c-uhcgm9Zr5JQG8SSbBDItlILI8ayzSClYCKcV7Y_E8,6951
10
+ abstractagent/logic/__init__.py,sha256=6nzStnUG4w5qcWYEGfiplT6p9YrunZurifPVJKo3cLQ,473
11
+ abstractagent/logic/builtins.py,sha256=fJXSW5wXR4cbP8R51C18w190MoRHQmL9U4BytBWBmoc,858
12
+ abstractagent/logic/codeact.py,sha256=uOk7rrP4JQv8_rHBhON8u0-XbZeNpBVwbzCqfn7y5-g,6267
13
+ abstractagent/logic/react.py,sha256=ONHdcRWNBfTg32OImUPfWhz1V6rZUG1Njcb4ldyt5qo,4849
14
+ abstractagent/logic/types.py,sha256=idLhxgBaN3LY7tDmwMNL9hgWCKM5P1BRNv5YYkXMy80,595
15
+ abstractagent/sandbox/__init__.py,sha256=Vay_BJzmfMcf-cAUoapDbckCyhHGQHFzObVR98x2j3g,186
16
+ abstractagent/sandbox/interface.py,sha256=DtL_RYaXgPojW-vUIgEPi_69sleSNQU-YCWrwZ_WSoI,462
17
+ abstractagent/sandbox/local.py,sha256=mFQzFgec0qgJ8VNbB0ZjeZi58BgrIE0frMFsasKe3iI,2143
18
+ abstractagent/tools/__init__.py,sha256=4Hh6lMiiwJe7yX5JSbKpdMC8K4spk2_uLpCpkyMejD0,1196
19
+ abstractagent/tools/code_execution.py,sha256=rQBJXfTGdCxVSr7SqTH17mQ9ylImNDcT5R7_bBIvygA,1417
20
+ abstractagent/tools/self_improve.py,sha256=yOtsa0iS5OxVPLpu3MN_fPxPTEMl3Qnm1GWYJHFsZe8,1732
21
+ abstractagent/ui/__init__.py,sha256=YB27Z-kNKEW7mE7kjEc1tja3osnoBtJ9LFoKoNWp0pU,175
22
+ abstractagent/ui/question.py,sha256=PUwVZICQTJWS66Yl14WeJCpvucD8gP83zpFnXKY3Rq0,6508
23
+ abstractagent-0.2.0.dist-info/licenses/LICENSE,sha256=6rL4UIO5IdK59THf7fx0q6Hmxp5grSFi7-kWLcczseA,1083
24
+ abstractagent-0.2.0.dist-info/METADATA,sha256=Bs-M5Qhk4Whto7usmkcDHUmTZnsPUfI2eIm31ql57XY,3258
25
+ abstractagent-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
26
+ abstractagent-0.2.0.dist-info/entry_points.txt,sha256=tEaR0KtY-chcgRTd6ZVkvsqqaDpw2rvi-1RFktHGczU,56
27
+ abstractagent-0.2.0.dist-info/top_level.txt,sha256=cgtC3Vjz_piTAMmRkd73tbUxk2jPeG3IxMbo7JK3RTU,14
28
+ abstractagent-0.2.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
+ react-agent = abstractagent.repl:main
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Laurent-Philippe Albou
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.
22
+
23
+
24
+
25
+
@@ -0,0 +1 @@
1
+ abstractagent