Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pi-coding-agent/README.md
Original file line number Diff line number Diff line change
@@ -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.
30 changes: 30 additions & 0 deletions pi-coding-agent/wordstats/.pi/extensions/guard.ts
Original file line number Diff line number Diff line change
@@ -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: {} };
},
});
}
4 changes: 4 additions & 0 deletions pi-coding-agent/wordstats/.pi/prompts/review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
description: Review the Python files for bugs
---
Review $1 for bugs and style problems. Reply with at most three bullets.
9 changes: 9 additions & 0 deletions pi-coding-agent/wordstats/.pi/skills/changelog/SKILL.md
Original file line number Diff line number Diff line change
@@ -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`.
5 changes: 5 additions & 0 deletions pi-coding-agent/wordstats/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Project rules

- Use only the Python standard library.
- Run tests with `python -m pytest -q`.
- Keep lines under 79 characters.
21 changes: 21 additions & 0 deletions pi-coding-agent/wordstats/README.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 27 additions & 0 deletions pi-coding-agent/wordstats/ask_pi.py
Original file line number Diff line number Diff line change
@@ -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)
1 change: 1 addition & 0 deletions pi-coding-agent/wordstats/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==9.2.0
30 changes: 30 additions & 0 deletions pi-coding-agent/wordstats/rpc_demo.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 2 additions & 0 deletions pi-coding-agent/wordstats/sample.txt
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions pi-coding-agent/wordstats/test_wordstats.py
Original file line number Diff line number Diff line change
@@ -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)]
15 changes: 15 additions & 0 deletions pi-coding-agent/wordstats/wordstats.py
Original file line number Diff line number Diff line change
@@ -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}")
Loading