Python 使用 langchain 过程中的错误总结
1. 环境
conda activate langchain
pip install -U langchain
$ pip show langchain
Name: langchain
Version: 0.3.7
Summary: Building applications with LLMs through composability
Home-page: https://github.com/langchain-ai/langchain
Author:
Author-email:
License: MIT
Location: ~/.conda/envs/langchain/lib/python3.10/site-packages
Requires: aiohttp, async-timeout, langchain-core, langchain-text-splitters, langsmith, numpy, pydantic, PyYAML, requests, SQLAlchemy, tenacity
Required-by: langchain-community
可知 langchain 为最新版本 0.3.7
2. 代码
使用 DevAGI 中转平台:
代码同目录下有 .env 文件,内容为
OPENAI_API_KEY=sk-zLNNYxxx
OPENAI_API_BASE=https://api.fe8.cn/v1
代码 model.py:
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
llm = ChatOpenAI() # 默认是gpt-3.5-turbo
response = llm.invoke("讲个笑话")
print(response.content)
2.1 报错 Unknown scheme for proxy URL URL(‘socks://127.0.0.1:1080/’) :
pydantic_core._pydantic_core.ValidationError: 1 validation error for ChatOpenAI
Value error, Unknown scheme for proxy URL URL('socks://127.0.0.1:1080/') [type=value_error, input_value={'model_kwargs': {}}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.9/v/value_error
- 终端解决方式:
$ unset all_proxy && unset ALL_PROXY
$ python model.py
- 代码形式:
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv, find_dotenv
import os
# 删除all_proxy环境变量
if 'all_proxy' in os.environ:
del os.environ['all_proxy']
# 删除ALL_PROXY环境变量
if 'ALL_PROXY' in os.environ:
del os.environ['ALL_PROXY']
_ = load_dotenv(find_dotenv())
llm = ChatOpenAI() # 默认是gpt-3.5-turbo
response = llm.invoke("讲个笑话")
print(response.content)
输出:
为什么兔子不爱上网?
因为他怕被网住了!
2.2 报错 openai.NotFoundError: 404 page not found
使用 Deepbricks 中转平台,启动代理后
代码:
from langchain_community.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
import os
# 删除all_proxy环境变量
if 'all_proxy' in os.environ:
del os.environ['all_proxy']
# 删除ALL_PROXY环境变量
if 'ALL_PROXY' in os.environ:
del os.environ['ALL_PROXY']
API_KEY = os.getenv("API_KEY")
BASE_URL = "https://api.deepbricks.ai/v1/chat/completions"
GPT_MODEL = "GPT-4o-mini"
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm = ChatOpenAI(
openai_api_key=API_KEY,
openai_api_base=BASE_URL,
model_name="GPT-4o-mini"
)
llm_chain = prompt | llm
question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
print(llm_chain.invoke(question))
报错:
...
File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/resources/chat/completions.py", line 830, in create
return self._post(
File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/_base_client.py", line 1281, in post
return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/_base_client.py", line 958, in request
return self._request(
File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/_base_client.py", line 1062, in _request
raise self._make_status_error_from_response(err.response) from None
openai.NotFoundError: 404 page not found
解决方法:
修改 ~/.conda/envs/langchain/lib/python3.10/site-packages/openai/resources/chat/completions.py
...
return self._post(
"/chat/completions",
...)
path 改成:
...
return self._post(
"https://api.deepbricks.ai/v1/chat/completions"
...)
运行:
LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-openai package and should be used instead. To use it run `pip install -U :class:`~langchain-openai` and import as `from :class:`~langchain_openai import ChatOpenAI``.
llm = ChatOpenAI(
content='Justin Bieber was born on March 1, 1994. To find out which NFL team won the Super Bowl that year, we need to identify the Super Bowl that took place in 1994.\n\nThe Super Bowl that followed the 1993 NFL season was Super Bowl XXVIII, which was played on January 30, 1994. In that game, the Dallas Cowboys played against the Buffalo Bills. The Cowboys won the game with a score of 30-13.\n\nTherefore, the NFL team that won the Super Bowl in the year Justin Bieber was born is the **Dallas Cowboys**.' additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 121, 'prompt_tokens': 33, 'total_tokens': 154, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GPT-4o-mini', 'system_fingerprint': 'fp_0ba0d124f1', 'finish_reason': 'stop', 'logprobs': None} id='run-cd444a45-5c5f-4e4c-8e65-e07b591e93e4-0'
Tips
参考:
- ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/