Skip to content

Commit 717cae4

Browse files
Fix spurious indentation in prompt() (#11)
* Fix spurious indentation in prompt() * Add tests & remove textwrap --------- Co-authored-by: rasbt <mail@sebastianraschka.com>
1 parent 408a29a commit 717cae4

2 files changed

Lines changed: 112 additions & 88 deletions

File tree

‎mini_coding_agent.py‎

Lines changed: 71 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import shutil
55
import subprocess
66
import sys
7-
import textwrap
87
import urllib.error
98
import urllib.request
109
import uuid
@@ -22,16 +21,16 @@
2221
"\\\\ \\|/ /",
2322
"`-----'__",
2423
)
25-
HELP_DETAILS = textwrap.dedent(
26-
"""\
27-
Commands:
28-
/help Show this help message.
29-
/memory Show the agent's distilled working memory.
30-
/session Show the path to the saved session file.
31-
/reset Clear the current session history and memory.
32-
/exit Exit the agent.
33-
"""
34-
).strip()
24+
HELP_DETAILS = "\n".join(
25+
[
26+
"Commands:",
27+
"/help Show this help message.",
28+
"/memory Show the agent's distilled working memory.",
29+
"/session Show the path to the saved session file.",
30+
"/reset Clear the current session history and memory.",
31+
"/exit Exit the agent.",
32+
]
33+
)
3534
MAX_TOOL_OUTPUT = 4000
3635
MAX_HISTORY = 12000
3736
IGNORED_PATH_NAMES = {".git", ".mini-coding-agent", "__pycache__", ".pytest_cache", ".ruff_cache", ".venv", "venv"}
@@ -126,21 +125,19 @@ def git(args, fallback=""):
126125
def text(self):
127126
commits = "\n".join(f"- {line}" for line in self.recent_commits) or "- none"
128127
docs = "\n".join(f"- {path}\n{snippet}" for path, snippet in self.project_docs.items()) or "- none"
129-
return textwrap.dedent(
130-
f"""\
131-
Workspace:
132-
- cwd: {self.cwd}
133-
- repo_root: {self.repo_root}
134-
- branch: {self.branch}
135-
- default_branch: {self.default_branch}
136-
- status:
137-
{self.status}
138-
- recent_commits:
139-
{commits}
140-
- project_docs:
141-
{docs}
142-
"""
143-
).strip()
128+
return "\n".join([
129+
"Workspace:",
130+
f"- cwd: {self.cwd}",
131+
f"- repo_root: {self.repo_root}",
132+
f"- branch: {self.branch}",
133+
f"- default_branch: {self.default_branch}",
134+
"- status:",
135+
self.status,
136+
"- recent_commits:",
137+
commits,
138+
"- project_docs:",
139+
docs,
140+
])
144141

145142

146143
##############################
@@ -350,49 +347,42 @@ def build_prefix(self):
350347
"<final>Done.</final>",
351348
]
352349
)
353-
return textwrap.dedent(
354-
f"""\
355-
You are Mini-Coding-Agent, a small local coding agent running through Ollama.
356-
357-
Rules:
358-
- Use tools instead of guessing about the workspace.
359-
- Return exactly one <tool>...</tool> or one <final>...</final>.
360-
- Tool calls must look like:
361-
<tool>{{"name":"tool_name","args":{{...}}}}</tool>
362-
- For write_file and patch_file with multi-line text, prefer XML style:
363-
<tool name="write_file" path="file.py"><content>...</content></tool>
364-
- Final answers must look like:
365-
<final>your answer</final>
366-
- Never invent tool results.
367-
- Keep answers concise and concrete.
368-
- If the user asks you to create or update a specific file and the path is clear, use write_file or patch_file instead of repeatedly listing files.
369-
- Before writing tests for existing code, read the implementation first.
370-
- When writing tests, match the current implementation unless the user explicitly asked you to change the code.
371-
- New files should be complete and runnable, including obvious imports.
372-
- Do not repeat the same tool call with the same arguments if it did not help. Choose a different tool or return a final answer.
373-
- Required tool arguments must not be empty. Do not call read_file, write_file, patch_file, run_shell, or delegate with args={{}}.
374-
375-
Tools:
376-
{tool_text}
377-
378-
Valid response examples:
379-
{examples}
380-
381-
{self.workspace.text()}
382-
"""
383-
).strip()
350+
rules = "\n".join([
351+
"- Use tools instead of guessing about the workspace.",
352+
"- Return exactly one <tool>...</tool> or one <final>...</final>.",
353+
"- Tool calls must look like:",
354+
' <tool>{"name":"tool_name","args":{...}}</tool>',
355+
"- For write_file and patch_file with multi-line text, prefer XML style:",
356+
' <tool name="write_file" path="file.py"><content>...</content></tool>',
357+
"- Final answers must look like:",
358+
" <final>your answer</final>",
359+
"- Never invent tool results.",
360+
"- Keep answers concise and concrete.",
361+
"- If the user asks you to create or update a specific file and the path is clear, use write_file or patch_file instead of repeatedly listing files.",
362+
"- Before writing tests for existing code, read the implementation first.",
363+
"- When writing tests, match the current implementation unless the user explicitly asked you to change the code.",
364+
"- New files should be complete and runnable, including obvious imports.",
365+
"- Do not repeat the same tool call with the same arguments if it did not help. Choose a different tool or return a final answer.",
366+
"- Required tool arguments must not be empty. Do not call read_file, write_file, patch_file, run_shell, or delegate with args={}.",
367+
])
368+
return "\n\n".join([
369+
"You are Mini-Coding-Agent, a small local coding agent running through Ollama.",
370+
"Rules:\n" + rules,
371+
"Tools:\n" + tool_text,
372+
"Valid response examples:\n" + examples,
373+
self.workspace.text(),
374+
])
384375

