Your first agent¶
This page installs alpineagents and runs an agent that reads a file. You need Python 3.11 or later.
Install¶
pip install alpineagents # or: uv add alpineagents
Anthropic models read ANTHROPIC_API_KEY. OpenAI-compatible servers read OPENAI_API_KEY. To try the library first
without a key, see Run without an API key.
Run it¶
from pathlib import Path
from alpineagents import Agent, ToolError, tool
@tool
def read_file(path: str) -> str:
"""Read a text file"""
file = Path(path)
if not file.exists():
raise ToolError(f"No such file: {path}")
return file.read_text()
agent = Agent(model="claude-sonnet-5", tools=[read_file])
print(agent.run("Summarize README.md in three lines"))
@toolturns the function into a tool. The type hints and the docstring tell the model how to call it.ToolErrortells the model the call failed, and the run continues. Any other exception stops the run.Agentholds the settings: the model and the tools.agent.runrepeats turns until the model answers, then returns the answer.
What you see¶
Progress is printed to the terminal while the agent works:
[turn 1] thinking
tool read_file(path="README.md")
done 6.7KB
[turn 2] thinking
README.md describes a Python agent framework.
done: stopped by waiting_for_user (2 turns)
- In turn 1 the model asked for
read_file. The Agent ran it, and the file was 6.7KB. - In turn 2 the model had the file and answered, and the answer was printed.
- A turn is one model reply and the tool calls it asked for. The last line says why the run ended.
waiting_for_usermeans the model answered without asking for a tool. Write your own loop explains it.
agent.run returns the answer, and print shows it a second time here. To hide the progress lines, pass
reporter=None to Agent.
Run without an API key¶
FakeModel returns prepared replies in order. It needs no key and no network. This is the same agent with a fake
model:
from pathlib import Path
from alpineagents import Agent, ToolError, tool
from alpineagents.testing import FakeModel, tool_call
@tool
def read_file(path: str) -> str:
"""Read a text file"""
file = Path(path)
if not file.exists():
raise ToolError(f"No such file: {path}")
return file.read_text()
fake = FakeModel([
tool_call("read_file", path="README.md"),
"README.md describes a Python agent framework.",
])
agent = Agent(model=fake, tools=[read_file])
print(agent.run("Summarize README.md"))
The first reply asks for read_file. The Agent runs the tool, and the second reply is the answer. Run it from the
folder that has README.md. You will use FakeModel again in Test your agent.
Next¶
Give the agent tools: what the model sees of a tool, and what happens when it fails.