()
| 16 | |
| 17 | |
| 18 | def main() -> None: |
| 19 | thread = client.beta.messages.thread( |
| 20 | model="claude-sonnet-5-5", |
| 21 | max_tokens=1024, |
| 22 | system="You are a support agent for Acme. Keep replies short.", |
| 23 | tools=[lookup_order], |
| 24 | ) |
| 25 | |
| 26 | # Each turn sends only the new messages; the server holds the rest of the conversation. |
| 27 | first = thread.send({"role": "user", "content": "Hi! I have a question about an order."}) |
| 28 | rich.print(first.content) |
| 29 | |
| 30 | # `stream()` sends a turn the same way and streams the reply as it arrives. |
| 31 | with thread.stream( |
| 32 | {"role": "user", "content": "Before I find the order number: how long does standard shipping usually take?"} |
| 33 | ) as stream: |
| 34 | for text in stream.text_stream: |
| 35 | print(text, end="", flush=True) |
| 36 | print() |
| 37 | |
| 38 | # A turn that may call `lookup_order` goes through the tool runner, which continues the same thread and answers |
| 39 | # the tool calls. |
| 40 | thread.append({"role": "user", "content": "It's order #4821 and it hasn't arrived. Can you check where it is?"}) |
| 41 | final = thread.tool_runner().until_done() |
| 42 | rich.print(final.content) |
| 43 | |
| 44 | # The streaming runner yields one stream per turn and still answers any tool calls in between. |
| 45 | thread.append({"role": "user", "content": "Thanks. What should I do if it isn't here by then?"}) |
| 46 | for stream in thread.tool_runner(stream=True): |
| 47 | for text in stream.text_stream: |
| 48 | print(text, end="", flush=True) |
| 49 | print() |
| 50 | |
| 51 | # `fork()` copies the thread. The fork's first turn starts a new server-side thread from the same history, and the |
| 52 | # two continue independently from then on. |
| 53 | cancellation = thread.fork() |
| 54 | cancellation.append({"role": "user", "content": "Actually, I'd rather cancel the order and get a refund."}) |
| 55 | rich.print(cancellation.tool_runner().until_done().content) |
| 56 | rich.print(thread.send({"role": "user", "content": "Great, I'll wait for it. Thanks!"}).content) |
| 57 | |
| 58 | # `model`, `system`, `tools`, ... are fixed for a thread's lifetime; start a new one from the history to change them. |
| 59 | escalation = client.beta.messages.thread( |
| 60 | model="claude-opus-5-5", |
| 61 | max_tokens=1024, |
| 62 | system="You are a support agent for Acme. Keep replies short.", |
| 63 | tools=[lookup_order], |
| 64 | messages=cancellation.messages, |
| 65 | ) |
| 66 | decision = escalation.send({"role": "user", "content": "Can you approve the refund?"}) |
| 67 | rich.print(decision.content) |
| 68 | |
| 69 | |
| 70 | main() |
no test coverage detected