How to parse text from message objects
This guide assumes familiarity with the following concepts:
LangChainmessage objects support content in avariety of formats, including text,multimodal data, and a list ofcontent block dicts.
The format ofChat model response content may depend on the provider. For example, the chat model forAnthropic will return string content for typical string input:
from langchain_anthropicimport ChatAnthropic
llm= ChatAnthropic(model="claude-3-5-haiku-latest")
response= llm.invoke("Hello")
response.content
'Hi there! How are you doing today? Is there anything I can help you with?'
But when tool calls are generated, the response content is structured into content blocks that convey the model's reasoning process:
from langchain_core.toolsimport tool
@tool
defget_weather(location:str)->str:
"""Get the weather from a location."""
return"Sunny."
llm_with_tools= llm.bind_tools([get_weather])
response= llm_with_tools.invoke("What's the weather in San Francisco, CA?")
response.content
[{'text': "I'll help you get the current weather for San Francisco, California. Let me check that for you right away.",
'type': 'text'},
{'id': 'toolu_015PwwcKxWYctKfY3pruHFyy',
'input': {'location': 'San Francisco, CA'},
'name': 'get_weather',
'type': 'tool_use'}]
To automatically parse text from message objects irrespective of the format of the underlying content, we can useStrOutputParser. We can compose it with a chat model as follows:
from langchain_core.output_parsersimport StrOutputParser
chain= llm_with_tools| StrOutputParser()
StrOutputParser simplifies the extraction of text from message objects:
response= chain.invoke("What's the weather in San Francisco, CA?")
print(response)
I'll help you check the weather in San Francisco, CA right away.
This is particularly useful in streaming contexts:
for chunkin chain.stream("What's the weather in San Francisco, CA?"):
print(chunk, end="|")
|I'll| help| you get| the current| weather for| San Francisco, California|. Let| me retrieve| that| information for you.||||||||||
See theAPI Reference for more information.