Git Product home page Git Product logo

claude-api-py's Introduction

Unofficial Claude API For Python

The UNOFFICIAL free API for Anthropic's Claude LLM.

Background

Claude is Anthropic's LLM app (similar to ChatGPT). This library allows you to use the API (for free) and interact with it in your python projects.

Implemented actions:

The Unofficial Claude API is under active development. The following endpoints are usable in some capacity:

  • Getting organizations you're in
  • Getting conversations you're in
  • Starting a conversation
  • Sending a message and receiving a response
  • Delete a conversation
  • Create an attachment from a file
  • Send attachments
  • getting message history

Note that the api is synchronous.

TODO features

  • Tests
  • Fixing models OTHER than claude_2
  • asynchronous mode
  • Better caching
  • cleaner errors and passing these up to users

This project is under active development and is extremely unstable, so there are no guarantees it will work for you. If you find a bug or you think it should work in a scenario where it doesn't, file an issue.

Usage

Step 1

Install the library using the following:

pip install claude-api-py

If that doesn't work, you can install directly from this github repository:

pip install git+git://github.com/AshwinPathi/claude-api-py.git

There is one requirement as of now:

Step 2

Get a sessionKey from the Claude website. You will need this to start the bot. Ideally also have a user agent of the computer you use to access claude.

You can get this information by logging into https://claude.ai/chats and doing the following:

  1. open inspect element (f12 on chrome)
  2. On the top bar, go to the Application tab.
  3. Under Storage, go to Cookies.
  4. look for a cookie called https://claude.ai, click it.
  5. click the sessionKey field, and copy the session key down. It should begin with sk-ant-sid01...

Step 3

Use the bot. You can see an example at example.py.

Examples:

Importing the necessary libraries

# The ClaudeClient is the raw API that gives you access to all organization and conversation level API calls
# with a simple python interface. However, you have to pass organization_uuid and conversation_uuid everywhere, so
# its not ideal if you want a simple to use API.
from claude import claude_client

# The ClaudeWrapper takes in a claude client instance and allows you to use a single organization and conversation
# context. This allows you to use the API more ergonomically.
from claude import claude_wrapper

Create the client and wrapper

client = claude_client.ClaudeClient(SESSION_KEY)

organizations = client.get_organizations()
# You can omit passing in the organization uuid and the wrapper will assume
# you will use the first organization instead.
claude_obj = claude_wrapper.ClaudeWrapper(client, organization_uuid=organizations[0]['uuid'])

Starting a new conversation

new_conversation_data = claude_obj.start_new_conversation("New Conversation", "Hi Claude!")
conversation_uuid = new_conversation_data['uuid']
# You can get the response from the initial message you sent with:
initial_response = new_conversation_data['response']
# You can get the title of the new chat you created with this:
chat_title = new_conversation_data['title']

Send a message (passing in the client uuid)

conversation_uuid = claude_obj.get_conversations()[0]['uuid']
response = claude_obj.send_message("How are you doing today!", conversation_uuid=conversation_uuid)

Setting a conversation context and sending a message

conversation_uuid = claude_obj.get_conversations()[0]['uuid']
# This is so you don't have to constantly pass in conversation uuid on every call that requires it.
# anywhere that has an argument conversation_uuid=X can be omitted if you set the conversation context.
claude_obj.set_conversation_context(conversation_uuid)

response = claude_obj.send_message("How are you doing today!")
response = claude_obj.send_message("Who won the league of legends worlds 2022 finals?")

Sending an attachment

# This generates an attachment in the right format
attachment = claude_obj.get_attachment('example_attachment.txt')
response = claude_obj.send_message("Hi Claude, what does this attachment say?", attachments=[attachment],
                                    conversation_uuid = conversation_uuid)

Deleting a conversation

deleted = claude_obj.delete_conversation(conversation_uuid)

Deleting all conversations in an organization

failed_deletions = claude_obj.delete_all_conversations()
assert len(failed_deletions) == 0

Renaming a conversation

conversation = claude_obj.rename_conversation("New name", conversation_uuid = conversation_uuid)

Get conversation history

conversation_history = claude_obj.get_conversation_info(conversation_uuid = conversation_uuid)

Disclaimer

This library is for purely educational purposes and is UNOFFICIAL. I am not responsible if your account gets banned. If you would like to use the actual API, go to anthropic website.

claude-api-py's People

Contributors

ashwinpathi avatar eakubilo avatar ochen1 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

claude-api-py's Issues

HTTP Error 403: Forbidden

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.

Support for File Upload

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.

An error was reported during start_new_conversation()

[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

Server is up

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

Bug: We are unable to serve your request

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.

Error when using stream request

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

Writing a Blogpost

Hey Ashwin

Great effort. Would it be alright if I write an Medium post for this repo?

Thanks

Empty Response

Screenshot 2023-08-10 10 39 16
Is anyone else going through this, or is it just me? It's been 2 days, and I haven't an empty response.

I meet errors 'http.client.RemoteDisconnected: Remote end closed connection without response' when chat with attachments

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?

Hope to get your advice on the question

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 ~

schema error

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

json.decoder.JSONDecodeError: Expecting value: line 2 column 9

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!

using model other than claude3

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,

TypeError: 'NoneType' object is not subscriptable

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.

image

Partially initialized module

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.

HTTP Error 500: Internal Server Error when using file attachment

code am using on google collab for testing

!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)

error am getting

image

Error when running example.py

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>?

feature switch accounts

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

can't get organizations uuid info when I ran the example.py

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?

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.

          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)

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.