diff --git a/pi-coding-agent/README.md b/pi-coding-agent/README.md new file mode 100644 index 0000000000..bf61eb7458 --- /dev/null +++ b/pi-coding-agent/README.md @@ -0,0 +1,5 @@ +# Should You Use the Pi Coding Agent? A Hands-on First Look + +This folder contains code associated with the Real Python tutorial [Should You Use the Pi Coding Agent? A Hands-on First Look](https://realpython.com/pi-coding-agent/). + +The `wordstats/` folder is a small Python project with a failing test, an `AGENTS.md` file, and a `.pi/` folder with a skill, a prompt template, and an extension. It also holds `ask_pi.py` and `rpc_demo.py`, which drive pi from Python. See `wordstats/README.md` for details. diff --git a/pi-coding-agent/wordstats/.pi/extensions/guard.ts b/pi-coding-agent/wordstats/.pi/extensions/guard.ts new file mode 100644 index 0000000000..2f08ed80e3 --- /dev/null +++ b/pi-coding-agent/wordstats/.pi/extensions/guard.ts @@ -0,0 +1,30 @@ +import { + type ExtensionAPI, + isToolCallEventType, +} from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // Block shell commands that contain the word rm. + pi.on("tool_call", async (event) => { + if ( + isToolCallEventType("bash", event) && + /\brm\b/.test(event.input.command) + ) { + return { block: true, reason: "rm is blocked in this project" }; + } + }); + + // A custom tool the model can call. + pi.registerTool({ + name: "count_lines", + label: "Count lines", + description: "Count the lines in a text file", + parameters: Type.Object({ path: Type.String() }), + async execute(_id, params) { + const { readFileSync } = await import("node:fs"); + const n = readFileSync(params.path, "utf8").split("\n").length - 1; + return { content: [{ type: "text", text: `${n} lines` }], details: {} }; + }, + }); +} diff --git a/pi-coding-agent/wordstats/.pi/prompts/review.md b/pi-coding-agent/wordstats/.pi/prompts/review.md new file mode 100644 index 0000000000..cde32e4b71 --- /dev/null +++ b/pi-coding-agent/wordstats/.pi/prompts/review.md @@ -0,0 +1,4 @@ +--- +description: Review the Python files for bugs +--- +Review $1 for bugs and style problems. Reply with at most three bullets. diff --git a/pi-coding-agent/wordstats/.pi/skills/changelog/SKILL.md b/pi-coding-agent/wordstats/.pi/skills/changelog/SKILL.md new file mode 100644 index 0000000000..bef2298659 --- /dev/null +++ b/pi-coding-agent/wordstats/.pi/skills/changelog/SKILL.md @@ -0,0 +1,9 @@ +--- +name: changelog +description: Add a CHANGELOG.md entry. Use when asked to update the changelog. +--- + +# Changelog + +Add one bullet under a `## Unreleased` heading in `CHANGELOG.md`, creating the +file if needed. Start the bullet with `Fixed`, `Added`, or `Changed`. diff --git a/pi-coding-agent/wordstats/AGENTS.md b/pi-coding-agent/wordstats/AGENTS.md new file mode 100644 index 0000000000..544ece24bd --- /dev/null +++ b/pi-coding-agent/wordstats/AGENTS.md @@ -0,0 +1,5 @@ +# Project rules + +- Use only the Python standard library. +- Run tests with `python -m pytest -q`. +- Keep lines under 79 characters. diff --git a/pi-coding-agent/wordstats/README.md b/pi-coding-agent/wordstats/README.md new file mode 100644 index 0000000000..925ee5b091 --- /dev/null +++ b/pi-coding-agent/wordstats/README.md @@ -0,0 +1,21 @@ +# wordstats + +A tiny word-frequency script used to try the pi coding agent. + +```console +$ python wordstats.py sample.txt +``` + +The test in `test_wordstats.py` fails until the script lowercases words and +strips punctuation. Run it with `python -m pytest -q`. + +## Files + +- `AGENTS.md`: project rules that pi reads automatically. +- `ask_pi.py`: runs `pi --mode json` and prints tool calls and the answer. +- `rpc_demo.py`: drives `pi --mode rpc` from Python. +- `.pi/extensions/guard.ts`: blocks `rm` and adds a `count_lines` tool. +- `.pi/skills/changelog/SKILL.md`: a skill. +- `.pi/prompts/review.md`: the `/review` prompt template. + +Run pi with `-a` so it trusts the project-local `.pi/` files. diff --git a/pi-coding-agent/wordstats/ask_pi.py b/pi-coding-agent/wordstats/ask_pi.py new file mode 100644 index 0000000000..4f85df6fc4 --- /dev/null +++ b/pi-coding-agent/wordstats/ask_pi.py @@ -0,0 +1,27 @@ +"""Run pi in JSON mode and print each tool call and the final answer.""" + +import json +import subprocess +import sys + +MODEL = ["--model", "openai/gpt-5.4-mini", "--thinking", "off"] +if len(sys.argv) != 2: + sys.exit("Usage: python ask_pi.py PROMPT") +cmd = ["pi", "--mode", "json", "--no-session", *MODEL, "-p", sys.argv[1]] +answer, failed = "", False +with subprocess.Popen( + cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, encoding="utf-8" +) as proc: + for line in proc.stdout: + event = json.loads(line) + if event["type"] == "tool_execution_start": + print("tool:", event["toolName"]) + elif event["type"] == "agent_end": + for msg in event["messages"]: + if msg["role"] == "assistant": + texts = [part.get("text", "") for part in msg["content"]] + answer = "".join(texts) or msg.get("errorMessage", "") + failed = msg.get("stopReason") == "error" + elif event["type"] == "agent_settled": + print("answer:", answer) +sys.exit(1 if failed else proc.returncode) diff --git a/pi-coding-agent/wordstats/requirements.txt b/pi-coding-agent/wordstats/requirements.txt new file mode 100644 index 0000000000..3fdf1e14fe --- /dev/null +++ b/pi-coding-agent/wordstats/requirements.txt @@ -0,0 +1 @@ +pytest==9.2.0 diff --git a/pi-coding-agent/wordstats/rpc_demo.py b/pi-coding-agent/wordstats/rpc_demo.py new file mode 100644 index 0000000000..848f146084 --- /dev/null +++ b/pi-coding-agent/wordstats/rpc_demo.py @@ -0,0 +1,30 @@ +"""Drive pi over RPC: two prompts in one session, then inspect the session.""" + +import json +import subprocess + +MODEL = ["--model", "openai/gpt-5.4-mini", "--thinking", "off"] +cmd = ["pi", "--mode", "rpc", "--no-session", *MODEL] +with subprocess.Popen( + cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8" +) as pi: + + def send(command): + pi.stdin.write(json.dumps(command) + "\n") + pi.stdin.flush() + for line in pi.stdout: + event = json.loads(line) + if event["type"] == "response": + print(event["command"], "->", json.dumps(event["data"])[:100]) + if event["type"] == "agent_settled" or ( + event["type"] == "response" and command["type"] != "prompt" + ): + return event + + send({"type": "prompt", "message": "Remember the number 42."}) + send( + {"type": "prompt", "message": "What number did I ask you to remember?"} + ) + send({"type": "get_last_assistant_text"}) + send({"type": "get_session_stats"}) + pi.stdin.close() diff --git a/pi-coding-agent/wordstats/sample.txt b/pi-coding-agent/wordstats/sample.txt new file mode 100644 index 0000000000..144e6e6f01 --- /dev/null +++ b/pi-coding-agent/wordstats/sample.txt @@ -0,0 +1,2 @@ +The cat saw the dog. The dog saw the cat! +A cat is not a dog, but the dog is a pet. diff --git a/pi-coding-agent/wordstats/test_wordstats.py b/pi-coding-agent/wordstats/test_wordstats.py new file mode 100644 index 0000000000..009b511c8a --- /dev/null +++ b/pi-coding-agent/wordstats/test_wordstats.py @@ -0,0 +1,5 @@ +from wordstats import top_words + + +def test_ignores_case_and_punctuation(): + assert top_words("The the THE, cat. Cat!", 2) == [("the", 3), ("cat", 2)] diff --git a/pi-coding-agent/wordstats/wordstats.py b/pi-coding-agent/wordstats/wordstats.py new file mode 100644 index 0000000000..9914d68757 --- /dev/null +++ b/pi-coding-agent/wordstats/wordstats.py @@ -0,0 +1,15 @@ +"""Count the most common words in a text file.""" + +import sys +from collections import Counter + + +def top_words(text, n=3): + words = text.split() + return Counter(words).most_common(n) + + +if __name__ == "__main__": + with open(sys.argv[1], encoding="utf-8") as file: + for word, count in top_words(file.read()): + print(f"{word}: {count}")