Skip to content

In [79] in anthropic_api_fundamentals/05_Streaming.ipynb error. Await must be inside async function. #73

Open
@alothings

Description

@alothings

Current code has await outside an async method. Python 3.13 doesn't allow that. Maybe a previous version did?

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:

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())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions