這個非官方的 Python API 透過簡單的聊天訊息介面提供對 Anthropic 的 Claude AI 的對話功能的存取。
雖然沒有得到 Anthropic 的正式支持,但該庫可以啟用有趣的對話應用程式。
它允許:
提出有關各種主題的問題。克勞德可以談論時事、流行文化、運動等等。
獲得有關複雜主題的有用解釋。請克勞德用簡單的術語解釋概念和想法。
從長文本或文件產生摘要。只需將文件路徑作為附件提供給 Claude,即可獲得簡潔的摘要。
收到對開放式提示和想法的深思熟慮的回應。克勞德可以集思廣益,擴展概念,並進行哲學討論。
發送圖像並讓 Claude 為您分析。
pip install unofficial-claude-api
pip uninstall unofficial-claude-api
(滾動瀏覽此自述文件,您還會發現手動替代方案)
from sys import exit as sys_exit
from claude_api . client import (
ClaudeAPIClient ,
SendMessageResponse ,
)
from claude_api . session import SessionData , get_session_data
from claude_api . errors import ClaudeAPIError , MessageRateLimitError , OverloadError
# Wildcard import will also work the same as above
# from claude_api import *
# List of attachments filepaths, up to 5, max 10 MB each
FILEPATH_LIST = [
"test1.txt" ,
"test2.txt" ,
]
# This function will automatically retrieve a SessionData instance using selenium
# It will auto gather cookie session, user agent and organization ID.
# Omitting profile argument will use default Firefox profile
session : SessionData = get_session_data ()
# Initialize a client instance using a session
# Optionally change the requests timeout parameter to best fit your needs...default to 240 seconds.
client = ClaudeAPIClient ( session , timeout = 240 )
# Create a new chat and cache the chat_id
chat_id = client . create_chat ()
if not chat_id :
# This will not throw MessageRateLimitError
# But it still means that account has no more messages left.
print ( " n Message limit hit, cannot create chat..." )
sys_exit ( 1 )
try :
# Used for sending message with or without attachments
# Returns a SendMessageResponse instance
res : SendMessageResponse = client . send_message (
chat_id , "Hello!" , attachment_paths = FILEPATH_LIST
)
# Inspect answer
if res . answer :
print ( res . answer )
else :
# Inspect response status code and raw answer bytes
print ( f" n Error code { res . status_code } , raw_answer: { res . raw_answer } " )
except ClaudeAPIError as e :
# Identify the error
if isinstance ( e , MessageRateLimitError ):
# The exception will hold these informations about the rate limit:
print ( f" n Message limit hit, resets at { e . reset_date } " )
print ( f" n { e . sleep_sec } seconds left until -> { e . reset_timestamp } " )
elif isinstance ( e , OverloadError ):
print ( f" n Overloaded error: { e } " )
else :
print ( f" n Got unknown Claude error: { e } " )
finally :
# Perform chat deletion for cleanup
client . delete_chat ( chat_id )
# Get a list of all chats ids
all_chat_ids = client . get_all_chat_ids ()
# Delete all chats
for chat in all_chat_ids :
client . delete_chat ( chat )
# Or by using a shortcut utility
client . delete_all_chats ()
sys_exit ( 0 )
# A convenience method to access a specific chat conversation is
chat_data = client . get_chat_data ( chat_id )
chat_data
將與呼叫/api/organizations/{organization_id}/chat_conversations/{chat_id}
傳回的 JSON 字典相同
下面是這個 json 的範例:
{
"uuid" : " <ConversationUUID> " ,
"name" : " " ,
"summary" : " " ,
"model" : null ,
"created_at" : " 1997-12-25T13:33:33.959409+00:00 " ,
"updated_at" : " 1997-12-25T13:33:39.487561+00:00 " ,
"chat_messages" : [
{
"uuid" : " <MessageUUID> " ,
"text" : " Who is Bugs Bunny? " ,
"sender" : " human " ,
"index" : 0 ,
"created_at" : " 1997-12-25T13:33:39.487561+00:00 " ,
"updated_at" : " 1997-12-25T13:33:40.959409+00:00 " ,
"edited_at" : null ,
"chat_feedback" : null ,
"attachments" : []
},
{
"uuid" : " <MessageUUID> " ,
"text" : " <Claude response's text> " ,
"sender" : " assistant " ,
"index" : 1 ,
"created_at" : " 1997-12-25T13:33:40.959409+00:00 " ,
"updated_at" : " 1997-12-25T13:33:42.487561+00:00 " ,
"edited_at" : null ,
"chat_feedback" : null ,
"attachments" : []
}
]
}
如果您出於某種原因想要避免使用 selenium 進行自動會話收集,您只需為ClaudeAPIClient
建構函數手動建立一個SessionData
類,如下所示...
from claude_api . session import SessionData
cookie_header_value = "The entire Cookie header value string when you visit https://claude.ai/chats"
user_agent = "User agent to use, required"
# You can retrieve this string from /api/organizations endpoint
# If omitted or None it will be auto retrieved when instantiating ClaudeAPIClient
organization_id = "<org_uuid>"
session = SessionData ( cookie_header_value , user_agent , organization_id )
注意(僅支援沒有使用者/密碼身份驗證的代理程式)
如果您想為所有請求設定 HTTP 代理,請按照以下範例操作:
from claude_api . client import HTTPProxy , ClaudeAPIClient
from claude_api . session import SessionData
# Create HTTPProxy instance
http_proxy = HTTPProxy (
"the.proxy.ip.addr" , # Proxy IP
8080 , # Proxy port
use_ssl = False # Set to True if proxy uses HTTPS schema
)
session = SessionData (...)
# Give the proxy instance to ClaudeAPIClient constructor, along with session data.
client = ClaudeAPIClient ( session , proxy = http_proxy )
如果您想選擇 SOCKS 代理,流程是相同的,但您需要匯入SOCKSProxy
類,並使用版本號對其進行配置。
from claude_api . client import SOCKSProxy , ClaudeAPIClient
from claude_api . session import SessionData
# Create SOCKSProxy instance
socks_proxy = SOCKSProxy (
"the.proxy.ip.addr" , # Proxy IP
8080 , # Proxy port
version_num = 5 # Either 4 or 5, defaults to 4
)
session = SessionData (...)
# Give the proxy instance to ClaudeAPIClient constructor as usual
client = ClaudeAPIClient ( session , proxy = socks_proxy )
如果您想要變更使用的模型,或者您的帳戶無法遷移到最新模型,您可以覆寫ClaudeAPIClient
建構函數的model_name
字串參數,如下所示:
from claude_api . client import ClaudeAPIClient
from claude_api . session import SessionData
session = SessionData (...)
# Defaults to None (latest Claude model)
client = ClaudeAPIClient ( session , model_name = "claude-2.0" )
您可以從官方 API 文件中檢索model_name
字串
如問題 #23 所述,如果您在使用 Selenium 自動擷取SessionData
類別時遇到 403 錯誤,且您的帳戶有多個組織,您可能需要覆寫檢索到的預設組織。
預設情況下, get_session_data
從此處找到的結果陣列中檢索最後一個組織。您可以使用參數organization_index
覆蓋要取得的索引:
from claude_api . session import get_session_data
# Defaults to -1 (last entry)
session = get_session_data ( organization_index = - 1 )
使用該API過程中可能出現的一些常見錯誤:
錯誤 [400] (無法準備文件附件):
若要修復此錯誤,請將附件檔案的副檔名變更為 .txt 之類的內容,因為預設此 api 對於未知檔案副檔名將回退到 octet-stream,Claude 可能會拒絕檔案資料。
錯誤[403] :
*這個bug在0.2.2版本之後應該已經修復了*
當呼叫send_message
時,此 api 有時會傳回 403 status_code,當發生這種情況時,建議尋找以下內容:
檢查您的 IP 位置是否允許,應該在美國/英國,其他位置可能偶爾工作。
不要嘗試一遍又一遍地發送相同的提示/文件,而是等待一段時間,然後更改輸入。
該儲存庫提供了一個非官方 API,用於自動化 claude.ai 上的免費帳戶。請注意,該 API 並未得到 Anthropic 的認可、支援或維護。您自行決定使用它並承擔風險。 Anthropic 可能隨時對其官方產品或 API 進行更改,這可能會影響該非官方 API 的功能。我們不保證使用此 API 檢索的資訊和資料的準確性、可靠性或安全性。透過使用此儲存庫,您同意維護者對其使用可能造成的任何損壞、問題或後果不承擔任何責任。請務必參閱 Anthropic 的官方文件和使用條款。此專案由不隸屬於 Anthropic 的貢獻者獨立維護。
預先非常感謝任何想要捐贈的人:)