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

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
  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 | 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
参考:

  1. ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/

http://www.kler.cn/a/383326.html

相关文章:

  • 【C++基础】09、结构体
  • 深入解析:Python中的决策树与随机森林
  • springboot472基于web网上村委会业务办理系统(论文+源码)_kaic
  • GOC编程 第2课 简单命令---直走和转弯命令
  • 安装fast_bev环境
  • 机器学习基础算法 (一)-线性回归
  • Hive专栏概述
  • 【Linux系统编程】第四十一弹---线程深度解析:从地址空间到多线程实践
  • 什么是采购合同管理?
  • 机器学习—神经网络中的层
  • 开源工业软件产教融合生态论坛 | 2024 CCF中国开源大会分论坛
  • RNN中的梯度消失与梯度爆炸问题
  • 化学学习和工作常用网站推荐
  • 如何用ChatGPT结合Python处理遥感数据
  • 家在你心里意味着什么?
  • 【计算机网络】零碎知识点(易忘 / 易错)总结回顾
  • SD-WAN助力企业实现供应链数字化
  • scala set训练
  • 数据采集之scrapy框架
  • 每日一题——第一百二十四题
  • PPO(Proximal Policy Optimization)算法介绍
  • Ubuntu Docker 安装
  • template和span标签的使用
  • Kafka相关知识点(上)
  • 删除GitLab仓库中项目下面的多个文件夹
  • 【数据库系统概论】第3章 关系数据库标准语言SQL(二)数据查询(超详细)