{ "cells": [ { "cell_type": "markdown", "id": "872bb8b5", "metadata": {}, "source": [ "# Transformation\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": 1, "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": 3, "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": 4, "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", "\n", "transform_chain = TransformChain(\n", " input_variables=[\"text\"], output_variables=[\"output_text\"], transform=transform_func\n", ")" ] }, { "cell_type": "code", "execution_count": 5, "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": 7, "id": "f7caa1ee", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' The speaker addresses the nation, noting that while last year they were kept apart due to COVID-19, this year they are together again. They are reminded that regardless of their political affiliations, they are all Americans.'" ] }, "execution_count": 7, "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.11.3" } }, "nbformat": 4, "nbformat_minor": 5 }