I am getting an error adding message in the messag...
# ask-ai
a
I am getting an error adding message in the messages like chat history.. checkout my code below
Copy code
messages = session.history.to_dict() #.copy(exclude_instructions=True)
messages["items"] = [ d for d in messages.get("items", []) if d.get("type") == "message" ]
try:
                    for item in (d for d in messages.get("items", []) if d.get("type") == "message"):
                        content = item.get("content")
                        if isinstance(content, list):
                            # Convert list to a single string
                            item["content"] = "\n".join(
                                "[image]" if isinstance(x, dict) and x.get("type") == "image_url" else str(x)
                                for x in content
                                if x not in (None, "")
                            )
                except Exception as e:
                    <http://logger.info|logger.info>(f"Error in try of formatting messages :: {e}")

# ERROR IN BELOW LINE
messages['items'].append({role:"assistant", content: "How may I assist you?"})
and error is coming when I'm appending custom role assistant content in the messages items.. suggest me what am I doing wrong?
✅ 1
t
Thanks for reaching out, Hiren. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I see you're trying to append a new assistant message but hit an error on the append line. You're responding about the line where you do: messages['items'].append({role:"assistant", content: "How may I assist you?"}) What's wrong: • In Python, dictionary keys must be valid expressions.
role:
and
content:
as written look like JavaScript object syntax, not Python. That causes a SyntaxError or NameError because
role
and
content
are treated as variables, not string keys. How to fix: • Use string keys for the dict in Python: messages['items'].append({"role": "assistant", "content": "How may I assist you?"}) Other checks (if you still get errors): • Verify
messages
is a dict and
messages['items']
is a list before appending: if isinstance(messages, dict) and isinstance(messages.get('items'), list): messages['items'].append({"role": "assistant", "content": "How may I assist you?"}) else: logger.info("messages or messages['items'] has unexpected type") • Ensure
messages
and
messages['items']
are not immutable copies (e.g., a tuple) from
to_dict()
— your earlier comment suggests you copied; if you used
.copy()
from some pydantic model you might need to convert to a plain dict/list first. If you'd like, share the exact exception text you're seeing and the runtime types of
messages
and
messages['items']
(print(type(messages), type(messages['items']))) and I’ll help further. , with interactive elements
a
name 'role' is not defined << this is the error that I'm getting btw.. is it because of passing role: instead of "role":?
t
Thanks — yes, the error "name 'role' is not defined" is caused by using unquoted keys (JavaScript-style) instead of string keys in Python. Fix: use quoted string keys and ensure
messages['items']
is a list. For example:
Copy code
messages['items'].append({"role": "assistant", "content": "How may I assist you?"})
Quick checks if you still see errors: • Confirm types:
print(type(messages), type(messages.get('items')))
• If
messages['items']
is None or not a list, initialize it first:
Copy code
messages.setdefault('items', [])
• If
messages
is an immutable object (from a model), convert to a plain dict/list before mutating. If you paste the exact traceback or the types printed, I’ll help you further. , with interactive elements