| 1 |
import pydantic |
| 2 |
|
| 3 |
import anthropic |
| 4 |
|
| 5 |
|
| 6 |
class Order(pydantic.BaseModel): |
| 7 |
product_name: str |
| 8 |
price: float |
| 9 |
quantity: int |
| 10 |
|
| 11 |
|
| 12 |
client = anthropic.Anthropic() |
| 13 |
|
| 14 |
prompt = """ |
| 15 |
Extract the product name, price, and quantity from this customer message: |
| 16 |
"Hi, I'd like to order 2 packs of Green Tea for 5.50 dollars each." |
| 17 |
""" |
| 18 |
|
| 19 |
with client.messages.stream( |
| 20 |
model="claude-sonnet-5-5", |
| 21 |
messages=[{"role": "user", "content": prompt}], |
| 22 |
max_tokens=1024, |
| 23 |
output_format=Order, |
| 24 |
) as stream: |
| 25 |
for event in stream: |
| 26 |
if event.type == "text": |
| 27 |
print(event.parsed_snapshot()) |
| 28 |
|
| 29 |
final_message = stream.get_final_message() |
| 30 |
print(f"\nFinal parsed order: {final_message.parsed_output}") |