-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_agent.py
More file actions
63 lines (46 loc) · 1.75 KB
/
sample_agent.py
File metadata and controls
63 lines (46 loc) · 1.75 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
"""Simple Q&A agent that answers questions about Python using the Anthropic SDK."""
import anthropic
def create_python_qa_agent():
"""Create a multi-turn Q&A agent that answers Python questions."""
client = anthropic.Anthropic()
system_prompt = (
"You are a Python expert. Answer questions about Python clearly and concisely. "
"Include short code examples when helpful. If a question is not about Python, "
"politely redirect the user to ask a Python-related question."
)
messages = []
def ask(question: str) -> str:
"""Send a question and return the answer."""
messages.append({"role": "user", "content": question})
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=16000,
system=system_prompt,
thinking={"type": "adaptive"},
messages=messages,
) as stream:
response = stream.get_final_message()
assistant_text = next(
(b.text for b in response.content if b.type == "text"), ""
)
messages.append({"role": "assistant", "content": response.content})
return assistant_text
return ask
def main():
"""Interactive Q&A loop for Python questions."""
ask = create_python_qa_agent()
print("Python Q&A Agent (powered by Claude)")
print("Type 'quit' to exit.\n")
while True:
question = input("Ask about Python: ").strip()
if question.lower() in ("quit", "exit", "q"):
break
if not question:
continue
try:
answer = ask(question)
print(f"\n{answer}\n")
except anthropic.APIError as e:
print(f"\nAPI error: {e}\n")
if __name__ == "__main__":
main()