codekingpro/portable-devtools
114k
1"""String output parser."""2 3from typing_extensions import override4 5from langchain_core.output_parsers.transform import BaseTransformOutputParser6 7 8class StrOutputParser(BaseTransformOutputParser[str]):9 """Extract text content from model outputs as a string.10 11 Converts model outputs (such as `AIMessage` or `AIMessageChunk` objects) into plain12 text strings. It's the simplest output parser and is useful when you need string13 responses for downstream processing, display, or storage.14 15 Supports streaming, yielding text chunks as they're generated by the model.16 17 Example:18 ```python19 from langchain_core.output_parsers import StrOutputParser20 from langchain_openai import ChatOpenAI21 22 model = ChatOpenAI(model="gpt-4o")23 parser = StrOutputParser()24 25 # Get string output from a model26 message = model.invoke("Tell me a joke")27 result = parser.invoke(message)28 print(result) # plain string29 30 # With streaming - use transform() to process a stream31 stream = model.stream("Tell me a story")32 for chunk in parser.transform(stream):33 print(chunk, end="", flush=True)34 ```35 """36 37 @classmethod38 def is_lc_serializable(cls) -> bool:39 """`StrOutputParser` is serializable.40 41 Returns:42 `True`43 """44 return True45 46 @classmethod47 def get_lc_namespace(cls) -> list[str]:48 """Get the namespace of the LangChain object.49 50 Returns:51 `["langchain", "schema", "output_parser"]`52 """53 return ["langchain", "schema", "output_parser"]54 55 @property56 def _type(self) -> str:57 """Return the output parser type for serialization."""58 return "default"59 60 @override61 def parse(self, text: str) -> str:62 """Returns the input text with no changes."""63 return text64 