st1vms/unofficial-claude-api

Unable to retrieve organization_id | create_chat request error

Opened this issue · 14 comments

when I try to automatically login using selenium, i get the following error (I have two profile at firefox btw, and I sign claude into both of them)

  python3 unofficial-claude-dir/unofficial-claude.py

Retrieving Claude session cookie from /home/keinvanity/.mozilla/firefox/gmpc627g.default-release

Unable to retrieve organization_id from profile: /home/keinvanity/.mozilla/firefox/gmpc627g.default-release
Check if this profile is logged into Claude!
Traceback (most recent call last):
  File "/home/keinvanity/Downloads/UnofficialClaude/unofficial-claude-dir/unofficial-claude.py", line 32, in <module>
    client = ClaudeAPIClient(session, model_name='claude-3-5-sonnet-20240620', timeout=240)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/keinvanity/Downloads/UnofficialClaude/claude/lib/python3.12/site-packages/claude_api/client.py", line 147, in __init__
    raise ValueError("Invalid SessionData argument!")
ValueError: Invalid SessionData argument!

when omitting selenium, and provide the organization id, and session key manually, I get this error instead

  python3 unofficial-claude-dir/unofficial-claude.py

Message limit hit, cannot create chat...

@kqvanity Can you please post the result of visiting https://claude.ai/api/organizations through logged Firefox profile?
Maybe it is related to your default organization being unavailable, and this could be a duplicate of #23, just to check...

As I see it, get_session_data failed to parse the organization uuid from that endpoint...And as a result it returned None which throwed the exception on ClaudeAPIClient. This usually means the json returned from /api/organizations was invalid...

post the result of visiting

[
  {
    "id": 14182401,
    "uuid": "552779e3-b45a-4d48-9e05-6d152ca782ea",
    "name": "Github",
    "settings": {
      "claude_console_privacy": "default_private",
      "allowed_invite_domains": null
    },
    "capabilities": [
      "api"
    ],
    "rate_limit_tier": "auto_api_evaluation",
    "billing_type": null,
    "free_credits_status": null,
    "data_retention": "default",
    "api_disabled_reason": "out_of_credits",
    "api_disabled_until": null,
    "billable_usage_paused_until": null,
    "raven_type": null,
    "created_at": "2024-06-21T17:03:47.830914Z",
    "updated_at": "2024-06-21T17:03:47.830914Z",
    "active_flags": []
  },
  {
    "id": 23162662,
    "uuid": "3675554f-5b05-4f44-881f-b66e28869268",
    "name": "solicitmind@gmail.com's Organization",
    "settings": {
      "claude_console_privacy": "default_private",
      "allowed_invite_domains": null
    },
    "capabilities": [
      "chat"
    ],
    "rate_limit_tier": "default_claude_ai",
    "billing_type": null,
    "free_credits_status": null,
    "data_retention": "default",
    "api_disabled_reason": null,
    "api_disabled_until": null,
    "billable_usage_paused_until": null,
    "raven_type": null,
    "created_at": "2024-09-29T09:24:20.496864Z",
    "updated_at": "2024-09-29T09:24:20.496864Z",
    "active_flags": []
  }
]

could be duplicate of

I did check it out before, but knowing that the 'solution' got merged, I thought that ought to be a different error

I did check it out before, but knowing that the 'solution' got merged, I thought that ought to be a different error

Did you retrieved this with the profile that's causing errors?
It seems you do also have the last organization set with capabilities chat.

I guess using get_session_data(organization_index=1) (or with 0) wouldn't change much of a thing tho...as the intended behaviour should look for the last entry in that json...but still it can't find the uuid in there...
I would need to inspect the json retrieved here

j = json_loads(pre.text)

If you could install this library from source and print the json on that line when the error occurs it would be very useful.

You can also inspect if selenium starts with a logged profile by turning off headless mode in this line:

opts = get_firefox_options(firefox_profile=profile, headless=True)

My first assumption would be that the profile is not logged...

@st1vms I keep changing those lines at the the virtual environment's dir at nvim venv/lib/python3.12/site-packages/claude_api/session.py , but no changes are visible!

@st1vms I keep changing those lines at the the virtual environment's dir at nvim venv/lib/python3.12/site-packages/claude_api/session.py , but no changes are visible!

I suggest you try outside virtual environment, by installing from source using

pip install -e .

with a terminal inside the source dir.

sorry. I had to let the script auto fetch the credentials with selenium for it to pick the changes I've made (instead of hardcoding them). Here's the output.

  python3 unofficial-claude.py

