langchain/docs/examples/chains/transformation.ipynb
2022-12-06 22:55:27 -08:00

131 lines
3.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "872bb8b5",
"metadata": {},
"source": [
"# Transformation Chain\n",
"\n",
"This notebook showcases using a generic transformation chain.\n",
"\n",
"As an example, we will create a dummy transformation that takes in a super long text, filters the text to only the first 3 paragraphs, and then passes that into an LLMChain to summarize those."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "bbbb4330",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chains import TransformChain, LLMChain, SimpleSequentialChain\n",
"from langchain.llms import OpenAI\n",
"from langchain.prompts import PromptTemplate"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "8ae5937c",
"metadata": {},
"outputs": [],
"source": [
"with open('../state_of_the_union.txt') as f:\n",
" state_of_the_union = f.read()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "98739592",
"metadata": {},
"outputs": [],
"source": [
"def transform_func(inputs: dict) -> dict:\n",
" text = inputs[\"text\"]\n",
" shortened_text = \"\\n\\n\".join(text.split(\"\\n\\n\")[:3])\n",
" return {\"output_text\": shortened_text}\n",
"\n",
"transform_chain = TransformChain(input_variables=[\"text\"], output_variables=[\"output_text\"], transform=transform_func)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "e9397934",
"metadata": {},
"outputs": [],
"source": [
"template = \"\"\"Summarize this text:\n",
"\n",
"{output_text}\n",
"\n",
"Summary:\"\"\"\n",
"prompt = PromptTemplate(input_variables=[\"output_text\"], template=template)\n",
"llm_chain = LLMChain(llm=OpenAI(), prompt=prompt)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "06f51f17",
"metadata": {},
"outputs": [],
"source": [
"sequential_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain])"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "f7caa1ee",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"' This speech addresses the American people and acknowledges the difficulties of last year due to COVID-19. It emphasizes the importance of coming together regardless of political affiliation and encourages a sense of unity as Americans.'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sequential_chain.run(state_of_the_union)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3ca6409",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}