diff --git a/sequential-chain/.env.example b/sequential-chain/.env.example new file mode 100644 index 0000000..89d34a6 --- /dev/null +++ b/sequential-chain/.env.example @@ -0,0 +1,5 @@ +OPENAI_API_KEY="" +LANGCHAIN_TRACING_V2=true +LANGCHAIN_ENDPOINT="https://api.smith.langchain.com" +LANGCHAIN_API_KEY="" +LANGCHAIN_PROJECT="" diff --git a/sequential-chain/.gitignore b/sequential-chain/.gitignore new file mode 100644 index 0000000..82f9275 --- /dev/null +++ b/sequential-chain/.gitignore @@ -0,0 +1,162 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/sequential-chain/image.png b/sequential-chain/image.png new file mode 100644 index 0000000..2f54f02 Binary files /dev/null and b/sequential-chain/image.png differ diff --git a/sequential-chain/readme.md b/sequential-chain/readme.md new file mode 100644 index 0000000..03296bf --- /dev/null +++ b/sequential-chain/readme.md @@ -0,0 +1,3 @@ +# Langchain Sequential Chain + +![alt text](image.png) \ No newline at end of file diff --git a/sequential-chain/requirements.txt b/sequential-chain/requirements.txt new file mode 100644 index 0000000..1016ee1 --- /dev/null +++ b/sequential-chain/requirements.txt @@ -0,0 +1,5 @@ +langchain +langchain_community +langchain_openai +langsmith +python_dotenv \ No newline at end of file diff --git a/sequential-chain/seqChain.ipynb b/sequential-chain/seqChain.ipynb new file mode 100644 index 0000000..30e281f --- /dev/null +++ b/sequential-chain/seqChain.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#Perform a Sequential chain in Langchain" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from dotenv import load_dotenv, find_dotenv\n", + "load_dotenv(find_dotenv())" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_openai import ChatOpenAI\n", + "from langchain_core.prompts import ChatPromptTemplate\n", + "from langchain_core.output_parsers import StrOutputParser\n", + "from langchain.chains import SequentialChain, LLMChain\n", + "from langchain.schema.runnable import RunnablePassthrough" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# using the Chat OpenAI GPT 4o-mini\n", + "llm = ChatOpenAI(temperature=0.0, model=\"gpt-4o-mini\")" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# List of Prompts to be used\n", + "original_review_prompt = \"\"\" \n", + "Translate the below review in English. If it is already in English, skip the translation and output the same review.\n", + "Review: {review}\n", + "\"\"\"\n", + "prompt1 = ChatPromptTemplate.from_template(original_review_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "summary_creation_prompt = \"\"\" \n", + "Create a concise summary of the following text, ensuring that the summary captures the main points and essential information.\n", + "Text: {english_review}\n", + "\"\"\"\n", + "prompt2 = ChatPromptTemplate.from_template(summary_creation_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "language_check_prompt =\"\"\" \n", + "Identify the language of the following review:\n", + "\\n\\n\n", + "{review}\n", + "\"\"\"\n", + "prompt3 = ChatPromptTemplate.from_template(language_check_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "find_sentiment_prompt = \"\"\"\n", + "You are a sentiment analysis expert. You will be given a sentence and you need to find the sentiment of the sentence.\n", + "The sentiment can be one of the following Review:\n", + "1. Positive 2. Negative 3. Neutral\n", + "\\n\\n\n", + "Review: {review}\n", + "English Review: {english_review}\n", + "Summary: {summary}\n", + "Original Review Language: {review_language}\n", + "\n", + "Determine the sentiment of the review and return the result in the following format:\n", + "Sentiment: \n", + "\\n\\n\n", + "\"\"\"\n", + "\n", + "prompt4 = ChatPromptTemplate.from_template(find_sentiment_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "build_email_response_prompt = \"\"\"\n", + "You are an expert email design assistant and good customer service agent. Your task is to generate a professional and engaging consise email response based on the customer review.\n", + "Thank them for their feedback in the response. If in case of any negative feedback, make it more polite, engaging and professional. \n", + "Sign the email with 'Sincerely, [Your Name]' at the end.\n", + "Use the below details.\n", + "\n", + "Review: {review}\n", + "English Review: {english_review}\n", + "Summary: {summary}\n", + "Original Review Language: {review_language}\n", + "Sentiment: {sentiment}\n", + "\"\"\"\n", + "prompt5 = ChatPromptTemplate.from_template(build_email_response_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Now goes the chains\n", + "output_parser = StrOutputParser()\n", + "original_review_chain = prompt1 | llm | output_parser\n", + "summary_creation_chain = prompt2 | llm | output_parser\n", + "language_check_chain = prompt3 | llm | output_parser\n", + "sentiment_check_chain = prompt4 | llm | output_parser\n", + "build_email_chain = prompt5 | llm | output_parser" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "final_chain = ({\"review\":RunnablePassthrough(),\"english_review\":original_review_chain}\n", + " |RunnablePassthrough.assign(summary = summary_creation_chain)\n", + " |RunnablePassthrough.assign(review_language = language_check_chain)\n", + " |RunnablePassthrough.assign(sentiment = sentiment_check_chain)\n", + " |RunnablePassthrough.assign(automated_email =build_email_chain)\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "review = \"\"\" Titre: Déçu par la qualité et le confort\n", + "\n", + "Avis: Je suis déçu par cette chemise. La coupe est trop serrée, bien que j'aie commandé ma taille habituelle. Le tissu est rigide et inconfortable, surtout après le lavage. La qualité ne vaut pas le prix. Je ne recommande pas cet achat.\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'review': \" Titre: Déçu par la qualité et le confort\\n\\nAvis: Je suis déçu par cette chemise. La coupe est trop serrée, bien que j'aie commandé ma taille habituelle. Le tissu est rigide et inconfortable, surtout après le lavage. La qualité ne vaut pas le prix. Je ne recommande pas cet achat.\",\n", + " 'english_review': 'Title: Disappointed by the quality and comfort\\n\\nReview: I am disappointed with this shirt. The fit is too tight, even though I ordered my usual size. The fabric is stiff and uncomfortable, especially after washing. The quality is not worth the price. I do not recommend this purchase.',\n", + " 'summary': 'The reviewer expresses disappointment with the shirt, citing a tight fit despite ordering the usual size, stiff and uncomfortable fabric after washing, and overall poor quality for the price. They do not recommend the purchase.',\n", + " 'review_language': 'The language of the review is French.',\n", + " 'sentiment': 'Sentiment: Negative',\n", + " 'automated_email': \"Subject: Thank You for Your Feedback\\n\\nDear [Customer's Name],\\n\\nThank you for taking the time to share your thoughts about the shirt. We genuinely appreciate your feedback, as it helps us improve our products and services.\\n\\nWe are sorry to hear that the fit and quality did not meet your expectations. Your experience is important to us, and we will certainly take your comments into consideration as we strive to enhance our offerings. \\n\\nIf you would like to discuss this further or explore alternative options, please feel free to reach out. We are here to help!\\n\\nSincerely, \\n[Your Name]\"}" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "result = final_chain.invoke(review)\n", + "result" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "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.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}