Giter VIP home page Giter VIP logo

claude2-pyapi's Introduction

Claude2 -pyAPI

主要功能,实现Claude2 创建会话、聊天、发送附件、获取历史会话,清理历史记录等功能

先决条件

  要使用这个API,您需要有以下:      Python安装在您的系统上

​ python =">=3.7"

  请求库安装

  pip install requests
  pip install python-dotenv

使用

在您的Python脚本导入claude_api模块:

from claude_api import Client
  • 接下来,你需要创建一个客户端类的实例通过提供你的Claude AI cookie:

  • 你可以通过浏览器访问https://claude.ai/ 确保你能通过网页调用Claude2 访问。然后通过F12浏览器抓取cookies 值

  • image-20230727113153074

    cookie = os.environ.get('cookie')
    claude_api = Client(cookie)
    

使用2

使用docker 方式启动

​ docker 编译打包镜像

docker build -t=wwwzhouhui/claude2-pyapi:0.0.2 .

​ docker 启动

docker run -d -p 5000:5000 -e "cookie=aaa" -e "uploads=/home/claude/uploads" -v /home/claude/uploads:/home/claude/uploads wwwzhouhui/claude2-pyapi:0.0.2

​ -p 启动容器内部端口5000,对外访问端口5000

​ -e 容器启动参数通过cookie 传递参数。

​ -v 读取文件附件临时文件,通过docker 挂卷方式。

​ 启动后

image-20230801135355477

​ cmd 命令行查看容器启动

image-20230801135526791

​ 容器内部启动日志

image-20230801135703958

IM启动

​ IM 功能入口程序是ImApp.py 所以启动如下命令

​ windows 命令

Python3  ImApp.py

​ linux 命令

nohup python3 ImApp.py & tail -f nohup.out

使用 replit 部署

Run on Repl.it

https://replit.com/@wwwzhouhui/Claude2-PyAPI#replit.nix

列出所有的对话

列出所有会话Id与Claude ,你可以使用list_all_conversations方法:

conversations = claude_api.list_all_conversations()
for conversation in conversations:
    conversation_id = conversation['uuid']
    print(conversation_id)

发送消息

发送消息给 Claude, 您可以使用send_message方法。您需要提供提示和对话ID:

prompt = "Hello, Claude!"
conversation_id = "<conversation_id>" or claude_api.create_new_chat()['uuid']
response = claude_api.send_message(prompt, conversation_id)
print(response)

发送消息带附件

你可以发送任何类型的附件claude 得到响应中使用附件参数send_message ()

注意:claude 目前只支持某些文件类型

prompt = "Hey,Summarize me this document.!"
conversation_id = "<conversation_id>" or claude_api.create_new_chat()['uuid']
response = claude_api.send_message(prompt, conversation_id,attachment="path/to/file.pdf")
print(response)

删除对话

删除一个对话,你可以使用delete_conversation方法:

conversation_id = "<conversation_id>"
deleted = claude_api.delete_conversation(conversation_id)
if deleted:
    print("Conversation deleted successfully")
else:
    print("Failed to delete conversation")

聊天对话的历史

聊天对话记录,您可以使用chat_conversation_history方法:

conversation_id = "<conversation_id>"
history = claude_api.chat_conversation_history(conversation_id)
print(history)

创建新的聊天

创建一个新的聊天对话(id),您可以使用create_new_chat方法:

new_chat = claude_api.create_new_chat()
conversation_id = new_chat['uuid']
print(conversation_id)

重置所有对话

重置所有对话,您可以使用reset_all方法:

reset = claude_api.reset_all()
if reset:
    print("All conversations reset successfully")
else:
    print("Failed to reset conversations")   

重命名聊天

重命名一个聊天对话,你可以使用rename_chat方法:

conversation_id = "<conversation_id>"
title = "New Chat Title"
renamed = claude_api.rename_chat(title, conversation_id)
if renamed:
    print("Chat conversation renamed successfully")
else:
    print("Failed to rename chat conversation")

​ 测试

​ 启动claude_flask.py

  1. 获取历史会话

    1. image-20230727113933463

    postman 导入测试的请求接口json

