KoushikNavuluri / Claude-API

This project provides an unofficial API for Claude AI, allowing users to access and interact with Claude AI .
https://pypi.org/project/claude-api/
MIT License
725 stars 120 forks source link

Claude-March-Updated #97

Open KiRyuWen opened 5 months ago

KiRyuWen commented 5 months ago

In claude_api.py => send_message(self, prompt, conversation_id, attachment=None, timeout=500): 1. original: payload = json.dumps({ "completion": { "prompt": f"{prompt}", "timezone": "Asia/Kolkata", "model": "claude-3-opus-20240229" }, "organization_uuid": f"{self.organization_id}", "conversation_uuid": f"{conversation_id}", "text": f"{prompt}", "attachments": attachments })

change to

payload = json.dumps({ "prompt": f"{prompt}", "timezone": "Asia/Kolkata", "model": "claude-3-haiku-20240307", "attachments": attachments, "files":[] })

2. change original loop data_strings to following loop

for data_string in data_strings: if data_string.find('data:')==-1 or data_string == "event: completion" or data_string == "event: stop" or data_string == "ping": continue json_str = data_string[6:].strip() data = json.loads(json_str)

  if 'completion' in data:
    completions.append(data['completion'])

Feel free to let me know if you have any questions. If it works for you, please give me a blessing for upcoming interviews!

Luisrepi commented 5 months ago

@KiRyuWen It didn't work for me or maybe I didn't do it right, could you upload the entire file?

KiRyuWen commented 5 months ago

Sorry for late replying to you, @Luisrepi First, in claude_api.py add this line on the top of the file. import chardet

and replace the send_message function as follows.

def send_message(self, prompt, conversation_id, attachment=None,timeout=500):
    url = f"https://claude.ai/api/organizations/{self.organization_id}/chat_conversations/{conversation_id}/completion"

    # Upload attachment if provided
    attachments = []
    if attachment:
      attachment_response = self.upload_attachment(attachment)
      if attachment_response:
        attachments = [attachment_response]
      else:
        return {"Error: Invalid file format. Please try again."}

    # Ensure attachments is an empty list when no attachment is provided
    if not attachment:
      attachments = []

    # payload = json.dumps({
    #   "completion": {
    #     "prompt": f"{prompt}",
    #     "timezone": "Asia/Kolkata",
    #     "model": "claude-3-opus-20240229"
    #   },
    #   "organization_uuid": f"{self.organization_id}",
    #   "conversation_uuid": f"{conversation_id}",
    #   "text": f"{prompt}",
    #   "attachments": attachments
    # })
    payload = json.dumps({
      "prompt": f"{prompt}",
      "timezone": "Asia/Kolkata",
      # "model": "claude-3-haiku-20240307",
      "attachments": attachments,
      "files":[]
    })

    headers = {
      'User-Agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
      'Accept': 'text/event-stream, text/event-stream',
      'Accept-Language': 'zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3',
      'Referer': 'https://claude.ai/chats',
      'Content-Type': 'application/json',
      'Origin': 'https://claude.ai',
      'DNT': '1',
      'Connection': 'keep-alive',
      'Cookie': f'{self.cookie}',
      'Sec-Fetch-Dest': 'empty',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Site': 'same-origin',
      'TE': 'trailers'
    }

    response = requests.post( url, headers=headers, data=payload,impersonate="chrome110",timeout=500)

    result  = chardet.detect(response.content) #support every language
    decoded_data = response.content.decode(f"{result['encoding']}", errors="ignore")
    # print(decoded_data)
    decoded_data = re.sub('\n+', '\n', decoded_data).strip()
    data_strings = decoded_data.split('\n')
    completions = []

    answer = ''

    for data_string in data_strings:
      if data_string.find('data:')==-1 or data_string == "event: completion" or data_string == "event: stop" or data_string == "ping":
        continue
      json_str = data_string[6:].strip()
      data = json.loads(json_str)

      if 'completion' in data:
        completions.append(data['completion'])

    answer = ''.join(completions)

    # Returns answer
    return answer