ValueError
semantic_kernel.exceptions.ValueError
Stack trace
ValueError: Invalid chat history format: expected list of chat messages but got string
File "semantic_kernel/chat_history.py", line 78, in load_history
raise ValueError("Invalid chat history format: expected list of chat messages but got string")
File "semantic_kernel/chat_session.py", line 45, in get_chat_context
history = self.chat_history.load_history()
File "app.py", line 32, in main
context = chat_session.get_chat_context() Why it happens
Semantic Kernel expects chat history to be a list of message objects with specific keys like 'role' and 'content'. If the history is saved or loaded as a plain string or malformed JSON, the deserialization fails and raises this ValueError. This often happens when chat history is manually serialized or corrupted.
Detection
Add validation after loading chat history to assert it is a list of dicts with required keys before passing to Semantic Kernel methods, and log the raw history data if validation fails.
Causes & fixes
Chat history saved as a plain string instead of a list of message dicts
Ensure chat history is serialized as JSON array of message objects, not as a raw string or single JSON string.
Chat history file or storage corrupted or truncated, causing invalid JSON
Add error handling to detect corrupted files and fallback to empty history or reload from backup.
Incorrect deserialization method used, e.g., using str() instead of json.loads()
Use json.loads() to parse chat history from storage to get a proper list of dicts.
Code: broken vs fixed
import os
from semantic_kernel import Kernel
history = os.environ.get('CHAT_HISTORY')
# This will fail if history is a string, not a list
kernel = Kernel()
chat_session = kernel.create_chat_session(history)
context = chat_session.get_chat_context() # Raises ValueError here
print(context) import os
import json
from semantic_kernel import Kernel
history_str = os.environ.get('CHAT_HISTORY', '[]')
history = json.loads(history_str) # Fixed: deserialize JSON string to list
kernel = Kernel()
chat_session = kernel.create_chat_session(history)
context = chat_session.get_chat_context() # Works correctly
print(context) # Shows chat context Workaround
Wrap chat history loading in try/except ValueError, and if caught, reset history to an empty list or minimal valid structure to allow continuation.
Prevention
Always serialize chat history as JSON arrays of message objects and validate format on load; use Semantic Kernel's built-in save/load utilities to avoid manual errors.