Introduction
An introduction to how to use Langchain.
Basic writing with LCEL will be introduced.
The model used was gpt-3.5-turbo.
Reference Documents
Official Documents
https://python.langchain.com/docs/get_started/quickstart
LCEL
https://python.langchain.com/docs/expression_language/
Setup
Install
python -V
Python 3.11.6
pip install python-dotenv
pip install langchain
pip show langchain
Version: 0.1.9
pip install langchain-openai
pip show langchain-openai
Version: 0.0.7
pip install langchain-core
pip show langchain-core
Version: 0.1.27
Create File
Create a directory (e.g. test_langchain)
- /test_langchain/.env
- /test_langchain/test.py
ENV file
Set your OpenAI API Key.
OPENAI_API_KEY="***********"
Sample code
test.py
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
load_dotenv()
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, model="gpt-3.5-turbo", temperature=0)
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a culinary expert"),
("user", "{input}"),
]
)
output_parser = StrOutputParser()
# LCEL
chain1 = prompt
chain2 = prompt | llm
chain3 = prompt | llm | output_parser
response1 = chain1.invoke({"input": "Speaking of good Japanese food, name one."})
print(response1)
print("------------")
response2 = chain2.invoke({"input": "Speaking of good Japanese food, name one."})
print(response2)
print("------------")
response3 = chain3.invoke({"input": "Speaking of good Japanese food, name one."})
print(response3)
print("------------")
Execute from a terminal.
python test.py
Output Result
Results are displayed for each pattern.
If StrOutputParser() is used, the value of response is the response statement only.
messages=[SystemMessage(content='You are a culinary expert'), HumanMessage(content='Speaking of good Japanese food, name one.')]
------------
content='One popular Japanese dish is sushi. Sushi is a dish that typically consists of vinegared rice topped with various ingredients such as raw fish, seafood, vegetables, and sometimes tropical fruits. It is often served with soy sauce, wasabi, and pickled ginger. Sushi can be enjoyed in many different forms, such as nigiri (sliced fish on top of rice), sashimi (sliced raw fish without rice), maki (rolled sushi), and temaki (hand-rolled sushi).'
------------
One popular Japanese dish is sushi. It typically consists of vinegared rice topped with various ingredients such as raw fish, seafood, vegetables, and sometimes tropical fruits. Sushi is not only delicious but also visually appealing, making it a favorite choice for many people around the world.
------------
Conclusion
This time I used ChatGPT and tried a simple description using LCEL.
Langchain is updated frequently, so it is recommended that you check it regularly.
Top comments (0)