"""Module contains utility functions for working with messages.Some examples of what you can do with these functions include:* Convert messages to strings (serialization)* Convert messages from dicts to Message objects (deserialization)* Filter messages from a list of messages based on name, type or id etc."""from__future__importannotationsimportbase64importinspectimportjsonimportmathfromcollections.abcimportIterable,Sequencefromfunctoolsimportpartialfromtypingimport(TYPE_CHECKING,Annotated,Any,Callable,Literal,Optional,Union,cast,overload,)frompydanticimportDiscriminator,Field,Tagfromlangchain_core.exceptionsimportErrorCode,create_messagefromlangchain_core.messages.aiimportAIMessage,AIMessageChunkfromlangchain_core.messages.baseimportBaseMessage,BaseMessageChunkfromlangchain_core.messages.chatimportChatMessage,ChatMessageChunkfromlangchain_core.messages.functionimportFunctionMessage,FunctionMessageChunkfromlangchain_core.messages.humanimportHumanMessage,HumanMessageChunkfromlangchain_core.messages.modifierimportRemoveMessagefromlangchain_core.messages.systemimportSystemMessage,SystemMessageChunkfromlangchain_core.messages.toolimportToolCall,ToolMessage,ToolMessageChunkifTYPE_CHECKING:fromlangchain_text_splittersimportTextSplitterfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.prompt_valuesimportPromptValuefromlangchain_core.runnables.baseimportRunnabledef_get_type(v:Any)->str:"""Get the type associated with the object for serialization purposes."""ifisinstance(v,dict)and"type"inv:returnv["type"]elifhasattr(v,"type"):returnv.typeelse:msg=(f"Expected either a dictionary with a 'type' key or an object "f"with a 'type' attribute. Instead got type {type(v)}.")raiseTypeError(msg)AnyMessage=Annotated[Union[Annotated[AIMessage,Tag(tag="ai")],Annotated[HumanMessage,Tag(tag="human")],Annotated[ChatMessage,Tag(tag="chat")],Annotated[SystemMessage,Tag(tag="system")],Annotated[FunctionMessage,Tag(tag="function")],Annotated[ToolMessage,Tag(tag="tool")],Annotated[AIMessageChunk,Tag(tag="AIMessageChunk")],Annotated[HumanMessageChunk,Tag(tag="HumanMessageChunk")],Annotated[ChatMessageChunk,Tag(tag="ChatMessageChunk")],Annotated[SystemMessageChunk,Tag(tag="SystemMessageChunk")],Annotated[FunctionMessageChunk,Tag(tag="FunctionMessageChunk")],Annotated[ToolMessageChunk,Tag(tag="ToolMessageChunk")],],Field(discriminator=Discriminator(_get_type)),]
[docs]defget_buffer_string(messages:Sequence[BaseMessage],human_prefix:str="Human",ai_prefix:str="AI")->str:"""Convert a sequence of Messages to strings and concatenate them into one string. Args: messages: Messages to be converted to strings. human_prefix: The prefix to prepend to contents of HumanMessages. Default is "Human". ai_prefix: THe prefix to prepend to contents of AIMessages. Default is "AI". Returns: A single string concatenation of all input messages. Raises: ValueError: If an unsupported message type is encountered. Example: .. code-block:: python from langchain_core import AIMessage, HumanMessage messages = [ HumanMessage(content="Hi, how are you?"), AIMessage(content="Good, how are you?"), ] get_buffer_string(messages) # -> "Human: Hi, how are you?\nAI: Good, how are you?" """string_messages=[]forminmessages:ifisinstance(m,HumanMessage):role=human_prefixelifisinstance(m,AIMessage):role=ai_prefixelifisinstance(m,SystemMessage):role="System"elifisinstance(m,FunctionMessage):role="Function"elifisinstance(m,ToolMessage):role="Tool"elifisinstance(m,ChatMessage):role=m.roleelse:msg=f"Got unsupported message type: {m}"raiseValueError(msg)# noqa: TRY004message=f"{role}: {m.content}"ifisinstance(m,AIMessage)and"function_call"inm.additional_kwargs:message+=f"{m.additional_kwargs['function_call']}"string_messages.append(message)return"\n".join(string_messages)
[docs]defmessages_from_dict(messages:Sequence[dict])->list[BaseMessage]:"""Convert a sequence of messages from dicts to Message objects. Args: messages: Sequence of messages (as dicts) to convert. Returns: list of messages (BaseMessages). """return[_message_from_dict(m)forminmessages]
[docs]defmessage_chunk_to_message(chunk:BaseMessageChunk)->BaseMessage:"""Convert a message chunk to a message. Args: chunk: Message chunk to convert. Returns: Message. """ifnotisinstance(chunk,BaseMessageChunk):returnchunk# chunk classes always have the equivalent non-chunk class as their first parentignore_keys=["type"]ifisinstance(chunk,AIMessageChunk):ignore_keys.append("tool_call_chunks")returnchunk.__class__.__mro__[1](**{k:vfork,vinchunk.__dict__.items()ifknotinignore_keys})
MessageLikeRepresentation=Union[BaseMessage,list[str],tuple[str,str],str,dict[str,Any]]def_create_message_from_message_type(message_type:str,content:str,name:Optional[str]=None,tool_call_id:Optional[str]=None,tool_calls:Optional[list[dict[str,Any]]]=None,id:Optional[str]=None,**additional_kwargs:Any,)->BaseMessage:"""Create a message from a message type and content string. Args: message_type: (str) the type of the message (e.g., "human", "ai", etc.). content: (str) the content string. name: (str) the name of the message. Default is None. tool_call_id: (str) the tool call id. Default is None. tool_calls: (list[dict[str, Any]]) the tool calls. Default is None. id: (str) the id of the message. Default is None. additional_kwargs: (dict[str, Any]) additional keyword arguments. Returns: a message of the appropriate type. Raises: ValueError: if the message type is not one of "human", "user", "ai", "assistant", "function", "tool", "system", or "developer". """kwargs:dict[str,Any]={}ifnameisnotNone:kwargs["name"]=nameiftool_call_idisnotNone:kwargs["tool_call_id"]=tool_call_idifadditional_kwargs:ifresponse_metadata:=additional_kwargs.pop("response_metadata",None):kwargs["response_metadata"]=response_metadatakwargs["additional_kwargs"]=additional_kwargs# type: ignore[assignment]additional_kwargs.update(additional_kwargs.pop("additional_kwargs",{}))ifidisnotNone:kwargs["id"]=idiftool_callsisnotNone:kwargs["tool_calls"]=[]fortool_callintool_calls:# Convert OpenAI-format tool call to LangChain format.if"function"intool_call:args=tool_call["function"]["arguments"]ifisinstance(args,str):args=json.loads(args,strict=False)kwargs["tool_calls"].append({"name":tool_call["function"]["name"],"args":args,"id":tool_call["id"],"type":"tool_call",})else:kwargs["tool_calls"].append(tool_call)ifmessage_typein("human","user"):ifexample:=kwargs.get("additional_kwargs",{}).pop("example",False):kwargs["example"]=examplemessage:BaseMessage=HumanMessage(content=content,**kwargs)elifmessage_typein("ai","assistant"):ifexample:=kwargs.get("additional_kwargs",{}).pop("example",False):kwargs["example"]=examplemessage=AIMessage(content=content,**kwargs)elifmessage_typein("system","developer"):ifmessage_type=="developer":kwargs["additional_kwargs"]=kwargs.get("additional_kwargs")or{}kwargs["additional_kwargs"]["__openai_role__"]="developer"message=SystemMessage(content=content,**kwargs)elifmessage_type=="function":message=FunctionMessage(content=content,**kwargs)elifmessage_type=="tool":artifact=kwargs.get("additional_kwargs",{}).pop("artifact",None)message=ToolMessage(content=content,artifact=artifact,**kwargs)elifmessage_type=="remove":message=RemoveMessage(**kwargs)else:msg=(f"Unexpected message type: '{message_type}'. Use one of 'human',"f" 'user', 'ai', 'assistant', 'function', 'tool', 'system', or 'developer'.")msg=create_message(message=msg,error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raiseValueError(msg)returnmessagedef_convert_to_message(message:MessageLikeRepresentation)->BaseMessage:"""Instantiate a message from a variety of message formats. The message format can be one of the following: - BaseMessagePromptTemplate - BaseMessage - 2-tuple of (role string, template); e.g., ("human", "{user_input}") - dict: a message dict with role and content keys - string: shorthand for ("human", template); e.g., "{user_input}" Args: message: a representation of a message in one of the supported formats. Returns: an instance of a message or a message template. Raises: NotImplementedError: if the message type is not supported. ValueError: if the message dict does not contain the required keys. """ifisinstance(message,BaseMessage):_message=messageelifisinstance(message,str):_message=_create_message_from_message_type("human",message)elifisinstance(message,Sequence)andlen(message)==2:# mypy doesn't realise this can't be a string given the previous branchmessage_type_str,template=message# type: ignore[misc]_message=_create_message_from_message_type(message_type_str,template)elifisinstance(message,dict):msg_kwargs=message.copy()try:try:msg_type=msg_kwargs.pop("role")exceptKeyError:msg_type=msg_kwargs.pop("type")# None msg content is not allowedmsg_content=msg_kwargs.pop("content")or""exceptKeyErrorase:msg=f"Message dict must contain 'role' and 'content' keys, got {message}"msg=create_message(message=msg,error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raiseValueError(msg)frome_message=_create_message_from_message_type(msg_type,msg_content,**msg_kwargs)else:msg=f"Unsupported message type: {type(message)}"msg=create_message(message=msg,error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raiseNotImplementedError(msg)return_message
[docs]defconvert_to_messages(messages:Union[Iterable[MessageLikeRepresentation],PromptValue],)->list[BaseMessage]:"""Convert a sequence of messages to a list of messages. Args: messages: Sequence of messages to convert. Returns: list of messages (BaseMessages). """# Import here to avoid circular importsfromlangchain_core.prompt_valuesimportPromptValueifisinstance(messages,PromptValue):returnmessages.to_messages()return[_convert_to_message(m)forminmessages]
[docs]@_runnable_supportdeffilter_messages(messages:Union[Iterable[MessageLikeRepresentation],PromptValue],*,include_names:Optional[Sequence[str]]=None,exclude_names:Optional[Sequence[str]]=None,include_types:Optional[Sequence[Union[str,type[BaseMessage]]]]=None,exclude_types:Optional[Sequence[Union[str,type[BaseMessage]]]]=None,include_ids:Optional[Sequence[str]]=None,exclude_ids:Optional[Sequence[str]]=None,exclude_tool_calls:Optional[Sequence[str]|bool]=None,)->list[BaseMessage]:"""Filter messages based on name, type or id. Args: messages: Sequence Message-like objects to filter. include_names: Message names to include. Default is None. exclude_names: Messages names to exclude. Default is None. include_types: Message types to include. Can be specified as string names (e.g. "system", "human", "ai", ...) or as BaseMessage classes (e.g. SystemMessage, HumanMessage, AIMessage, ...). Default is None. exclude_types: Message types to exclude. Can be specified as string names (e.g. "system", "human", "ai", ...) or as BaseMessage classes (e.g. SystemMessage, HumanMessage, AIMessage, ...). Default is None. include_ids: Message IDs to include. Default is None. exclude_ids: Message IDs to exclude. Default is None. exclude_tool_calls: Tool call IDs to exclude. Default is None. Can be one of the following: - `True`: all AIMessages with tool calls and all ToolMessages will be excluded. - a sequence of tool call IDs to exclude: - ToolMessages with the corresponding tool call ID will be excluded. - The `tool_calls` in the AIMessage will be updated to exclude matching tool calls. If all tool_calls are filtered from an AIMessage, the whole message is excluded. Returns: A list of Messages that meets at least one of the incl_* conditions and none of the excl_* conditions. If not incl_* conditions are specified then anything that is not explicitly excluded will be included. Raises: ValueError if two incompatible arguments are provided. Example: .. code-block:: python from langchain_core.messages import filter_messages, AIMessage, HumanMessage, SystemMessage messages = [ SystemMessage("you're a good assistant."), HumanMessage("what's your name", id="foo", name="example_user"), AIMessage("steve-o", id="bar", name="example_assistant"), HumanMessage("what's your favorite color", id="baz",), AIMessage("silicon blue", id="blah",), ] filter_messages( messages, incl_names=("example_user", "example_assistant"), incl_types=("system",), excl_ids=("bar",), ) .. code-block:: python [ SystemMessage("you're a good assistant."), HumanMessage("what's your name", id="foo", name="example_user"), ] """# noqa: E501messages=convert_to_messages(messages)filtered:list[BaseMessage]=[]formsginmessages:if((exclude_namesandmsg.nameinexclude_names)or(exclude_typesand_is_message_type(msg,exclude_types))or(exclude_idsandmsg.idinexclude_ids)):continueelse:passifexclude_tool_callsisTrueand((isinstance(msg,AIMessage)andmsg.tool_calls)orisinstance(msg,ToolMessage)):continueifisinstance(exclude_tool_calls,(list,tuple,set)):ifisinstance(msg,AIMessage)andmsg.tool_calls:tool_calls=[tool_callfortool_callinmsg.tool_callsiftool_call["id"]notinexclude_tool_calls]ifnottool_calls:continuecontent=msg.content# handle Anthropic content blocksifisinstance(msg.content,list):content=[content_blockforcontent_blockinmsg.contentif(notisinstance(content_block,dict)orcontent_block.get("type")!="tool_use"orcontent_block.get("id")notinexclude_tool_calls)]msg=msg.model_copy(# noqa: PLW2901update={"tool_calls":tool_calls,"content":content})elif(isinstance(msg,ToolMessage)andmsg.tool_call_idinexclude_tool_calls):continue# default to inclusion when no inclusion criteria given.if(not(include_typesorinclude_idsorinclude_names)or(include_namesandmsg.nameininclude_names)or(include_typesand_is_message_type(msg,include_types))or(include_idsandmsg.idininclude_ids)):filtered.append(msg)else:passreturnfiltered
[docs]@_runnable_supportdefmerge_message_runs(messages:Union[Iterable[MessageLikeRepresentation],PromptValue],*,chunk_separator:str="\n",)->list[BaseMessage]:"""Merge consecutive Messages of the same type. **NOTE**: ToolMessages are not merged, as each has a distinct tool call id that can't be merged. Args: messages: Sequence Message-like objects to merge. chunk_separator: Specify the string to be inserted between message chunks. Default is "\n". Returns: list of BaseMessages with consecutive runs of message types merged into single messages. By default, if two messages being merged both have string contents, the merged content is a concatenation of the two strings with a new-line separator. The separator inserted between message chunks can be controlled by specifying any string with ``chunk_separator``. If at least one of the messages has a list of content blocks, the merged content is a list of content blocks. Example: .. code-block:: python from langchain_core.messages import ( merge_message_runs, AIMessage, HumanMessage, SystemMessage, ToolCall, ) messages = [ SystemMessage("you're a good assistant."), HumanMessage("what's your favorite color", id="foo",), HumanMessage("wait your favorite food", id="bar",), AIMessage( "my favorite colo", tool_calls=[ToolCall(name="blah_tool", args={"x": 2}, id="123", type="tool_call")], id="baz", ), AIMessage( [{"type": "text", "text": "my favorite dish is lasagna"}], tool_calls=[ToolCall(name="blah_tool", args={"x": -10}, id="456", type="tool_call")], id="blur", ), ] merge_message_runs(messages) .. code-block:: python [ SystemMessage("you're a good assistant."), HumanMessage("what's your favorite color\\nwait your favorite food", id="foo",), AIMessage( [ "my favorite colo", {"type": "text", "text": "my favorite dish is lasagna"} ], tool_calls=[ ToolCall({"name": "blah_tool", "args": {"x": 2}, "id": "123", "type": "tool_call"}), ToolCall({"name": "blah_tool", "args": {"x": -10}, "id": "456", "type": "tool_call"}) ] id="baz" ), ] """# noqa: E501ifnotmessages:return[]messages=convert_to_messages(messages)merged:list[BaseMessage]=[]formsginmessages:last=merged.pop()ifmergedelseNoneifnotlast:merged.append(msg)elifisinstance(msg,ToolMessage)ornotisinstance(msg,last.__class__):merged.extend([last,msg])else:last_chunk=_msg_to_chunk(last)curr_chunk=_msg_to_chunk(msg)ifcurr_chunk.response_metadata:curr_chunk.response_metadata.clear()if(isinstance(last_chunk.content,str)andisinstance(curr_chunk.content,str)andlast_chunk.contentandcurr_chunk.content):last_chunk.content+=chunk_separatormerged.append(_chunk_to_msg(last_chunk+curr_chunk))returnmerged
# TODO: Update so validation errors (for token_counter, for example) are raised on# init not at runtime.
[docs]@_runnable_supportdeftrim_messages(messages:Union[Iterable[MessageLikeRepresentation],PromptValue],*,max_tokens:int,token_counter:Union[Callable[[list[BaseMessage]],int],Callable[[BaseMessage],int],BaseLanguageModel,],strategy:Literal["first","last"]="last",allow_partial:bool=False,end_on:Optional[Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]]]=None,start_on:Optional[Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]]]=None,include_system:bool=False,text_splitter:Optional[Union[Callable[[str],list[str]],TextSplitter]]=None,)->list[BaseMessage]:r"""Trim messages to be below a token count. trim_messages can be used to reduce the size of a chat history to a specified token count or specified message count. In either case, if passing the trimmed chat history back into a chat model directly, the resulting chat history should usually satisfy the following properties: 1. The resulting chat history should be valid. Most chat models expect that chat history starts with either (1) a `HumanMessage` or (2) a `SystemMessage` followed by a `HumanMessage`. To achieve this, set `start_on="human"`. In addition, generally a `ToolMessage` can only appear after an `AIMessage` that involved a tool call. Please see the following link for more information about messages: https://python.langchain.com/docs/concepts/#messages 2. It includes recent messages and drops old messages in the chat history. To achieve this set the `strategy="last"`. 3. Usually, the new chat history should include the `SystemMessage` if it was present in the original chat history since the `SystemMessage` includes special instructions to the chat model. The `SystemMessage` is almost always the first message in the history if present. To achieve this set the `include_system=True`. **Note** The examples below show how to configure `trim_messages` to achieve a behavior consistent with the above properties. Args: messages: Sequence of Message-like objects to trim. max_tokens: Max token count of trimmed messages. token_counter: Function or llm for counting tokens in a BaseMessage or a list of BaseMessage. If a BaseLanguageModel is passed in then BaseLanguageModel.get_num_tokens_from_messages() will be used. Set to `len` to count the number of **messages** in the chat history. Note: Use `count_tokens_approximately` to get fast, approximate token counts. This is recommended for using `trim_messages` on the hot path, where exact token counting is not necessary. strategy: Strategy for trimming. - "first": Keep the first <= n_count tokens of the messages. - "last": Keep the last <= n_count tokens of the messages. Default is "last". allow_partial: Whether to split a message if only part of the message can be included. If ``strategy="last"`` then the last partial contents of a message are included. If ``strategy="first"`` then the first partial contents of a message are included. Default is False. end_on: The message type to end on. If specified then every message after the last occurrence of this type is ignored. If ``strategy=="last"`` then this is done before we attempt to get the last ``max_tokens``. If ``strategy=="first"`` then this is done after we get the first ``max_tokens``. Can be specified as string names (e.g. "system", "human", "ai", ...) or as BaseMessage classes (e.g. SystemMessage, HumanMessage, AIMessage, ...). Can be a single type or a list of types. Default is None. start_on: The message type to start on. Should only be specified if ``strategy="last"``. If specified then every message before the first occurrence of this type is ignored. This is done after we trim the initial messages to the last ``max_tokens``. Does not apply to a SystemMessage at index 0 if ``include_system=True``. Can be specified as string names (e.g. "system", "human", "ai", ...) or as BaseMessage classes (e.g. SystemMessage, HumanMessage, AIMessage, ...). Can be a single type or a list of types. Default is None. include_system: Whether to keep the SystemMessage if there is one at index 0. Should only be specified if ``strategy="last"``. Default is False. text_splitter: Function or ``langchain_text_splitters.TextSplitter`` for splitting the string contents of a message. Only used if ``allow_partial=True``. If ``strategy="last"`` then the last split tokens from a partial message will be included. if ``strategy=="first"`` then the first split tokens from a partial message will be included. Token splitter assumes that separators are kept, so that split contents can be directly concatenated to recreate the original text. Defaults to splitting on newlines. Returns: list of trimmed BaseMessages. Raises: ValueError: if two incompatible arguments are specified or an unrecognized ``strategy`` is specified. Example: Trim chat history based on token count, keeping the SystemMessage if present, and ensuring that the chat history starts with a HumanMessage ( or a SystemMessage followed by a HumanMessage). .. code-block:: python from typing import list from langchain_core.messages import ( AIMessage, HumanMessage, BaseMessage, SystemMessage, trim_messages, ) messages = [ SystemMessage("you're a good assistant, you always respond with a joke."), HumanMessage("i wonder why it's called langchain"), AIMessage( 'Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!' ), HumanMessage("and who is harrison chasing anyways"), AIMessage( "Hmmm let me think.\n\nWhy, he's probably chasing after the last cup of coffee in the office!" ), HumanMessage("what do you call a speechless parrot"), ] trim_messages( messages, max_tokens=45, strategy="last", token_counter=ChatOpenAI(model="gpt-4o"), # Most chat models expect that chat history starts with either: # (1) a HumanMessage or # (2) a SystemMessage followed by a HumanMessage start_on="human", # Usually, we want to keep the SystemMessage # if it's present in the original history. # The SystemMessage has special instructions for the model. include_system=True, allow_partial=False, ) .. code-block:: python [ SystemMessage(content="you're a good assistant, you always respond with a joke."), HumanMessage(content='what do you call a speechless parrot'), ] Trim chat history based on the message count, keeping the SystemMessage if present, and ensuring that the chat history starts with a HumanMessage ( or a SystemMessage followed by a HumanMessage). trim_messages( messages, # When `len` is passed in as the token counter function, # max_tokens will count the number of messages in the chat history. max_tokens=4, strategy="last", # Passing in `len` as a token counter function will # count the number of messages in the chat history. token_counter=len, # Most chat models expect that chat history starts with either: # (1) a HumanMessage or # (2) a SystemMessage followed by a HumanMessage start_on="human", # Usually, we want to keep the SystemMessage # if it's present in the original history. # The SystemMessage has special instructions for the model. include_system=True, allow_partial=False, ) .. code-block:: python [ SystemMessage(content="you're a good assistant, you always respond with a joke."), HumanMessage(content='and who is harrison chasing anyways'), AIMessage(content="Hmmm let me think.\n\nWhy, he's probably chasing after the last cup of coffee in the office!"), HumanMessage(content='what do you call a speechless parrot'), ] Trim chat history using a custom token counter function that counts the number of tokens in each message. .. code-block:: python messages = [ SystemMessage("This is a 4 token text. The full message is 10 tokens."), HumanMessage("This is a 4 token text. The full message is 10 tokens.", id="first"), AIMessage( [ {"type": "text", "text": "This is the FIRST 4 token block."}, {"type": "text", "text": "This is the SECOND 4 token block."}, ], id="second", ), HumanMessage("This is a 4 token text. The full message is 10 tokens.", id="third"), AIMessage("This is a 4 token text. The full message is 10 tokens.", id="fourth"), ] def dummy_token_counter(messages: list[BaseMessage]) -> int: # treat each message like it adds 3 default tokens at the beginning # of the message and at the end of the message. 3 + 4 + 3 = 10 tokens # per message. default_content_len = 4 default_msg_prefix_len = 3 default_msg_suffix_len = 3 count = 0 for msg in messages: if isinstance(msg.content, str): count += default_msg_prefix_len + default_content_len + default_msg_suffix_len if isinstance(msg.content, list): count += default_msg_prefix_len + len(msg.content) * default_content_len + default_msg_suffix_len return count First 30 tokens, allowing partial messages: .. code-block:: python trim_messages( messages, max_tokens=30, token_counter=dummy_token_counter, strategy="first", allow_partial=True, ) .. code-block:: python [ SystemMessage("This is a 4 token text. The full message is 10 tokens."), HumanMessage("This is a 4 token text. The full message is 10 tokens.", id="first"), AIMessage( [{"type": "text", "text": "This is the FIRST 4 token block."}], id="second"), ] """# noqa: E501# Validate argumentsifstart_onandstrategy=="first":msg="start_on parameter is only valid with strategy='last'"raiseValueError(msg)ifinclude_systemandstrategy=="first":msg="include_system parameter is only valid with strategy='last'"raiseValueError(msg)messages=convert_to_messages(messages)ifhasattr(token_counter,"get_num_tokens_from_messages"):list_token_counter=token_counter.get_num_tokens_from_messageselifcallable(token_counter):if(list(inspect.signature(token_counter).parameters.values())[0].annotationisBaseMessage):deflist_token_counter(messages:Sequence[BaseMessage])->int:returnsum(token_counter(msg)formsginmessages)# type: ignore[arg-type, misc]else:list_token_counter=token_counter# type: ignore[assignment]else:msg=(f"'token_counter' expected to be a model that implements "f"'get_num_tokens_from_messages()' or a function. Received object of type "f"{type(token_counter)}.")raiseValueError(msg)try:fromlangchain_text_splittersimportTextSplitterexceptImportError:text_splitter_fn:Optional[Callable]=cast("Optional[Callable]",text_splitter)else:ifisinstance(text_splitter,TextSplitter):text_splitter_fn=text_splitter.split_textelse:text_splitter_fn=text_splittertext_splitter_fn=text_splitter_fnor_default_text_splitterifstrategy=="first":return_first_max_tokens(messages,max_tokens=max_tokens,token_counter=list_token_counter,text_splitter=text_splitter_fn,partial_strategy="first"ifallow_partialelseNone,end_on=end_on,)elifstrategy=="last":return_last_max_tokens(messages,max_tokens=max_tokens,token_counter=list_token_counter,allow_partial=allow_partial,include_system=include_system,start_on=start_on,end_on=end_on,text_splitter=text_splitter_fn,)else:msg=f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'."raiseValueError(msg)
[docs]defconvert_to_openai_messages(messages:Union[MessageLikeRepresentation,Sequence[MessageLikeRepresentation]],*,text_format:Literal["string","block"]="string",)->Union[dict,list[dict]]:"""Convert LangChain messages into OpenAI message dicts. Args: messages: Message-like object or iterable of objects whose contents are in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats. text_format: How to format string or text block contents: - "string": If a message has a string content, this is left as a string. If a message has content blocks that are all of type 'text', these are joined with a newline to make a single string. If a message has content blocks and at least one isn't of type 'text', then all blocks are left as dicts. - "block": If a message has a string content, this is turned into a list with a single content block of type 'text'. If a message has content blocks these are left as is. Returns: The return type depends on the input type: - dict: If a single message-like object is passed in, a single OpenAI message dict is returned. - list[dict]: If a sequence of message-like objects are passed in, a list of OpenAI message dicts is returned. Example: .. code-block:: python from langchain_core.messages import ( convert_to_openai_messages, AIMessage, SystemMessage, ToolMessage, ) messages = [ SystemMessage([{"type": "text", "text": "foo"}]), {"role": "user", "content": [{"type": "text", "text": "whats in this"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,'/9j/4AAQSk'"}}]}, AIMessage("", tool_calls=[{"name": "analyze", "args": {"baz": "buz"}, "id": "1", "type": "tool_call"}]), ToolMessage("foobar", tool_call_id="1", name="bar"), {"role": "assistant", "content": "thats nice"}, ] oai_messages = convert_to_openai_messages(messages) # -> [ # {'role': 'system', 'content': 'foo'}, # {'role': 'user', 'content': [{'type': 'text', 'text': 'whats in this'}, {'type': 'image_url', 'image_url': {'url': "data:image/png;base64,'/9j/4AAQSk'"}}]}, # {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '1','function': {'name': 'analyze', 'arguments': '{"baz": "buz"}'}}], 'content': ''}, # {'role': 'tool', 'name': 'bar', 'content': 'foobar'}, # {'role': 'assistant', 'content': 'thats nice'} # ] .. versionadded:: 0.3.11 """# noqa: E501iftext_formatnotin("string","block"):err=f"Unrecognized {text_format=}, expected one of 'string' or 'block'."raiseValueError(err)oai_messages:list=[]ifis_single:=isinstance(messages,(BaseMessage,dict,str)):messages=[messages]messages=convert_to_messages(messages)fori,messageinenumerate(messages):oai_msg:dict={"role":_get_message_openai_role(message)}tool_messages:list=[]content:Union[str,list[dict]]ifmessage.name:oai_msg["name"]=message.nameifisinstance(message,AIMessage)andmessage.tool_calls:oai_msg["tool_calls"]=_convert_to_openai_tool_calls(message.tool_calls)ifmessage.additional_kwargs.get("refusal"):oai_msg["refusal"]=message.additional_kwargs["refusal"]ifisinstance(message,ToolMessage):oai_msg["tool_call_id"]=message.tool_call_idifnotmessage.content:content=""iftext_format=="string"else[]elifisinstance(message.content,str):iftext_format=="string":content=message.contentelse:content=[{"type":"text","text":message.content}]else:iftext_format=="string"andall(isinstance(block,str)orblock.get("type")=="text"forblockinmessage.content):content="\n".join(blockifisinstance(block,str)elseblock["text"]forblockinmessage.content)else:content=[]forj,blockinenumerate(message.content):# OpenAI formatifisinstance(block,str):content.append({"type":"text","text":block})elifblock.get("type")=="text":ifmissing:=[kforkin("text",)ifknotinblock]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': 'text' "f"but is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(err)content.append({"type":block["type"],"text":block["text"]})elifblock.get("type")=="image_url":ifmissing:=[kforkin("image_url",)ifknotinblock]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': 'image_url' "f"but is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(err)content.append({"type":"image_url","image_url":block["image_url"],})# Anthropic and Bedrock converse formatelif(block.get("type")=="image")or"image"inblock:# Anthropicifsource:=block.get("source"):ifmissing:=[kforkin("media_type","type","data")ifknotinsource]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': 'image' "f"but 'source' is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(err)content.append({"type":"image_url","image_url":{"url":(f"data:{source['media_type']};"f"{source['type']},{source['data']}")},})# Bedrock converseelifimage:=block.get("image"):ifmissing:=[kforkin("source","format")ifknotinimage]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has key 'image', "f"but 'image' is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(err)b64_image=_bytes_to_b64_str(image["source"]["bytes"])content.append({"type":"image_url","image_url":{"url":(f"data:image/{image['format']};"f"base64,{b64_image}")},})else:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': 'image' "f"but does not have a 'source' or 'image' key. Full "f"content block:\n\n{block}")raiseValueError(err)elifblock.get("type")=="tool_use":ifmissing:=[kforkin("id","name","input")ifknotinblock]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': "f"'tool_use', but is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(err)ifnotany(tool_call["id"]==block["id"]fortool_callincast("AIMessage",message).tool_calls):oai_msg["tool_calls"]=oai_msg.get("tool_calls",[])oai_msg["tool_calls"].append({"type":"function","id":block["id"],"function":{"name":block["name"],"arguments":json.dumps(block["input"]),},})elifblock.get("type")=="tool_result":ifmissing:=[kforkin("content","tool_use_id")ifknotinblock]:msg=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': "f"'tool_result', but is missing expected key(s) "f"{missing}. Full content block:\n\n{block}")raiseValueError(msg)tool_message=ToolMessage(block["content"],tool_call_id=block["tool_use_id"],status="error"ifblock.get("is_error")else"success",)# Recurse to make sure tool message contents are OpenAI format.tool_messages.extend(convert_to_openai_messages([tool_message],text_format=text_format))elif(block.get("type")=="json")or"json"inblock:if"json"notinblock:msg=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': 'json' "f"but does not have a 'json' key. Full "f"content block:\n\n{block}")raiseValueError(msg)content.append({"type":"text","text":json.dumps(block["json"]),})elif(block.get("type")=="guard_content")or"guard_content"inblock:if("guard_content"notinblockor"text"notinblock["guard_content"]):msg=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': "f"'guard_content' but does not have a "f"messages[{i}].content[{j}]['guard_content']['text'] "f"key. Full content block:\n\n{block}")raiseValueError(msg)text=block["guard_content"]["text"]ifisinstance(text,dict):text=text["text"]content.append({"type":"text","text":text})# VertexAI formatelifblock.get("type")=="media":ifmissing:=[kforkin("mime_type","data")ifknotinblock]:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] has 'type': "f"'media' but does not have key(s) {missing}. Full "f"content block:\n\n{block}")raiseValueError(err)if"image"notinblock["mime_type"]:err=(f"OpenAI messages can only support text and image data."f" Received content block with media of type:"f" {block['mime_type']}")raiseValueError(err)b64_image=_bytes_to_b64_str(block["data"])content.append({"type":"image_url","image_url":{"url":(f"data:{block['mime_type']};base64,{b64_image}")},})elifblock.get("type")=="thinking":content.append(block)else:err=(f"Unrecognized content block at "f"messages[{i}].content[{j}] does not match OpenAI, "f"Anthropic, Bedrock Converse, or VertexAI format. Full "f"content block:\n\n{block}")raiseValueError(err)iftext_format=="string"andnotany(block["type"]!="text"forblockincontent):content="\n".join(block["text"]forblockincontent)oai_msg["content"]=contentifmessage.contentandnotoai_msg["content"]andtool_messages:oai_messages.extend(tool_messages)else:oai_messages.extend([oai_msg,*tool_messages])ifis_single:returnoai_messages[0]else:returnoai_messages
def_first_max_tokens(messages:Sequence[BaseMessage],*,max_tokens:int,token_counter:Callable[[list[BaseMessage]],int],text_splitter:Callable[[str],list[str]],partial_strategy:Optional[Literal["first","last"]]=None,end_on:Optional[Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]]]=None,)->list[BaseMessage]:messages=list(messages)ifnotmessages:returnmessages# Check if all messages already fit within token limitiftoken_counter(messages)<=max_tokens:# When all messages fit, only apply end_on filtering if neededifend_on:for_inrange(len(messages)):ifnot_is_message_type(messages[-1],end_on):messages.pop()else:breakreturnmessages# Use binary search to find the maximum number of messages within token limitleft,right=0,len(messages)max_iterations=len(messages).bit_length()for_inrange(max_iterations):ifleft>=right:breakmid=(left+right+1)//2iftoken_counter(messages[:mid])<=max_tokens:left=mididx=midelse:right=mid-1# idx now contains the maximum number of complete messages we can includeidx=leftifpartial_strategyandidx<len(messages):included_partial=Falsecopied=Falseifisinstance(messages[idx].content,list):excluded=messages[idx].model_copy(deep=True)copied=Truenum_block=len(excluded.content)ifpartial_strategy=="last":excluded.content=list(reversed(excluded.content))for_inrange(1,num_block):excluded.content=excluded.content[:-1]iftoken_counter(messages[:idx]+[excluded])<=max_tokens:messages=messages[:idx]+[excluded]idx+=1included_partial=Truebreakifincluded_partialandpartial_strategy=="last":excluded.content=list(reversed(excluded.content))ifnotincluded_partial:ifnotcopied:excluded=messages[idx].model_copy(deep=True)copied=True# Extract text content efficientlytext=Noneifisinstance(excluded.content,str):text=excluded.contentelifisinstance(excluded.content,list)andexcluded.content:forblockinexcluded.content:ifisinstance(block,str):text=blockbreakelifisinstance(block,dict)andblock.get("type")=="text":text=block.get("text")breakiftext:ifnotcopied:excluded=excluded.model_copy(deep=True)split_texts=text_splitter(text)base_message_count=token_counter(messages[:idx])ifpartial_strategy=="last":split_texts=list(reversed(split_texts))# Binary search for the maximum number of splits we can includeleft,right=0,len(split_texts)max_iterations=len(split_texts).bit_length()for_inrange(max_iterations):ifleft>=right:breakmid=(left+right+1)//2excluded.content="".join(split_texts[:mid])ifbase_message_count+token_counter([excluded])<=max_tokens:left=midelse:right=mid-1ifleft>0:content_splits=split_texts[:left]ifpartial_strategy=="last":content_splits=list(reversed(content_splits))excluded.content="".join(content_splits)messages=messages[:idx]+[excluded]idx+=1ifend_on:for_inrange(idx):ifidx>0andnot_is_message_type(messages[idx-1],end_on):idx-=1else:breakreturnmessages[:idx]def_last_max_tokens(messages:Sequence[BaseMessage],*,max_tokens:int,token_counter:Callable[[list[BaseMessage]],int],text_splitter:Callable[[str],list[str]],allow_partial:bool=False,include_system:bool=False,start_on:Optional[Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]]]=None,end_on:Optional[Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]]]=None,)->list[BaseMessage]:messages=list(messages)iflen(messages)==0:return[]# Filter out messages after end_on typeifend_on:for_inrange(len(messages)):ifnot_is_message_type(messages[-1],end_on):messages.pop()else:break# Handle system message preservationsystem_message=Noneifinclude_systemandlen(messages)>0andisinstance(messages[0],SystemMessage):system_message=messages[0]messages=messages[1:]# Reverse messages to use _first_max_tokens with reversed logicreversed_messages=messages[::-1]# Calculate remaining tokens after accounting for system message if presentremaining_tokens=max_tokensifsystem_message:system_tokens=token_counter([system_message])remaining_tokens=max(0,max_tokens-system_tokens)reversed_result=_first_max_tokens(reversed_messages,max_tokens=remaining_tokens,token_counter=token_counter,text_splitter=text_splitter,partial_strategy="last"ifallow_partialelseNone,end_on=start_on,)# Re-reverse the messages and add back the system message if neededresult=reversed_result[::-1]ifsystem_message:result=[system_message]+resultreturnresult_MSG_CHUNK_MAP:dict[type[BaseMessage],type[BaseMessageChunk]]={HumanMessage:HumanMessageChunk,AIMessage:AIMessageChunk,SystemMessage:SystemMessageChunk,ToolMessage:ToolMessageChunk,FunctionMessage:FunctionMessageChunk,ChatMessage:ChatMessageChunk,}_CHUNK_MSG_MAP={v:kfork,vin_MSG_CHUNK_MAP.items()}def_msg_to_chunk(message:BaseMessage)->BaseMessageChunk:ifmessage.__class__in_MSG_CHUNK_MAP:return_MSG_CHUNK_MAP[message.__class__](**message.model_dump(exclude={"type"}))formsg_cls,chunk_clsin_MSG_CHUNK_MAP.items():ifisinstance(message,msg_cls):returnchunk_cls(**message.model_dump(exclude={"type"}))msg=(f"Unrecognized message class {message.__class__}. Supported classes are "f"{list(_MSG_CHUNK_MAP.keys())}")msg=create_message(message=msg,error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raiseValueError(msg)def_chunk_to_msg(chunk:BaseMessageChunk)->BaseMessage:ifchunk.__class__in_CHUNK_MSG_MAP:return_CHUNK_MSG_MAP[chunk.__class__](**chunk.model_dump(exclude={"type","tool_call_chunks"}))forchunk_cls,msg_clsin_CHUNK_MSG_MAP.items():ifisinstance(chunk,chunk_cls):returnmsg_cls(**chunk.model_dump(exclude={"type","tool_call_chunks"}))msg=(f"Unrecognized message chunk class {chunk.__class__}. Supported classes are "f"{list(_CHUNK_MSG_MAP.keys())}")msg=create_message(message=msg,error_code=ErrorCode.MESSAGE_COERCION_FAILURE)raiseValueError(msg)def_default_text_splitter(text:str)->list[str]:splits=text.split("\n")return[s+"\n"forsinsplits[:-1]]+splits[-1:]def_is_message_type(message:BaseMessage,type_:Union[str,type[BaseMessage],Sequence[Union[str,type[BaseMessage]]]],)->bool:types=[type_]ifisinstance(type_,(str,type))elsetype_types_str=[tfortintypesifisinstance(t,str)]types_types=tuple(tfortintypesifisinstance(t,type))returnmessage.typeintypes_strorisinstance(message,types_types)def_bytes_to_b64_str(bytes_:bytes)->str:returnbase64.b64encode(bytes_).decode("utf-8")def_get_message_openai_role(message:BaseMessage)->str:ifisinstance(message,AIMessage):return"assistant"elifisinstance(message,HumanMessage):return"user"elifisinstance(message,ToolMessage):return"tool"elifisinstance(message,SystemMessage):returnmessage.additional_kwargs.get("__openai_role__","system")elifisinstance(message,FunctionMessage):return"function"elifisinstance(message,ChatMessage):returnmessage.roleelse:msg=f"Unknown BaseMessage type {message.__class__}."raiseValueError(msg)# noqa: TRY004def_convert_to_openai_tool_calls(tool_calls:list[ToolCall])->list[dict]:return[{"type":"function","id":tool_call["id"],"function":{"name":tool_call["name"],"arguments":json.dumps(tool_call["args"]),},}fortool_callintool_calls]
[docs]defcount_tokens_approximately(messages:Iterable[MessageLikeRepresentation],*,chars_per_token:float=4.0,extra_tokens_per_message:float=3.0,count_name:bool=True,)->int:"""Approximate the total number of tokens in messages. The token count includes stringified message content, role, and (optionally) name. - For AI messages, the token count also includes stringified tool calls. - For tool messages, the token count also includes the tool call ID. Args: messages: List of messages to count tokens for. chars_per_token: Number of characters per token to use for the approximation. Default is 4 (one token corresponds to ~4 chars for common English text). You can also specify float values for more fine-grained control. See more here: https://platform.openai.com/tokenizer extra_tokens_per_message: Number of extra tokens to add per message. Default is 3 (special tokens, including beginning/end of message). You can also specify float values for more fine-grained control. See more here: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb count_name: Whether to include message names in the count. Enabled by default. Returns: Approximate number of tokens in the messages. Note: This is a simple approximation that may not match the exact token count used by specific models. For accurate counts, use model-specific tokenizers. Warning: This function does not currently support counting image tokens. .. versionadded:: 0.3.46 """token_count=0.0formessageinconvert_to_messages(messages):message_chars=0ifisinstance(message.content,str):message_chars+=len(message.content)# TODO: add support for approximate counting for image blockselse:content=repr(message.content)message_chars+=len(content)if(isinstance(message,AIMessage)# exclude Anthropic format as tool calls are already included in the contentandnotisinstance(message.content,list)andmessage.tool_calls):tool_calls_content=repr(message.tool_calls)message_chars+=len(tool_calls_content)ifisinstance(message,ToolMessage):message_chars+=len(message.tool_call_id)role=_get_message_openai_role(message)message_chars+=len(role)ifmessage.nameandcount_name:message_chars+=len(message.name)# NOTE: we're rounding up per message to ensure that# individual message token counts add up to the total count# for a list of messagestoken_count+=math.ceil(message_chars/chars_per_token)# add extra tokens per messagetoken_count+=extra_tokens_per_message# round up once more time in case extra_tokens_per_message is a floatreturnmath.ceil(token_count)