messages_stream.py 720 B

1234567891011121314151617181920212223242526
  1. import asyncio
  2. from g4f.client import AsyncClient
  3. async def main():
  4. client = AsyncClient()
  5. stream = client.chat.completions.create(
  6. model="gpt-4",
  7. messages=[{"role": "user", "content": "Say hello there!"}],
  8. stream=True,
  9. )
  10. accumulated_text = ""
  11. try:
  12. async for chunk in stream:
  13. if chunk.choices and chunk.choices[0].delta.content:
  14. content = chunk.choices[0].delta.content
  15. accumulated_text += content
  16. print(content, end="", flush=True)
  17. except Exception as e:
  18. print(f"\nError occurred: {e}")
  19. finally:
  20. print("\n\nFinal accumulated text:", accumulated_text)
  21. asyncio.run(main())