当前位置: 首页 > news >正文

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 ChatOpenAIValue 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
  1. 终端解决方式:
$ unset all_proxy && unset ALL_PROXY
$ python model.py
  1. 代码形式:
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 | llmquestion = "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 createreturn self._post(File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/_base_client.py", line 1281, in postreturn 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 requestreturn self._request(File "~/.conda/envs/langchain/lib/python3.10/site-packages/openai/_base_client.py", line 1062, in _requestraise 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
参考:

  1. ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/
http://www.lryc.cn/news/478631.html

相关文章:

  • MySQL基础篇总结
  • 全面解析:网络协议及其应用
  • 一文了解Java序列化
  • 【前端基础】CSS基础
  • Linux之selinux和防火墙
  • 架构零散知识点
  • 【从零开始的LeetCode-算法】3254. 长度为 K 的子数组的能量值 I
  • 跨IDE开发
  • 2020年美国总统大选数据分析与模型预测
  • C++应用场景开发——学生信息管理系统!!!
  • Pytorch实现transformer语言模型
  • Java后台生成指定路径下创建指定名称的文件
  • sqlcoder70b模型,如果需要训练或者微调需要什么样的GPU机器
  • 【Python实战案例】爬虫项目实例(附赠源码)
  • PDF多功能工具箱 PDF Shaper v14.6
  • Jupyter Notebook添加kernel的解决方案
  • Linux 无名管道
  • Java项目实战II基于Spring Boot的药店管理系统的设计与实现(开发文档+数据库+源码)
  • 前端拖拽库方案之react-beautiful-dnd
  • 【题解】CF2033G
  • 【error】 react 控制台报错Invalid hook call
  • SDL基本使用
  • 大模型的temperature参数
  • 软件项目功能复用指南,复用方案,评估方案(word原件)
  • leetcode 3255 长度为 K 的子数组的能量值 II 中等
  • CCS下载安装(以12.3.0版本为例)
  • C++STL容器详解——list
  • linux tar 打包为多个文件
  • json字符串与python字典的区别与联系
  • 数据结构-链表【chapter1】【c语言版】