Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
149 lines (121 loc) · 3.97 KB
/
Copy pathmain.py
File metadata and controls
149 lines (121 loc) · 3.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/env python3
"""
Claude Platform Python Example
================================
Demonstrates the Anthropic Python SDK:
- Single message completion with prompt caching
- Streaming response
- Multi-turn interactive chat
Setup:
uv pip install anthropic python-dotenv
$env:ANTHROPIC_API_KEY = "sk-ant-..." # Windows PowerShell
Usage:
python main.py
"""
import os
import sys
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
except ImportError:
pass
try:
import anthropic
except ImportError:
print("ERROR: anthropic package not installed.")
print(" Run: uv pip install anthropic python-dotenv")
sys.exit(1)
MODEL = "claude-sonnet-4-6"
SYSTEM = (
"You are a helpful, concise assistant. "
"Answer questions clearly and accurately."
)
def _make_client() -> anthropic.Anthropic:
key = os.environ.get("ANTHROPIC_API_KEY", "")
if not key:
print("ERROR: ANTHROPIC_API_KEY is not set.")
print(" PowerShell: $env:ANTHROPIC_API_KEY = 'sk-ant-...'")
print(" Or copy .env.example -> .env and add your key.")
sys.exit(1)
return anthropic.Anthropic(api_key=key)
def single_message(client: anthropic.Anthropic, prompt: str) -> str:
"""One-shot completion with a cached system prompt."""
resp = client.messages.create(
model=MODEL,
max_tokens=1024,
system=[
{
"type": "text",
"text": SYSTEM,
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": prompt}],
)
return resp.content[0].text
def stream_message(client: anthropic.Anthropic, prompt: str) -> None:
"""Stream tokens to stdout as they arrive."""
print("Claude: ", end="", flush=True)
with client.messages.stream(
model=MODEL,
max_tokens=1024,
system=[
{
"type": "text",
"text": SYSTEM,
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": prompt}],
) as stream:
for chunk in stream.text_stream:
print(chunk, end="", flush=True)
print()
def interactive_chat(client: anthropic.Anthropic) -> None:
"""Multi-turn chat loop that keeps the full conversation history."""
history: list[dict] = []
print(f"\n[Interactive Chat — {MODEL}]")
print("Type 'quit' or press Ctrl+C to exit.\n")
while True:
try:
user_input = input("You: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye!")
break
if not user_input:
continue
if user_input.lower() in ("quit", "exit", "bye"):
print("Goodbye!")
break
history.append({"role": "user", "content": user_input})
resp = client.messages.create(
model=MODEL,
max_tokens=2048,
system=[
{
"type": "text",
"text": SYSTEM,
"cache_control": {"type": "ephemeral"},
}
],
messages=history,
)
reply = resp.content[0].text
history.append({"role": "assistant", "content": reply})
print(f"Claude: {reply}")
u = resp.usage
cached = getattr(u, "cache_read_input_tokens", 0) or 0
print(f" [tokens in={u.input_tokens} cached={cached} out={u.output_tokens}]\n")
def main() -> None:
client = _make_client()
print("=== 1. Single message ===")
answer = single_message(client, "What is prompt caching and why does it save money?")
print(f"Claude: {answer}\n")
print("=== 2. Streaming ===")
stream_message(client, "List three things that make Python popular. One sentence each.")
print()
print("=== 3. Interactive chat ===")
interactive_chat(client)
if __name__ == "__main__":
main()