ashwinpathi / claude-api-py Goto Github PK
View Code? Open in Web Editor NEWUnofficial Python API for Anthropic's Claude LLM
Home Page: https://pypi.org/project/claude-api-py/
License: MIT License
Unofficial Python API for Anthropic's Claude LLM
Home Page: https://pypi.org/project/claude-api-py/
License: MIT License
Dear author, is it possible to implement asynchronously if I have multiple Sessionkeys? It seems that he is limited by the official single dialogue, can you give me some suggestions to increase his efficiency? Thank you ~
I've been using this service for the past 2 second and the server has been constantly up, I'm not sure how to deal with this situation as it has been constantly affecting the food delivery experience. Please resolve the issue asap so I could watch the motorcycle youtube
Can you help to see if there is a mistake or what is the situation, the failure of her now @AshwinPathi
When I try to run response = claude_obj.send_message("How are you doing today!", conversation_uuid=conversation_uuid)
, it returns a normal response to me I'm doing well, thanks for asking! As an AI assistant without human emotions, XXX
However, when I try to run
attachment = claude_obj.get_attachment('test.txt')
response = claude_obj.send_message("Hi Claude, what does this attachment say?", attachments=[attachment],
conversation_uuid = conversation_uuid)
I randomly got errors: http.client.RemoteDisconnected: Remote end closed connection without response
and HTTP Error 500: Internal Server Error
.
Anyone could offer me a hand?
Thanks so much for this!
I got 'HTTP Error 403: Forbidden' when send message to claude, does Anthropic ban this way?
Thanks so much for this!
!pip install claude-api-py
!pip install sseclient-py
!pip install git+git://github.com/AshwinPathi/claude-api-py.git
from claude import claude_wrapper
from claude import claude_client
client = claude_client.ClaudeClient("my_Session_key")
organizations = client.get_organizations()
claude_obj = claude_wrapper.ClaudeWrapper(client)
attachment = claude_obj.get_attachment('train.txt')
response = claude_obj.send_message("Hi Claude, what does this attachment say?", attachments=[attachment],
conversation_uuid = conversation_uuid)
I can do it myself but it would be ideal if it will be in the repo
Brother, please add a feature to switch accounts. Because each account has a request limit. Thank You.
prompt = 'string hello world'
newchat = claude_obj.start_new_conversation("New Conversation", f"Hi Claude! {prompt}")
if newchat is not None:
// Doing something according to the concept
else:
// HTTP Error 429: Too Many Requests
// None
// Switch accounts
while trying to start new conv or send message code shows this error:
requests.exceptions.MissingSchema: Invalid URL '<http.client.HTTPResponse object at 0x0000022655E3E700>': No scheme supplied. Perhaps you meant https://<http.client.HTTPResponse object at 0x0000022655E3E700>?
title rename, org id functions work properly
[16-Aug-23 09:36:26:root:WARNING][claude_client.py:93 - send_message() ] Response from sending message is None.
Traceback (most recent call last):
File "C:/Users//Desktop/claude-api-py/example.py", line 114, in
main()
File "C:/Users//Desktop/claude-api-py/example.py", line 43, in main
assert new_convo_response is not None
AssertionError
HTTP Error 403: Forbidden
Hey Ashwin
Great effort. Would it be alright if I write an Medium post for this repo?
Thanks
I tried using the pypi installation of the module, but it gives me
Traceback (most recent call last):
File "/home/sami/backup/alvin-work/claude.py", line 2, in
from claude import claude_client
File "/home/sami/backup/alvin-work/claude.py", line 2, in
from claude import claude_client
ImportError: cannot import name 'claude_client' from partially initialized module 'claude' (most likely due to a circular import) (/home/sami/backup/alvin-work/claude.py)
The pypi installation worked fine.
if it's possible to add claude-2-100k model that would be very appreciated..
After downloading all requirements, I try to run example.py
.
However, it throws an error:
Traceback (most recent call last):
File "example.py", line 109, in <module>
main()
File "example.py", line 27, in main
organizations = client.get_organizations()
File "D:\AppData\miniconda3\envs\myclaude2\lib\site-packages\claude\claude_client.py", line 255, in get_organizations
return response.json()
File "D:\AppData\miniconda3\envs\myclaude2\lib\site-packages\claude\custom_requests.py", line 41, in json
return json.loads(self.data.decode("utf-8"))
File "D:\AppData\miniconda3\envs\myclaude2\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "D:\AppData\miniconda3\envs\myclaude2\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\AppData\miniconda3\envs\myclaude2\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 9 (char 9)
It seems that this error may be caused by my lack of organization?
Thanks for your reply!
e:/repositories/Claude_test2/example.py
Listing current conversations:
[{'created_at': '2023-07-18T12:31:00.542947+00:00',
'name': 'Hello greeting',
'summary': '',
'updated_at': '2023-07-18T12:31:02.300568+00:00',
'uuid': 'f66541ef-793d-48d8-b575-c2b9e6e27365'}]
Traceback (most recent call last):
File "e:\repositories\Claude_test2\example.py", line 94, in <module>
main()
File "e:\repositories\Claude_test2\example.py", line 39, in main
conversation_uuid = claude_obj.start_new_conversation("New Conversation", "Hi Claude!")
File "e:\repositories\Claude_test2\claude\claude_wrapper.py", line 80, in start_new_conversation
send_init_message_result = self._client.send_message(
File "e:\repositories\Claude_test2\claude\claude_client.py", line 58, in send_message
for elem in self._send_message(
File "e:\repositories\Claude_test2\claude\claude_client.py", line 241, in _send_message
for streamed_data_chunk in custom_requests.sse(
File "e:\repositories\Claude_test2\claude\custom_requests.py", line 68, in sse
client = sseclient.SSEClient(response)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\sseclient.py", line 48, in __init__
self._connect()
File "C:\Users\Ahmed\anaconda3\lib\site-packages\sseclient.py", line 56, in _connect
self.resp = requester.get(self.url, stream=True, **self.requests_kwargs)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\api.py", line 73, in get
return request("get", url, params=params, **kwargs)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\sessions.py", line 573, in request
prep = self.prepare_request(req)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\sessions.py", line 484, in prepare_request
p.prepare(
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\models.py", line 368, in prepare
self.prepare_url(url, params)
File "C:\Users\Ahmed\anaconda3\lib\site-packages\requests\models.py", line 439, in prepare_url
raise MissingSchema(
requests.exceptions.MissingSchema: Invalid URL '<http.client.HTTPResponse object at 0x0000019644DF8760>': No scheme supplied. Perhaps you meant http://<http.client.HTTPResponse object at 0x0000019644DF8760>?
I'm trying to run this code:
from claude import claude_client
from claude import claude_wrapper
SESSION_KEY = <MY_SESSION_KEY>
client = claude_client.ClaudeClient(SESSION_KEY)
organizations = client.get_organizations()
organizations
but I get this:
WARNING:root:Failed response object: Response(ok=False, data=b'', status_code=None, error='HTTP Error 403: Forbidden')
None
I don't really understand what the problem is.
Traceback (most recent call last):
File "/Users/bicaihua/PycharmProjects/Weibo/weibo-crawler/Claude_Copilot.py", line 109, in
main()
File "/Users/bicaihua/PycharmProjects/Weibo/weibo-crawler/Claude_Copilot.py", line 30, in main
claude_obj = claude_wrapper.ClaudeWrapper(client, organizations[0]['uuid']) # type: ignore
TypeError: 'NoneType' object is not subscriptable
error like above. how to solve this?
Dear author, I find the code seems to be invalid? The request is 500, but I use the browser to access normally, the account is normal, could you help me update
The following code is shown
def test_claude_stream(): SESSION_KEY = "" client = claude_client.ClaudeClient(SESSION_KEY) organizations = client.get_organizations() resp = client.send_message(organization_uuid=organizations[0]['uuid'], message="vuex usage?", stream=True, attachments=List[AttachmentType], conversation_uuid=Optional[str], timezone=constants.Timezone.LA, model=constants.Model.CLAUDE_2, ) print(resp.__next__())
The error is as follows:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\chat-claude.py", line 62, in
test_claude_stream()
File "C:\Users\Administrator\Desktop\chat-claude.py", line 56, in test_claude_stream
print(resp.next())
File "C:\Users\Administrator\PycharmProjects\pythonProject1\venv\lib\site-packages\claude\claude_client.py", line 289, in send_message
for streamed_data_chunk in custom_requests.sse(
File "C:\Users\Administrator\PycharmProjects\pythonProject1\venv\lib\site-packages\claude\custom_requests.py", line 198, in sse
encoded_request_body = json.dumps(request_body).encode()
File "D:\python3.9\lib\json_init.py", line 231, in dumps
return _default_encoder.encode(obj)
File "D:\python3.9\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\python3.9\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "D:\python3.9\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type _UnionGenericAlias is not JSON serializable
{'completion': '', 'stop_reason': 'stop_sequence', 'model': 'claude-2.0', 'stop': '\n\nHuman:', 'log_id': '21dd0513512255a6ee47a1dc3c7945aad0f13208b3d9b74f51d3c282c3068592', 'messageLimit': {'type': 'within_limit'}}
In code:
encoded_request_body = json.dumps(request_body).encode()
try:
response = urlopen(request, data=encoded_request_body)
client = sseclient.SSEClient(response)
for event in client.events():
yield event.data
except (HTTPError, URLError) as e:
logger.logger.info("SEE POST failed with error: %s", str(e))
print(e)
I got the following error:
{"error": {"type": "permission_error", "message": "We are unable to serve your request"}}
No idea why, just copy paste the access token.
I am repeating the process in example.py
. But it report with the error like this :
TypeError Traceback (most recent call last)
Cell In[3], line 117
112 time.sleep(1)
116 if __name__ == '__main__':
--> 117 main()
Cell In[3], line 32, in main()
29 print(organizations)
31 # Wraps the client api and organization into a single organization.
---> 32 claude_obj = claude_wrapper.ClaudeWrapper(client, organizations[0]['uuid']) # type: ignore
34 # We can list our existing conversations here.
35 conversations = claude_obj.get_conversations()
TypeError: 'NoneType' object is not subscriptable
I checked organization
object . It is None.
Hey! Stumbled upon this project, it looks really promising, and the code is very clean, thank you very much for building this!
I wanted to build support for file uploading. For this, I added this into claude_client.py
:
def convert_file(
self, organization_uuid: str, file_path: str
) -> Optional[JsonType]:
"""Uploads a file"""
CONVERT_DOCUMENT_API_ENDPOINT = "/api/convert_document"
request_body = {
"organization_uuid": organization_uuid,
"file": open(file_path, 'rb'),
}
header = {}
header.update(self._get_default_header())
header.update({"content-type": "multipart/form-data"})
response = custom_requests.post(
self._get_api_url(CONVERT_DOCUMENT_API_ENDPOINT),
headers=header,
request_body=request_body,
)
if not response.ok:
return None
return response.json()
However, this request fails due to the encoding in custom_requests.py#L53.
Could you please nudge me into the right direction, what I have to change/look further into? I've also noticed that your message endpoint do have support for attachments, but are passed an empty List every time. Any thoughts on how you'd like to have an message endpoint which supports files as well?
If you do not wish to have file uploads in your project, just close this issue, no worries.
Hello, I recently improved the existing solutions, by fixing header consistency, adding auto session gathering using Firefox login and selenium, and auto user agent retrieval along with timezone.
My unofficial version of the API does currently work like a charm, it supports chat creation/deletion/retrieval and messages with attachments (with all the supported file types). It also let you handle a MessageRateLimit exception that provides you with the amount of seconds to sleep before next rateReset.
Come have a try! Leave a ⭐ if you can : )
https://github.com/st1vms/unofficial-claude2-api
Originally posted by @st1vms in #21 (comment)
I see an option to create new conversation and in the second message upload a file. Can I upload a file in the a new conversation?
This part of the code sometimes goes wrong, looks like it's returning a null value, right? Can you help fix him? I'll look at the root of the problem @AshwinPathi
I am trying to use claude API to run some analysis in parallel. However, it seems like after using several times, it was blocked for too many attempts. Here I am using default model which is Claude3 sonnet model. Does anyone know if it will occur the same problem for Claude 1 or 2 ?
Also, when I loaded model for Claude 2 or Claude-instant . It reports error like this :
HTTP Error 403: Forbidden
My code look like this :
model = constants.Model.CLAUDE_2_P_0
response = claude_obj.send_message(message=prompt, conversation_uuid=conversation_uuid,model=model)
response
This code works for default.model but not for claude 2 and claude 1. Does anyone know how to load claude 2 or claude 1 ?
Thanks,
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.