Skip to content

Instantly share code, notes, and snippets.

@iht
Last active November 24, 2023 15:11
Show Gist options
  • Save iht/5ede79213d78558e2baf452b5e11b892 to your computer and use it in GitHub Desktop.
Save iht/5ede79213d78558e2baf452b5e11b892 to your computer and use it in GitHub Desktop.
Schema for a StructuredOutputParser in langchain
# See previous gist https://gist.github.com/iht/d5bedff9ee86ed5223cfa2ad06080ca0
import json
# ...
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
def _dict_to_json(x: dict) -> str:
return "```\n" + json.dumps(x) + "\n```"
response_schema = [
ResponseSchema(name="query", description="SQL query to solve the user question."),
ResponseSchema(name="question", description="Question asked by the user."),
ResponseSchema(name="context", description="Documents retrieved from the vector store.")]
output_parser = StructuredOutputParser.from_response_schemas(response_schema)
# ...
chain1 = question | docs | some_prompt | some_model1 | StrOutputParser()
json_chain1 = {"output": chain1} | question | docs | RunnableLambda(_dict_to_json) | StrOutputParser()
output_chain1 = json_chain1 | output_parser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment