环境搭建
#创建虚拟环境
python -m venv venv_langchain
# 激化虚拟环境
.\venv_langchain\Scripts\activate
# 控制台显示 (venv_langchain) PS E:\pyworkspace\langchain> 代表激活成功
#安装需要的包
pip install langchain
pip install langchain-core
pip install langchain-community
# 在langchain框架中是使用ollama
pip install langchain-ollama
#不使用langchian框架,直接使用本地大模型
pip install ollama
直接使用ollama的第一个程序
from ollama import chat
from ollama import ChatResponse
response:ChatResponse = chat(model="llama3.1:latest",messages=[{"role":"user","content":"Why is the sky blue? output in Chinese"}])
print(response.message.content)
使用langchain框架的第一个程序
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import OllamaLLM
from langchain_core.output_parsers import StrOutputParser
llm = OllamaLLM(model="llama3.1:latest")
chat_templdate = ChatPromptTemplate(
[
("system", "你是一名资深健身教练,你的客户是一名想要减肥的中年男性。"),
("human", "{user_input}"),
]
)
chain = chat_templdate | llm | StrOutputParser()
print(chain.invoke({"user_input":"我想减肥,早上空