Back to Repositories

Testing SimpleChatEngine Message Processing in llama_index

This test suite validates the SimpleChatEngine functionality in llama_index, focusing on basic chat interactions and message history management. It ensures proper handling of chat messages, response formatting, and state management across conversations.

Test Coverage Overview

The test suite covers core functionality of SimpleChatEngine including:
  • Basic chat message handling and responses
  • Chat history management and persistence
  • Engine reset functionality
  • Initialization with predefined chat history
Edge cases include message formatting validation and chat state reset verification.

Implementation Analysis

The testing approach employs direct instantiation and interaction with SimpleChatEngine to verify chat functionality. Tests utilize Python’s native assertion patterns to validate response formats and message history management, with particular attention to string formatting and message sequencing.

Technical Details

Testing components include:
  • Python’s built-in assertion framework
  • ChatMessage and MessageRole types from llama_index.core
  • SimpleChatEngine class with default configuration
  • String comparison for response validation

Best Practices Demonstrated

The test suite demonstrates several testing best practices:
  • Isolated test cases with clear purpose
  • State reset between tests
  • Explicit assertion messages
  • Comprehensive validation of output formats
  • Clean setup and teardown patterns

run-llama/llama_index

llama-index-core/tests/chat_engine/test_simple.py

            
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.chat_engine.simple import SimpleChatEngine


def test_simple_chat_engine() -> None:
    engine = SimpleChatEngine.from_defaults()

    engine.reset()
    response = engine.chat("Test message 1")
    assert str(response) == "user: Test message 1
assistant: "

    response = engine.chat("Test message 2")
    assert (
        str(response)
        == "user: Test message 1
assistant: user: Test message 1
assistant: 
"
        "user: Test message 2
assistant: "
    )

    engine.reset()
    response = engine.chat("Test message 3")
    assert str(response) == "user: Test message 3
assistant: "


def test_simple_chat_engine_with_init_history() -> None:
    engine = SimpleChatEngine.from_defaults(
        chat_history=[
            ChatMessage(role=MessageRole.USER, content="test human message"),
            ChatMessage(role=MessageRole.ASSISTANT, content="test ai message"),
        ],
    )

    response = engine.chat("new human message")
    assert (
        str(response) == "user: test human message
assistant: test ai message
"
        "user: new human message
assistant: "
    )