get 请求,获取当前会话历史记录 http://127.0.0.1:5000/chat/0c24bd45-ac55-4a24-8393-1582369f5abd

其中0c24bd45-ac55-4a24-8393-1582369f5abd 是对话ID

请求参数 无:

image-20230727114240619

​ 点击 send postman 接口会调用 启动的flask 程序,调用成功后postman 接口会返回当天聊天会话历史记录

image-20230727114435649

​ 程序控制台会返回请求 GET /chat/0c24bd45-ac55-4a24-8393-1582369f5abd 返回200

image-20230727114534664

  1. 创建新会话

    请求 方式 POST 请求url http://127.0.0.1:5000/chat

    headhers 设置 Content-Type= application/json

    image-20230727114755516

​ body 请求参数, prompt 是固定值, 后面是您需要问的问题。

​ {

​ "prompt": "亚洲金融危机爆发时间是什么时候?请告诉我为什么会出现金融危机?"

​ }

image-20230727114914418

​ 请求返回

image-20230727115103581

我们刷新一下网页端,查看当前浏览器

image-20230727115222342

3 当前会话中发送消息

请求 方式 POST 请求url http://127.0.0.1:5000/send

headhers 设置 Content-Type= application/json

image-20230727115403219

​ body 请求参数, prompt 是固定值, 后面是您需要问的问题。conversation_id 当前聊天会话ID

​ {

​ "conversation_id": "0c24bd45-ac55-4a24-8393-1582369f5abd",

​ "prompt": "**和美国的科技有哪些差距?估计多少年才能缩小差距?!"

​ }

​ 请求返回

image-20230727115712187

​ 我们刷新一下网页端,查看当前浏览器

image-20230727115852900

4 文件上传功能

​ 请求 方式 POST 请求url http://127.0.0.1:5000/upload

headhers 设置 Content-Type= multipart/form-data

image-20230801094048526

body 请求参数 使用form-data, form 表单1 参数file 类型选择 file

image-20230801094345113

image-20230801094413288

请求返回

image-20230801094552650

5 发送消息并附带附件

请求 方式 POST 请求url http://127.0.0.1:5000/sendattachment

headhers 设置 Content-Type= multipart/form-data

image-20230801094751415

body 请求参数 使用form-data, form 表单三个参数 ,conversation_id,prompt,file 其中 前面2个 文件类型txt,最后一个文件类型选择file

image-20230801094956606

请求返回

image-20230801095053897

刷新网页查看页面结果。

image-20230801095236798

视频信息:https://foul-maxilla-075.notion.site/claude2-a81a9488e7e943f588f4fe80a0a2fce0

代理相关配置说明:

env 配置文件增加

HTTP_PROXY="http://127.0.0.1:10809"
HTTPS_PROXY="https://127.0.0.1:10809"
#SOCKS5_PROXY="socks5://127.0.0.1:10808"
ISPROXY=True

如果启用代理模式访问,ISPROXY设置True.另外 配置HTTP_PROXY、HTTPS_PROXY 、SOCKS5_PROXY 代理。二者可选。如果不设置代理可以将ISPROXY 设置为空或者 ISPROXY=False HTTP_PROXY、HTTPS_PROXY 、SOCKS5_PROXY 可以设置为空。

微信机器人功能:

增加claude_wechatbot.py 实现微信机器人调用claude2创建聊天信息、发送聊天信息、获取历史聊天对话功能。

Screenshot_20230813_213239_com.tencent.mm

主要代码简单介绍

itchat.instance.receivingRetryCount = 600  # 修改断线超时时间
itchat.auto_login(enableCmdQR=2,hotReload=False,qrCallback=qrCallback)
user_id = itchat.instance.storageClass.userName
name = itchat.instance.storageClass.nickName
logger.info("Wechat login success, user_id: {}, nickname: {}".format(user_id, name))
#itchat.send('Hello, filehelper', toUserName='wwzhouhui')
# msg="天气预报"
# itchat.send('%s' % tuling(msg),toUserName='filehelper')
itchat.run()