385376
def memory_text(self):
386377
memory = self.session["memory"]
387-
return textwrap.dedent(
388-
f"""\
389-
Memory:
390-
- task: {memory['task'] or "-"}
391-
- files: {", ".join(memory["files"]) or "-"}
392-
- notes:
393-
{chr(10).join(f"- {note}" for note in memory["notes"]) or "- none"}
394-
"""
395-
).strip()
378+
notes = "\n".join(f"- {note}" for note in memory["notes"]) or "- none"
379+
return "\n".join([
380+
"Memory:",
381+
f"- task: {memory['task'] or '-'}",
382+
f"- files: {', '.join(memory['files']) or '-'}",
383+
"- notes:",
384+
notes,
385+
])
396386

397387
#####################################################
398388
#### 4) Context Reduction And Output Management #####
@@ -430,19 +420,12 @@ def history_text(self):
430420
#### 2) Prompt Shape And Cache Reuse (Continued) #######
431421
########################################################
432422
def prompt(self, user_message):
433-
return textwrap.dedent(
434-
f"""\
435-
{self.prefix}
436-
437-
{self.memory_text()}
438-
439-
Transcript:
440-
{self.history_text()}
441-
442-
Current user request:
443-
{user_message}
444-
"""
445-
).strip()
423+
return "\n\n".join([
424+
self.prefix,
425+
self.memory_text(),
426+
"Transcript:\n" + self.history_text(),
427+
"Current user request:\n" + user_message,
428+
])
446429

447430
###############################################
448431
#### 5) Session Memory (Continued) ###########
@@ -825,15 +808,15 @@ def tool_run_shell(self, args):
825808
text=True,
826809
timeout=timeout,
827810
)
828-
return textwrap.dedent(
829-
f"""\
830-
exit_code: {result.returncode}
831-
stdout:
832-
{result.stdout.strip() or "(empty)"}
833-
stderr:
834-
{result.stderr.strip() or "(empty)"}
835-
"""
836-
).strip()
811+
return "\n".join(
812+
[
813+
f"exit_code: {result.returncode}",
814+
"stdout:",
815+
result.stdout.strip() or "(empty)",
816+
"stderr:",
817+
result.stderr.strip() or "(empty)",
818+
]
819+
)
837820

838821
def tool_write_file(self, args):
839822
path = self.path(args["path"])

‎tests/test_mini_coding_agent.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,47 @@ def test_welcome_screen_keeps_box_shape_for_long_paths(tmp_path):
254254
assert "commands: Commands:" not in welcome
255255

256256

257+
def test_prompt_top_level_sections_stay_flush_left_with_multiline_content(tmp_path):
258+
workspace = WorkspaceContext(
259+
cwd=str(tmp_path),
260+
repo_root=str(tmp_path),
261+
branch="fix/prompt-indentation",
262+
default_branch="main",
263+
status=" M mini_coding_agent.py\n?? tests/test_prompt.py",
264+
recent_commits=["abc123 first commit", "def456 second commit"],
265+
project_docs={"README.md": "line1\nline2"},
266+
)
267+
store = SessionStore(tmp_path / ".mini-coding-agent" / "sessions")
268+
agent = MiniAgent(
269+
model_client=FakeModelClient([]),
270+
workspace=workspace,
271+
session_store=store,
272+
approval_policy="auto",
273+
)
274+
agent.session["memory"] = {
275+
"task": "verify prompt formatting",
276+
"files": ["mini_coding_agent.py"],
277+
"notes": ["saw inconsistent indentation", "need regression coverage"],
278+
}
279+
agent.record({"role": "user", "content": "inspect prompt()", "created_at": "1"})
280+
agent.record(
281+
{
282+
"role": "tool",
283+
"name": "read_file",
284+
"args": {"path": "mini_coding_agent.py"},
285+
"content": " def prompt(self, user_message):\n ...",
286+
"created_at": "2",
287+
}
288+
)
289+
290+
prompt = agent.prompt("is this issue legit?")
291+
lines = prompt.splitlines()
292+
293+
for label in ["Rules:", "Tools:", "Valid response examples:", "Workspace:", "Memory:", "Transcript:", "Current user request:"]:
294+
assert label in lines
295+
assert f" {label}" not in prompt
296+
297+
257298
def _make_filler(i):
258299
return {"role": "tool", "name": "list_files", "args": {}, "content": "", "created_at": str(i)}
259300

0 commit comments

Comments
 (0)