anthropics / anthropics/courses
In [79] in anthropic_api_fundamentals/05_Streaming.ipynb error. Await must be inside async function.
- Dominant language
- Jupyter Notebook
- Stars
- 22.8k
- Forks
- 2.5k
- PR merge metrics
- No merged PRs in 30d
Description
Current code has await outside an async method. Python 3.13 doesn't allow that. Maybe a previous version did?
```py
from anthropic import AsyncAnthropic
client = AsyncAnthropic()
async def streaming_with_helpers():
async with client.messages.stream(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Write me sonnet about orchids",
}
],
model="claude-3-opus-20240229",
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
final_message = await stream.get_final_message()
print("\n\nSTREAMING IS DONE. HERE IS THE FINAL ACCUMULATED MESSAGE: ")
print(final_message.to_json())
await streaming_with_helpers()
```
Fix:
```py
import asyncio
from anthropic import AsyncAnthropic
client = AsyncAnthropic()
async def streaming_with_helpers():
async with client.messages.stream(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Write me sonnet about orchids",
}
],
model="claude-3-haiku-20240307",
) as stream: # stream : MessageStreamManager, a Context Manager
async for text in stream.text_stream:
print(text, end="", flush=True)
final_message = await stream.get_final_message()
print("\n\nSTREAMING IS DONE. HERE IS THE FINAL ACCUMULATED MESSAGE: ")
print(final_message.to_json())
async def main():
await streaming_with_helpers()
asyncio.run(main())
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.