Retrieving Claude session cookie from /home/keinvanity/.mozilla/firefox/gmpc627g.default-release
pre {"type":"error","error":{"type":"permission_error","message":"Invalid authorization"}}
j {'type': 'error', 'error': {'type': 'permission_error', 'message': 'Invalid authorization'}}

Unable to retrieve organization_id from profile: /home/keinvanity/.mozilla/firefox/gmpc627g.default-release
Check if this profile is logged into Claude!
Traceback (most recent call last):
  File "/home/keinvanity/Downloads/claude-misc/unofficial-claude-dir/unofficial-claude.py", line 33, in <module>
    client = ClaudeAPIClient(session, model_name='claude-3-5-sonnet-20240620', timeout=240)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/keinvanity/Downloads/claude-misc/unofficial-claude-dir/venv/lib/python3.12/site-packages/claude_api/client.py", line 147, in __init__
    raise ValueError("Invalid SessionData argument!")
ValueError: Invalid SessionData argument!

It's also worth mentioning that selenium opens up firefox with old extensions of mine still being present! I can't persist firefox to inspect it.

Selenium basically loads another profile that doesn't have claude logged in. I don't know how to set which Firefox profile to load

Does it work when not giving any profile to get_session_data ?

Apart from double checking the profile path...
I don't know...do you have the latest geckodriver executable and selenium library installed? Maybe you need to upgrade them...

Doe it work when not giving any profile

I already tried to pass the values right away. I visited https://claude.ai/api/organizations. Copied the second UUID, request cookie starting with CH-prefers-color-sche and then hardcoded those values in the example.py file you've provided at the readme, only to be prompted with

Message limit hit, cannot create chat..

Doe it work when not giving any profile

I already tried to pass the values right away. I visited https://claude.ai/api/organizations. Copied the second UUID, request cookie starting with CH-prefers-color-sche and then hardcoded those values in the example.py file you've provided at the readme, only to be prompted with

Message limit hit, cannot create chat..

I'm sorry but I can't recreate the issue on my end.

Can you please take a look at the response in create_chat when giving all parameters manually (cookie, user_agent, organization_id)?
You should insert a print(response.content) in this line:

if response and response.status_code == 201:

That's the change I've made

        print(payload)
        print(headers)
        response = http_post(
            url,
            headers=headers,
            data=payload,
            proxies=self.__get_proxy(),
            timeout=self.timeout,
            impersonate="chrome110",
        )
        print(response.text)
        if response and response.status_code == 201:
            j = response.json()
            if j and "uuid" in j:
                return j["uuid"]
        return None

and that's the output

{"name":"","uuid":"ae0cc...............-719249bfd0a4"}
{'Host': 'claude.ai', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/json', 'Content-Length': '57', 'Referer': 'https://claude.ai/chats', 'Origin': 'https://claude.ai', 'DNT': '1', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'Connection': 'keep-alive', 'Cookie': 'CH-prefers-color-scheme=light; __ssid=a5addfdf8.......f8e1438aa80; lastActiveOrg=3675554f-5b.......-b66e28869268; activitySessionId=02850caa-ec.............8a-297805bbbccd; __stripe_mid=cad07f96-fc54-4c73-89b0-e2f239331fac1ff7ad; sessionKey=sk-ant-sid01...................27A', 'TE': 'trailers'}
{"type":"error","error":{"type":"invalid_request_error","message":"Input should be a valid dictionary o


Message limit hit, cannot create chat...

The error indicates a problem with the payload, but I can not recreate the bug on my end.

Maybe try with another account and see if it works.

I doubt they changed that endpoint...

I'll try to avoid selenium altogether. The organization ID i pass is the second UUID retrieved from https://claude.ai/api/organizations. How about the cookie. I basically open up claude.com, inspect the request, and copypaste the value of Cookie.

cookie_header_value = "CH-prefers-color-scheme=light; __ssid=a5addf..............7df8e1438aa80; lastActiveOrg=36.....-.......869268; __stripe_mid=cad07f96.....-........-....9331fac1ff7ad; sessionKey=sk-ant-sid01-wI.....................3PTgWxkSk3FpeQ-jIqAeAAA; activitySessionId=3a......5-0183-4ad9-9ccc.........uoM9ywZODlIGvbF...............UQ6fIkpHU.8WsBYu16KsdMA7VCn72_TWC_jr4xd3E.XPlCl7CYjJ5vsLig9.mM90vfP7bbVs9TJB1x12lOaa.QhA"
user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0"
# You can retrieve this string from /api/organizations endpoint
# If omitted or None it will be auto retrieved when instantiating ClaudeAPIClient
organization_id = "3675........-......68"
session: SessionData = SessionData(cookie_header_value, user_agent, organization_id)