liveBook · Manning

StrOutputParser

As explained in MongoDB 8.0 in Action, Third Edition

StrOutputParser is a LangChain component that converts a language-model result into a string output.

StrOutputParser is a LangChain output component that converts a language-model response into plain text for presentation as a chatbot’s final answer. section 14.5.4 section 14.5.2

Use it as the final stage of a retrieval-augmented generation chain:

  • Retrieve relevant documents through MongoDB Atlas Vector Search. section 14.5.4
  • Combine retrieved content and metadata with the user’s question in a ChatPromptTemplate. section 14.5.4
  • Pass the structured prompt to ChatOpenAI, then send its response to StrOutputParser. section 14.5.4
  • Return the parser’s string result to the user instead of exposing the model response structure. section 14.5.4 section 14.5.2

Final chatbot output

A model response containing generation metadata and a text field can become a simple output such as: “MongoDB supports compound, geospatial, text search, unique, array, TTL, sparse, partial, hash, and collated indexes.” section 14.5.4

import os
from langchain_openai import ChatOpenAI
from langchain_community.document_loaders import PyPDFLoader
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import MongoDBAtlasVectorSearch
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables import (
    RunnableLambda,
    RunnableParallel,
    RunnablePassthrough,
)
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pymongo import MongoClient

# Set DB
if os.environ.get("MONGO_URI", None) is None:
    raise Exception("Missing `MONGO_URI` environment variable.")
MONGO_URI = os.environ["MONGO_URI"]

DB_NAME = "langchain"
COLLECTION_NAME = "mongodb"
ATLAS_VECTOR_SEARCH_INDEX_NAME = "default"

client = MongoClient(MONGO_URI)
db = client[DB_NAME]
MONGODB_COLLECTION = db[COLLECTION_NAME]

# Read from MongoDB Atlas Vector Search
vectorstore = MongoDBAtlasVectorSearch.from_connection_string(
    MONGO_URI,
    DB_NAME + "." + COLLECTION_NAME,
    OpenAIEmbeddings(disallowed_special=()),
    index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
)
retriever = vectorstore.as_retriever(search_kwargs={"k": 1})

# RAG prompt
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

# RAG
model = ChatOpenAI()
chain = (
   RunnableParallel({"context": retriever,
➥"question": RunnablePassthrough()})
    | prompt
    | model
    | StrOutputParser()
)


# Add typing for input
class Question(BaseModel):
    __root__: str


chain = chain.with_types(input_type=Question)


def _ingest(url: str) -> dict:
    loader = PyPDFLoader(url)
    data = loader.load()

    # Split docs
    text_splitter = RecursiveCharacterTextSplitter
➥(chunk_size=500, chunk_overlap=0)
    docs = text_splitter.split_documents(data)

    # Insert the documents in MongoDB Atlas Vector Search
    _ = MongoDBAtlasVectorSearch.from_documents(
        documents=docs,
        embedding=OpenAIEmbeddings(disallowed_special=()),
        collection=MONGODB_COLLECTION,
        index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
    )
    return {}

ingest = RunnableLambda(_ingest)

Inspect the Python chain imports and placement of StrOutputParser alongside ChatOpenAI, prompts, vector search, and runnable components. section 14.5.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains its position and purpose in the runnable chain but does not detail parser internals or configuration options.
Examples
Demonstrates conversion through a MongoDB-indexes question whose generated answer becomes a simple output string.
What it assumes
Assumes a LangChain runnable chain and language-model response, while showing the conversion step without requiring parser implementation knowledge.
What you can do after
Apply it via LangChain to expose a model’s generated answer as a user-facing string.
How it connects
Connects output parsing with ChatOpenAI, ChatPromptTemplate, RunnableParallel, RunnablePassthrough, retrievers, and MongoDB Atlas Vector Search.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.