LangChain 是一个旨在帮助开发人员构建由大型语言模型(LLMs)驱动的应用程序的框架。其主要特点如下:
安装 LangChain 到 Python 环境
LangChain作为一个框架由许多包组成
pip install langchain // 0.2.10
pip install langcahin_community // 0.2.9
pip install langchain_openai // 0.1.17
可以使用pip show package_name
验证和查看版本
LangChain 0.2
Runnable interface
LangChain 引入了一个标准接口 “Runnable” 协议,旨在简化自定义链的创建和调用过程。该协议已在多个 LangChain 组件中实现,包括聊天模型、LLM、输出解析器、检索器和提示模板等。通过统一的接口,开发者可以更轻松地定义和调用自定义链。
Runnable 协议包含以下标准接口方法:
组件 | 输入类型 | 输出类型 |
---|---|---|
Prompt | Dictionary | PromptValue |
ChatModel | 单字符串、聊天消息列表或 PromptValue | ChatMessage |
LLM | 单字符串、聊天消息列表或 PromptValue | String |
OutputParser | LLM 或 ChatModel 的输出 | 取决于解析器 |
Retriever | 单字符串 | 文档列表 |
Tool | 单字符串或字典(取决于工具) | 取决于工具 |
使用本地模型,可以通过 LM Studio、Ollama 等方式下载
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio", max_tokens=256, temperature=0.0, top_p=0.9)
llm.invoke("你好")
AIMessage(content='你好!很高兴能为你提供帮助。有什么问题或者需要我做的事情吗?', response_metadata={'token_usage': {'completion_tokens': 16, 'prompt_tokens': 24, 'total_tokens': 40}, 'model_name': 'Qwen/Qwen1.5-7B-Chat-GGUF/qwen1_5-7b-chat-q5_k_m.gguf', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-16d51193-ab6e-4462-bb18-9818b88962ec-0', usage_metadata={'input_tokens': 24, 'output_tokens': 16, 'total_tokens': 40})
AIMessage.content 即为返回内容
————————————————————
使用 OpenAI API 访问云端模型,例如通过 OpenAI 或 阿里云DashScope模型服务灵积 申请
from langchain_openai import ChatOpenAI
qwen = ChatOpenAI(model="qwen-turbo", api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", max_tokens=256, temperature=0.0, top_p=0.9)
qwen.invoke("你好")
AIMessage(content='你好!有什么我可以帮助你的吗?', response_metadata={'token_usage': {'completion_tokens': 8, 'prompt_tokens': 9, 'total_tokens': 17}, 'model_name': 'qwen-turbo', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-d9ef21c6-2b64-4982-964a-d55b651865a2-0', usage_metadata={'input_tokens': 9, 'output_tokens': 8, 'total_tokens': 17})
————————————————————
也可以直接调用 HuggingFace 上的模型
from langchain_community.llms.huggingface_hub import HuggingFaceHub
model = HuggingFaceHub(repo_id="openai-community/gpt2", task="text-generation", huggingfacehub_api_token="hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
response = model.generate(["Hello, how are you?"])
print(response)
generations=[[Generation(text="Hello, how are you?\n\nI'm a little bit of a nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd. I'm a big nerd")]] llm_output=None run=[RunInfo(run_id=UUID('0e4e40a7-d8ea-4a4b-8194-58c45bda66a5'))]
==================================
使用提示词模板 PromptTemplate
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that translates {input_language} to {output_language}."),
("user", "{input}")
])
chain = prompt | llm # 简单组合链,串联可运行对象
chain.invoke({
"input": "I love pr