以上代码执行启动一个微信登陆监听画面,在系统控制台中会出现二维码。用微信扫描二维码,这样登陆访问的微信就具备机器人功能。

image-20230813214437724

# text_reply msg_files可以处理好友之间的聊天回复
@itchat.msg_register([TEXT,MAP,CARD,NOTE,SHARING])
def text_reply(msg):
    #itchat.send('%s' % get_chat_history(msg['Text']),msg['FromUserName'])
     itchat.send('%s' % send_message_judge(msg['Text']),msg['FromUserName'])

​ 以上代码实现监听claude2 回复消息监听转发到微信中,通过微信机器人发送给问问题的人。

def create_chat(msg):
    data = {'prompt': msg}
    prompt = data['prompt']

    cookie = get_cookie()
    isproxy= get_proxy()
    client = Client(cookie,isproxy)
    conversation = client.create_new_chat()
    conversation_id = conversation['uuid']
    response = client.send_message(prompt, conversation_id)
    logger.info("create_chat {} "+str(response))
    answer = response
    logger.info("create_chat {} answer".format(answer))
    resultdata = {'uuid': conversation_id,'answer':answer}
    return resultdata
# 发送消息
def send_message(msg,conversation_id):
    data = {'prompt': msg}
    prompt = data['prompt']
    cookie = get_cookie()
    isproxy= get_proxy()
    client = Client(cookie,isproxy)
    response = client.send_message(prompt, conversation_id)
    logger.info("send_message {} "+str(response))
    answer = response
    logger.info("send_message {} answer".format(answer))
    return answer


Conversation_id = ""
# 发送消息判断 如果是有Conversation_id 有值说明已经创建过群聊,直接发送消息,如果没有消息创建消息
def send_message_judge(msg):
    global Conversation_id
    if Conversation_id != "":
        return send_message(msg,Conversation_id)
    else:
        result= create_chat(msg)
        Conversation_id = result['uuid']
        return result['answer']

​ 调用claude2api接口实现消息的创建和消息的发送给claude2,输入提示词实现调用claude2获取回答问题消息。

企业微信机器人功能:

增加了ImApp.py 通过工厂方法构建IM 功能目前包含企业微信和微信功能目前测试通过了claude2创建聊天信息、发送聊天信息发生消息给企业微信。

企业微信需要回调函数,所以程序运行需要有公网访问地址,最好需要固定IP

image-20230823174713575

详细测试可以看视频https://foul-maxilla-075.notion.site/claude2-3ed6c06da96249a1ad106d1ce987aa6c

qq机器人功能:

增加qqchat_channel.py 频道通过反向代理socket整合go-cqhttp实现了QQ调用claude2接口功能

image-20230828224651203

飞书机器人功能:

image-20230902173417020

钉钉机器人功能

​ 详细见钉钉配置

微信公众号功能

详细见微信公众号配置

  • version 0.0.1: 基础功能包括创建会话、聊天、获取历史会话,清理历史记录等功能
  • version 0.0.2: 修改文件读取功能,增加了文件上传功能和发送消息并附带附件功能;增加了项目演示视频信息。
  • version 0.0.3:增加docker容器运行,运行cookie传参数使用,避免程序写死;增加replit 部署
  • version 0.0.4:修改claude_api.py接口代码,考虑国内网络环境以及容器部署没办法访问claude,增加代理proxy访问方式
  • version 0.0.5:修改claude_api.py接口代码对于send_message返回数据解析做了相应修改;增加微信创建聊天、发送聊天、获取历史聊天信息功能;
  • version 0.0.6:修复We are unable to serve your request 问题,替换成curl_cffi 模拟浏览器模式,增加testcurl_cffi.py 测试代码
  • version 0.0.7:新增加IM功能工厂代码,目前完成企业微信整合claude_api.py接口功能,后面重写微信功能
  • version 0.0.8:新增QQ整合claude_api.py接口功能,可以通过QQ执行claude2接口调用了。实现qq使用到了go-cqhttp
  • version 0.0.9:修改了claude_ai_bot.py代码微信、QQ发送消息每次都创建消息的BUG. 增加了钉钉IM功能。
  • version 0.10.0:新增加了飞书整合claude_api.py接口功能,开源通过飞书执行claude2接口调用了。
  • version 0.11.0:修改了dingtalk_channel.py代码,完成了钉钉整合claude2接口调用,并完成了测试。
  • version 0.11.1:修改了telegram_channel.py代码,未测试。
  • version 0.11.2:应网友要求增加了微信技术交流群。
  • version 0.12.0:修改钉钉IM功能并完成测试,新增加微信公众号调用claude_api.py接口功能。
  • version 0.12.2:更新claude_api.py 代码修改了文件上传增加doc 和pdf 文件上传解析功能。
  • version 0.12.3:增加testsend_messagestream.py 实现stream输出。

