How to call Claude API from a python script
Hosted on our YouTube channel Watch on YouTube ↗
Solve this math problem step by step in plain text only. Sara is 5 years older than her brother. In 3 years, the sum of their ages will be 33. How old is each of them now?
Run it: python math_problem.py
from pathlib import Path
from anthropic import Anthropic
# For local testing only.
API_KEY = "REDACTED"
PROMPT_FILE = "input.txt"
OUTPUT_FILE = "output.txt"
def math_problem():
client = Anthropic(api_key=API_KEY)
prompt = Path(PROMPT_FILE).read_text(encoding="utf-8")
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=500,
system=(
"You are a helpful math tutor. "
"Respond in plain text only. "
"Do not use Markdown, headings, bullet points, or LaTeX."
),
messages=[
{
"role": "user",
"content": prompt
}
]
)
output_text = next(
(block.text for block in response.content if block.type == "text"),"")
with open("input.txt", "w") as f:
f.write(prompt)
with open("output.txt", "w") as f:
for block in response.content:
if block.type == "text":
f.write(block.text)
print("Prompt:")
print(prompt)
print("\nClaude's output:")
print(output_text)
print(f"\nOutput saved to {OUTPUT_FILE}")
if __name__ == "__main__":
math_problem()
Let the brother's current age be x. Then Sara's current age is x + 5, since she is 5 years older. In 3 years: Brother's age will be x + 3 Sara's age will be (x + 5) + 3 = x + 8 The sum of their ages in 3 years is 33, so: (x + 3) + (x + 8) = 33 Combine like terms: 2x + 11 = 33 Subtract 11 from both sides: 2x = 22 Divide both sides by 2: x = 11 So the brother is currently 11 years old. Sara's age is x + 5 = 11 + 5 = 16 Check: In 3 years, brother will be 14 and Sara will be 19. 14 + 19 = 33, which matches the problem statement. Answer: Sara is currently 16 years old, and her brother is currently 11 years old.
# Step 1: Install the Claude API package
```
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
# Step 2: Set your API key on math_problem.py at line 5
```
API_KEY = "REDACTED"
```
# Step 3: Run it
```
python math_problem.py
```