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

解决调用Claude 3.7接口 403 Request not allowed问题

1.  遇到问题

        Python 基于 Langchain 对接 Claude 3.7 大模型接口进行问答时,由于国内不在Claude支持的国家和地区,所以一直调不通,错误    anthropic.PermissionDeniedError: Error code: 403 - {'error': {'type': 'forbidden', 'message': 'Request not allowed'}} 

         详细堆栈如下:

ERROR:root:Error code: 403 - {'error': {'type': 'forbidden', 'message': 'Request not allowed'}}
Traceback (most recent call last):File "E:\Idea_workspace\Temp_view\test-python\test\llm\test_claude37.py", line 58, in <module>for chunk in llm.stream(messages):File "D:\Program Files\Python311\Lib\site-packages\langchain_core\language_models\chat_models.py", line 494, in streamfor chunk in self._stream(input_messages, stop=stop, **kwargs):File "D:\Program Files\Python311\Lib\site-packages\langchain_anthropic\chat_models.py", line 995, in _streamstream = self._client.messages.create(**payload)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "D:\Program Files\Python311\Lib\site-packages\anthropic\_utils\_utils.py", line 275, in wrapperreturn func(*args, **kwargs)^^^^^^^^^^^^^^^^^^^^^File "D:\Program Files\Python311\Lib\site-packages\anthropic\resources\messages\messages.py", line 953, in createreturn self._post(^^^^^^^^^^^File "D:\Program Files\Python311\Lib\site-packages\anthropic\_base_client.py", line 1336, in postreturn cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "D:\Program Files\Python311\Lib\site-packages\anthropic\_base_client.py", line 1013, in requestreturn self._request(^^^^^^^^^^^^^^File "D:\Program Files\Python311\Lib\site-packages\anthropic\_base_client.py", line 1117, in _requestraise self._make_status_error_from_response(err.response) from None
anthropic.PermissionDeniedError: Error code: 403 - {'error': {'type': 'forbidden', 'message': 'Request not allowed'}}

2.  解决问题

        调用Claude 3.7 进行问答时,通常会采用流式输出 或 异步调用,这两种不同的调用 解决403有点差异。 原理都是通过设置代理客户端(如下图,配上ip:端口就能访问外网的那种)、转发请求。

代码里有注释,所以就不过多说明了,有问题可留言沟通。


from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
import httpx
import os
import dotenv
import logging
import asynciodotenv.load_dotenv()
INPUT_PLACEHOLDER = '{input}'
# 读取环境变量值,或直接改为你的代理地址,比如:proxy_url = http://192.168.1.101:10082
proxy_url = os.getenv("CLAUDE_PROXY")if proxy_url:#新建异步httpx客户端async_transport = httpx.AsyncHTTPTransport(proxy=httpx.Proxy(url=proxy_url))async_http_client = httpx.AsyncClient(transport=async_transport)#新建httpx客户端transport = httpx.HTTPTransport(proxy=httpx.Proxy(url=proxy_url))http_client = httpx.Client(transport=transport)
else:async_http_client = Nonehttp_client = None
llm = ChatAnthropic(thinking={"type": "enabled","budget_tokens": 4096},model="claude-3-7-sonnet-20250219",max_tokens=8192
)
if http_client:# 设置同步httpx客户端llm._client._client = http_client
if async_http_client:# 设置异步httpx客户端llm._async_client._client = async_http_client
system_prompt = """
你是一个人工智能助手,你可以回答用户的问题。"""
prompt = ChatPromptTemplate.from_messages([("system", system_prompt),("user", INPUT_PLACEHOLDER)
])
output_parser = StrOutputParser()
messages = prompt.format(input="你是谁?中文回答")# Stream 流式输出 同步调用
try:for chunk in llm.stream(messages):print("" + chunk.text(), end="")
except Exception as e:logging.exception(e)#Async 异步调用
async def main():result = await llm.ainvoke(messages)print("\n\n异步:" + result.text())asyncio.run(main())

效果如图

 3. 总结

        其实Claude 3.7 403问题一直困扰研发团队,不得不 花钱租用Aws服务器在上面做调试&开发,成本又高又不方便(尤其是多人使用)。

        后来找时间看了些 langchain_anthropic和httpx的源码 该问题才算完美解决。


文章转载自:

http://leNoPGIF.mqghs.cn
http://g5Vs8Rq3.mqghs.cn
http://4v7alXH0.mqghs.cn
http://J50YSQ5U.mqghs.cn
http://AUGdCiiI.mqghs.cn
http://HPEprFPo.mqghs.cn
http://UkugL8ck.mqghs.cn
http://REjF0zD4.mqghs.cn
http://8iyVKecI.mqghs.cn
http://Nv9k2aRf.mqghs.cn
http://ONyC7Dqx.mqghs.cn
http://ZjLJR3ei.mqghs.cn
http://yLuSnAGK.mqghs.cn
http://bzSv2fyV.mqghs.cn
http://niiVTG9Y.mqghs.cn
http://VW3NbB1S.mqghs.cn
http://cGyjWmJU.mqghs.cn
http://zZT2cgam.mqghs.cn
http://FUmyO1As.mqghs.cn
http://82hzJCQ5.mqghs.cn
http://uSvGHmb8.mqghs.cn
http://ZV4pFT0C.mqghs.cn
http://wLwZOugW.mqghs.cn
http://SLqRUHHb.mqghs.cn
http://fsH7Gecp.mqghs.cn
http://3UuxNxnp.mqghs.cn
http://j4DoP0qy.mqghs.cn
http://CUgJoLSr.mqghs.cn
http://rM68NBcD.mqghs.cn
http://wwdXkrXX.mqghs.cn
http://www.dtcms.com/a/163221.html

相关文章:

  • Linux 内核中 TCP 协议的支撑解析
  • 通信协议:数字世界的隐形语言——从基础认知到工程实践-优雅草卓伊凡
  • C++每日训练 Day 18:构建响应式表单与数据验证(初学者友好)
  • [USACO08DEC] Hay For Sale S Java
  • WPF(Windows Presentation Foundation)的内容模型
  • Go 语言中的 `os.Truncate` 函数详解
  • STM32单片机入门学习——第49节: [15-2] 读写内部FLASH读取芯片ID
  • 本地大模型编程实战(29)查询图数据库NEO4J(2)
  • Mysql中索引的知识
  • 洛谷P12238 [蓝桥杯 2023 国 Java A] 单词分类
  • 基于LVS+Keepalived+NFS的高可用负载均衡集群部署
  • 基于大模型的大肠息肉全程管理研究报告
  • 破茧成蝶:一家传统制造企业的年轻化转型之路
  • 总结小程序的坑
  • ​钓鱼网页散播银狐木马,远控后门威胁终端安全
  • 数字中国浪潮下:Coremail AI赋能邮件办公,筑牢安全防线引领转型
  • VSCode突然连接不上服务器(已解决)
  • “情况说明“以后,Unity XR 开发者如何选择?
  • JavaWeb:后端web基础(TomcatServletHTTP)
  • Linux《进程概念(中)》
  • SSM书籍管理(业务编写)
  • c#WebsocketSever
  • 【3D基础】顶点法线与平面法线在光照与PBR中的区别与影响
  • 第13讲:图形尺寸与分辨率设置——适配论文版面,打造专业图稿!
  • upload-labs PASS 1-5通关
  • 【无报错,亲测有效】如何在Windows和Linux系统中查看MySQL版本
  • 第一章 应急响应- Linux入侵排查
  • PyTorch 深度学习实战(23):多任务强化学习(Multi-Task RL)之扩展
  • C++23中的std::forward_like:完美转发的增强
  • Qt入门——什么是Qt?