视频演示地址:

第一节 :基础功能包括创建会话、聊天、获取历史会话

哔哩哔哩:https://www.bilibili.com/video/BV1Cz4y1x7BV/

YouTube:https://www.youtube.com/watch?v=e-ssvXw9Di8&t=49s

西瓜视频:https://www.ixigua.com/7260833345888584249?is_new_connect=0&is_new_user=0

第二节 :文件上传功能和发送消息并附带附件功能,支持docker容器部署

哔哩哔哩:https://www.bilibili.com/video/BV1KN411h7Hm/

YouTube:https://www.youtube.com/watch?v=_uqHbZjoV14&t=40s

西瓜视频:https://www.ixigua.com/7262393347132621352

第三节 :支持微信聊天功能,实现微信创建聊天、发送聊天、获取历史聊天信息功能

哔哩哔哩:https://www.bilibili.com/video/BV1f8411R7Aj

YouTube: https://www.youtube.com/watch?v=_l0yE2Kgm1g&t=40s

西瓜视频:https://www.ixigua.com/7266855523801268772

第四节 :整合微信聊天功能,支持企业微信聊天功能 实现微信创建聊天、发送聊天、信息功能

哔哩哔哩:https://www.bilibili.com/video/BV1LP411W7tN

YouTube: https://www.youtube.com/watch?v=aTZvQcO5Ou8&t=62s

西瓜视频:https://www.toutiao.com/video/7271532310493659683

第五节 :整合QQ聊天,飞书功能,支持企QQ、飞书聊天功能 实现QQ、飞书创建聊天、发送聊天、信息功能

哔哩哔哩:https://www.bilibili.com/video/BV19F41167sD

YouTube:https://www.youtube.com/watch?v=6rJvyaWJgYE

西瓜视频:https://www.ixigua.com/7274261124952883723

第六节 :整合钉钉,微信公众号功能,支持钉钉、微信公众号聊天功能 实现钉钉、微信公众号创建聊天、发送聊天、信息功能

哔哩哔哩:https://www.bilibili.com/video/BV1g34y1K7cE

YouTube:https://www.youtube.com/watch?v=Kly9ip5Fims

西瓜视频:https://www.ixigua.com/7266855523801268772

🎉 致谢

感谢以下项目对本项目提供的有力支持:

  1. Claude-API

    提供claude2 网页端逆向接口

  2. chatgpt-on-wechat

    提供微信、企业微信功能整合

  3. go-cqhttp

    提供QQ功能

问题反馈

如有问题,请在GitHub Issue中提交,在提交问题之前,请先查阅以往的issue是否能解决你的问题。

常见问题汇总

  1. 请求无权限

    image-20230811130335065

此类问题是当前访问的地区和国家不能访问https://claude.ai 导致的。类似前端页面返回错误地址信息

可以检查自己IP 地址 使用这个网站https://ipleak.net/ 测试

image-20230811132845703

以上ip显示是荷兰不是英国和美国这样导致访问地址受限。

image-20230811130718423

image-20230811131419471

  1. uuid 返回不了值

    代码claude_api.py get_organization_id 方法中出错

     response = self.send_request("GET",url,headers=headers)
            if response.status_code == 200:
                res = json.loads(response.text)
                uuid = res[0]['uuid']
                return uuid
            else:
                print(f"Error: {response.status_code} - {response.text}")
    

    ​ 返回code 200 但是程序解析 uuid = res[0]['uuid'] 返回报错。

    这是因为和问题1 类似权限问题导致网站重定向到错误页面 不能返回正确的 json 数字,代码在解析json代码不严谨返回解析报错。

    可以通过网页端访问https://claude.ai/api/organizations

    image-20230811131542303

