Back to Repositories

Testing Chat Completion API Implementation in gpt4free

This test suite validates the chat completion functionality in the gpt4free library, testing both synchronous and asynchronous API implementations for generating responses. It demonstrates core message handling and streaming capabilities.

Test Coverage Overview

The test coverage focuses on two primary chat completion paths – synchronous streaming and asynchronous response generation.

  • Tests streaming response handling with poetry generation prompt
  • Validates asynchronous chat completion with basic greeting
  • Covers model selection and message formatting
  • Includes provider configuration options (commented examples)

Implementation Analysis

The testing approach employs both synchronous and asynchronous Python patterns to validate the g4f.ChatCompletion interface. It leverages Python’s asyncio framework for async testing, while using standard print statements for streaming output verification.

The implementation demonstrates proper async/await syntax and stream handling with flush controls for real-time output.

Technical Details

  • Uses Python’s built-in asyncio library
  • Implements sys.path manipulation for import resolution
  • Utilizes pathlib for cross-platform path handling
  • Tests against g4f.models.default configuration
  • Includes stream=True parameter testing

Best Practices Demonstrated

The test suite showcases several testing best practices including proper separation of synchronous and asynchronous test cases.

  • Clear test case isolation
  • Proper exception handling structure
  • Flexible provider configuration
  • Maintainable message formatting
  • Effective use of Python’s async features

xtekky/gpt4free

etc/testing/test_chat_completion.py

            
import sys
from pathlib import Path

sys.path.append(str(Path(__file__).parent.parent.parent))

import g4f, asyncio

print("create:", end=" ", flush=True)
for response in g4f.ChatCompletion.create(
    model=g4f.models.default,
    #provider=g4f.Provider.Bing,
    messages=[{"role": "user", "content": "write a poem about a tree"}],
    stream=True
):
    print(response, end="", flush=True)
print()

async def run_async():
    response = await g4f.ChatCompletion.create_async(
        model=g4f.models.default,
        #provider=g4f.Provider.Bing,
        messages=[{"role": "user", "content": "hello!"}],
    )
    print("create_async:", response)

asyncio.run(run_async())