Attach custom metadata to a message using the additional_kwargs or response_metadata fields, or use the id field for a unique identifier. For arbitrary metadata, you can subclass BaseMessage and add custom fields, but ensure they are serializable and excluded when converting to provider formats.
LangChain's BaseMessage objects have built-in fields for metadata that are ignored by LLM APIs: additional_kwargs (for provider-specific data) and response_metadata (for response metadata). You can safely store custom key-value pairs there. For example, message.additional_kwargs["user_id"] = "123". These fields are not sent to the LLM when the message is serialized to provider format (OpenAI, Anthropic). If you need to attach more complex metadata, you can subclass BaseMessage and override the to_json and from_json methods to ensure compatibility. The simplest approach is to store metadata separately in your state (e.g., a separate dictionary keyed by message ID) to keep messages clean.