​ 返回带有uuid的 json 返回值,说明网络情况是允许访问的。

  1. 发任何消息回复: {"error": {"type": "permission_error", "message": "We are unable to serve your request"}}

    在requirements.txt 增加urllib3和curl_cffi 2个依赖。修改了curl_cffi 模拟浏览器模式

    详细测试看这个视频https://foul-maxilla-075.notion.site/testcurl_cff-We-are-unable-to-serve-your-request-f5445d3f8dc040be8ee94a1a19ad923a

技术交流群

claude2-pyapi's People

Contributors

wwwzhouhui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

claude2-pyapi's Issues

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Traceback (most recent call last):
File "C:\Python311\Lib\runpy.py", line 198, in _run_module_as_main
return _run_code(code, main_globals, None,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\runpy.py", line 88, in run_code
exec(code, run_globals)
File "c:\Users\Administrator.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy_main
.py", line 39, in
cli.main()
File "c:\Users\Administrator.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\Administrator.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 284, in run_file
runpy.run_path(target, run_name="main")
File "c:\Users\Administrator.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 320, in run_path
code, fname = _get_code_from_file(run_name, path_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Administrator.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 294, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Desktop\yuni_dev\test\claudeapi1.py", line 4
claude_cookie = "C:\Users\Administrator\Desktop\yuni_dev\test\claude_cookies.json"

         ^

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

发现Chat里面background_tasks.add_task(client.send_message, prompt, conversation_id) 这里会报错,就是说send_message函数出现了报错

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "D:\miniconda3\envs\py310\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 435, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "D:\miniconda3\envs\py310\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\fastapi\applications.py", line 290, in __call__
    await super().__call__(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\applications.py", line 122, in __call__
    await self.middleware_stack(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\middleware\cors.py", line 83, in __call__
    await self.app(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
    raise exc
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "D:\miniconda3\envs\py310\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__
    raise e
  File "D:\miniconda3\envs\py310\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "D:\miniconda3\envs\py310\lib\site-packages\starlette\routing.py", line 66, in app
    response = await func(request)
  File "D:\miniconda3\envs\py310\lib\site-packages\fastapi\routing.py", line 241, in app
    raw_response = await run_endpoint_function(
  File "D:\miniconda3\envs\py310\lib\site-packages\fastapi\routing.py", line 167, in run_endpoint_function
    return await dependant.call(**values)
  File "c:\Users\TD\Desktop\python\LC server\APP\fastapi\main.py", line 150, in create_chat
    return client.send_message(prompt, conversation_id)
  File "c:\Users\TD\Desktop\python\LC server\APP\fastapi\claude_api.py", line 179, in send_message
    data = json.loads(json_str)
  File "D:\miniconda3\envs\py310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "D:\miniconda3\envs\py310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\miniconda3\envs\py310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

请问有人遇到过吗

Failed to perform, ErrCode: 23, Reason: 'Failure writing output to destination'. This may be a libcurl error, See https://curl.se/libcurl/c/libcurl-errors.html first for more details.

    def send_message(self, prompt, conversation_id, attachment=None):
        # ......
        buffer = BytesIO()
        c = Curl()
        headers_list = [f"{k}: {v}".encode() for k, v in headers.items()]

        def stream_callback(data):
            json_str = data.decode('utf-8')
            decoded_data = re.sub('\n+', '\n', json_str).strip()
            data_strings = decoded_data.split('\n')
            for data_string in data_strings:
                json_str = data_string[6:].strip()
                _data = json.loads(json_str)
                if 'completion' in _data:
                    buffer.write(str(_data['completion']).encode('utf-8'))
                    print(_data['completion'], end="")

        c.setopt(CurlOpt.URL, b'https://claude.ai/api/append_message')
        c.setopt(CurlOpt.WRITEFUNCTION, stream_callback)
        c.setopt(CurlOpt.HTTPHEADER, headers_list)
        c.setopt(CurlOpt.POSTFIELDS, payload)
        c.impersonate("chrome110")
        c.perform()
        c.close()
        body = buffer.getvalue()
        print(body.decode())
        return body

报错如下

    response = claude.send_message(user_input, conversation_id)
  File "E:\0nlp\split\Claude-API-main\claude-api\claude_api.py", line 181, in send_message
    c.perform()
  File "E:\0nlp\split\Claude-API-main\venv\lib\site-packages\curl_cffi\curl.py", line 251, in perform
    self._check_error(ret, action="perform")
  File "E:\0nlp\split\Claude-API-main\venv\lib\site-packages\curl_cffi\curl.py", line 106, in _check_error
    raise error
curl_cffi.curl.CurlError: Failed to perform, ErrCode: 23, Reason: 'Failure writing output to destination'. This may be a libcurl error, See https://curl.se/libcurl/c/libcurl-errors.html first for more details.

uuid 获取失败

File "e:\人工智能\claude\Claude2-PyAPI-master\Claude2-PyAPI-master\claude_api.py", line 34, in get_organization_id
uuid = res[0]['uuid']
KeyError: 0

HTTP/2 stream 1 was not closed cleanly before end of the underlying stream

带附件请求总是会遇到这个问题,不带附件偶尔遇到,请问有没有解决方案
Traceback (most recent call last):

File ~\anaconda3\envs\compe\lib\site-packages\curl_cffi\requests\session.py:436 in request
c.perform()

File ~\anaconda3\envs\compe\lib\site-packages\curl_cffi\curl.py:191 in perform
self._check_error(ret, action="perform")

File ~\anaconda3\envs\compe\lib\site-packages\curl_cffi\curl.py:84 in _check_error
raise error

CurlError: Failed to perform, ErrCode: 92, Reason: 'HTTP/2 stream 1 was not closed cleanly before end of the underlying stream'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File ~\anaconda3\envs\compe\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)

File e:\repositories\claude2\test.py:49
response = claude_api.send_message(prompt, conversation_id)

File E:\Repositories\claude2\Claude2-PyAPI\claude_api.py:146 in send_message
response = self.send_request("POST",url,headers=headers, data=payload, stream=True)

File E:\Repositories\claude2\Claude2-PyAPI\claude_api.py:344 in send_request
return requests.request(method, url, headers=headers, data=data, files=files, params=params,impersonate="chrome110",timeout=500)

File ~\anaconda3\envs\compe\lib\site-packages\curl_cffi\requests_init_.py:46 in request
return s.request(

File ~\anaconda3\envs\compe\lib\site-packages\curl_cffi\requests\session.py:438 in request
raise RequestsError(e)

RequestsError: Failed to perform, ErrCode: 92, Reason: 'HTTP/2 stream 1 was not closed cleanly before end of the underlying stream'

raise RequestsError(str(e), e.code, rsp) from e curl_cffi.requests.errors.RequestsError: Failed to perform, ErrCode: 7, Reason: 'Failed to connect to 127.0.0.1 port 10808 after 2026 ms: Connection refused'. This may be a libcurl error, See https://curl.se/libcurl/c/libcurl-errors.html first for more details.

raise RequestsError(str(e), e.code, rsp) from e
curl_cffi.requests.errors.RequestsError: Failed to perform, ErrCode: 7, Reason: 'Failed to connect to 127.0.0.1 port 10808 after 2026 ms: Connection refused'. This may be a libcurl error, See https://curl.se/libcurl/c/libcurl-errors.html first for more details.

企业微信应用发送消息报错

ImApp.py运行后发送消息报错如下

[2023-09-04 04:16:36,824] ERROR in app: Exception on /wechat [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 203, in _new_conn
    sock = connection.create_connection(
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    raise err
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 73, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 776, in urlopen
    self._prepare_proxy(conn)
  File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 1041, in _prepare_proxy
    conn.connect()
  File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 611, in connect
    self.sock = sock = self._new_conn()
  File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 218, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f105b7f8280>: Failed to establish a new connection: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

urllib3.exceptions.ProxyError: ('Unable to connect to proxy', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f105b7f8280>: Failed to establish a new connection: [Errno 111] Connection refused'))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/requests/adapters.py", line 486, in send
    resp = conn.urlopen(
  File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 844, in urlopen
    retries = retries.increment(
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/retry.py", line 515, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='qyapi.weixin.qq.com', port=443): Max retries exceeded with url: /cgi-bin/message/send?access_token=1000005 (Caused by ProxyError('Unable to connect to proxy', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f105b7f8280>: Failed to establish a new connection: [Errno 111] Connection refused')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/claude/channel/wechatcom/wechatenterprise_channel.py", line 25, in handler_msg
    return WechatEnterpriseChannel().handle()
  File "/home/claude/channel/wechatcom/wechatenterprise_channel.py", line 89, in handle
    self.client.message.send_text(self.AppId,msg.source,reply)
  File "/usr/local/lib/python3.10/site-packages/wechatpy/enterprise/client/api/message.py", line 62, in send_text
    return self.send(
  File "/usr/local/lib/python3.10/site-packages/wechatpy/enterprise/client/api/message.py", line 58, in send
    return self._post('message/send', data=data)
  File "/usr/local/lib/python3.10/site-packages/wechatpy/client/api/base.py", line 19, in _post
    return self._client.post(url, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/wechatpy/client/base.py", line 182, in post
    return self._request(
  File "/usr/local/lib/python3.10/site-packages/wechatpy/client/base.py", line 85, in _request
    res = self._http.request(
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/requests/adapters.py", line 513, in send
    raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='qyapi.weixin.qq.com', port=443): Max retries exceeded with url: /cgi-bin/message/send?access_token=1000005 (Caused by ProxyError('Unable to connect to proxy', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f105b7f8280>: Failed to establish a new connection: [Errno 111] Connection refused')))
183.47.98.227 - - [04/Sep/2023 04:16:36] "POST /wechat?msg_signature=0c10c5427f385f5346b577e89f3c350fc2706cbd&timestamp=1693800996&nonce=1693700453 HTTP/1.1" 500 -
No ID found. Creating new ID
[ERROR][2023-09-04 04:16:36][wechatenterprise_channel.py:57] - You are using http proxy WRONG, the prefix should be 'http://' not 'https://',see: https://github.com/yifeikong/curl_cffi/issues/6
Traceback (most recent call last):
  File "/home/claude/channel/wechatcom/wechatenterprise_channel.py", line 53, in _do_send
    reply_text = super().build_reply_content(query, context)
  File "/home/claude/channel/channel.py", line 31, in build_reply_content
    return Bridge().fetch_reply_content(query, context)
  File "/home/claude/bridge/bridge.py", line 11, in fetch_reply_content
    return bot_factory.create_bot("claudeAI").reply(query, context)
  File "/home/claude/bot/claude/claude_ai_bot.py", line 19, in reply
    result= self.create_chat(query,Conversation_id)
  File "/home/claude/bot/claude/claude_ai_bot.py", line 30, in create_chat
    client = Client(self.cookie,self.isproxy)
  File "/home/claude/claude_api.py", line 18, in __init__
    self.organization_id =self.get_organization_id()
  File "/home/claude/claude_api.py", line 51, in get_organization_id
    response = self.send_request("GET",url,headers=headers)
  File "/home/claude/claude_api.py", line 325, in send_request
    return requests.request(method, url, headers=headers, data=data, files=files, params=params,impersonate="chrome110",proxies=self.proxies,timeout=500)
  File "/usr/local/lib/python3.10/site-packages/curl_cffi/requests/__init__.py", line 46, in request
    return s.request(
  File "/usr/local/lib/python3.10/site-packages/curl_cffi/requests/session.py", line 407, in request
    req, buffer, header_buffer = self._set_curl_options(
  File "/usr/local/lib/python3.10/site-packages/curl_cffi/requests/session.py", line 267, in _set_curl_options
    raise RequestsError(
curl_cffi.requests.errors.RequestsError: You are using http proxy WRONG, the prefix should be 'http://' not 'https://',see: https://github.com/yifeikong/curl_cffi/issues/6

curl_cffi.curl: TypeError: initializer for ctype 'char *' must be a bytes or list or tuple, not str

from Claude2_PyAPI.claude_api import Client
COOKIE=None
with root.joinpath("claude_cookie").open('r',encoding='utf8') as ck:
    COOKIE=ck.read().strip()
chat_uuid=[
    'ec4adbca-c7a0-4935-8a29-494c803a5793',
    'c92660e3-7f0f-4d3c-a9eb-6e7bd63ee4f7',
    '7ca6b8f1-aeb9-4ea3-a278-4806f6a2fb35',
    '08aa6cfd-8bb4-47e0-932a-9256512d2517',
    '26d967a0-ff0d-4b63-bd62-a38aa24748eb'
]
claude_api=Client(COOKIE)

prompt="Hello Claude! How are you?"

conversation_id = "<conversation_id>"
conversation_id = chat_uuid[0]
response = claude_api.send_message(prompt, conversation_id)
print(response)

简单想尝试下但报错:
Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: _run_module_as_main)
initializer for ctype 'char *' must be a bytes or list or tuple, not str
File "C:\Users\admin\AppData\Roaming\Python\Python310\site-packages\curl_cffi\curl.py", line 174, in setopt
self._headers = lib.curl_slist_append(self._headers, header)
File "D:\models\datasets\claude2(fetch)\Claude2_PyAPI\claude_api.py", line 179, in send_message
c.setopt(CurlOpt.HTTPHEADER, str(headers))
File "D:\models\datasets\claude2(fetch)\claude2.py", line 26, in
response = claude_api.send_message(prompt, conversation_id)
File "C:\Program Files\Python310\Lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Program Files\Python310\Lib\runpy.py", line 196, in _run_module_as_main (Current frame)
return _run_code(code, main_globals, None,
TypeError: initializer for ctype 'char *' must be a bytes or list or tuple, not str

send_message失败

作者大大你好!我在测试机上部署claude_flask项目,目前可以正常使用history接口获取历史提问数据。但在请求chat/时请求被挂起。
直接本地调用send_message方法会报 curl的char *不能为str。
由于UUID已经是能正常获取,使用的又是同个header,这让我找不到切入点。
我尝试在curl模块代码中捕获并跳过这些出错的参数,但这显然是无法正常运行的。
再次尝试修改claude_api下send_message的请求方法为requests.post,此时返回的respones为:
{'error': {'type': 'permission_error', 'message': 'We are unable to serve your request'}}
是否必须严格使用代码中CURL()的请求方式,抑或是我缺少了某些参数?

JSONDecodeError

Expecting value: line 1 column 1 (char 0)
StopIteration: 0

During handling of the above exception, another exception occurred:

File "C:\Users\Administrator\Desktop\yuni_dev\yuniverse\Claude2-PyAPI-master\claude_api.py", line 152, in send_message
data = json.loads(json_str)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Desktop\yuni_dev\yuniverse\Claude2-PyAPI-master\claude_api.py", line 345, in
response = claude_api.send_message(prompt, conversation_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

docker 部署问题

image
我已经打包好了镜像,但是我启动这个镜像的时候启动失败

Endpoint disabled

Sending any message will result in:
{"error":{"type":"permission_error","message":"Endpoint disabled"}}

Does anyone have this problem?

requests.exceptions.ProxyError

requests.exceptions.ProxyError: HTTPSConnectionPool(host='claude.ai', port=443): Max retries exceeded with url: /api/organizations (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000279EFE8C1C8>: Failed to establish a new connection: [WinError 10061]
由于目标计算机积极拒绝,无法连接。')))

ModuleNotFoundError: No module named 'exceptions'

Traceback (most recent call last):
File "e:\projects\Claude2-PyAPI\bot.py", line 2, in
from claude_api import Client
File "e:\projects\Claude2-PyAPI\claude_api.py", line 9, in
import docx
File "E:\prgramfiles\python3\lib\site-packages\docx.py", line 30, in
from exceptions import PendingDeprecationWarning
ModuleNotFoundError: No module named 'exceptions'是什么问题

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.