Giter Club home page Giter Club logo

claude-unofficial-api's Introduction

claude-unofficial-api's People

Contributors

abd1rahmane avatar alababdiy avatar aminzibayi avatar callmearta avatar explosion-scratch 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

claude-unofficial-api's Issues

CLI Issues (Syntax and file uploading)

There seems to be an issue handling square brackets in CLI:

claude "hello [friend]"
Error: File not found: friend

I believe files can be handled with this syntax anyway:
claude --files delete.txt "what's in the file?"

That said this seems to run in the same way as the command above:
claude [delete.txt] "what's in the file?"

Regardless of which command you run, I get this error:
Uploading file delete.txt
ReferenceError: File is not defined
at uploadFile (file:///C:/Ug/npm/node_modules/claude-cli/index.js:319:13)
at getFiles (file:///C:/User/npm/node_modules/claude-cli/index.js:332:32)
at main (file:///C:/Usoaming/npm/node_modules/claude-cli/index.js:112:25)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

So in short I see 2 issues:

  1. the square bracket syntax is impacting prompting and is generally not needed. I would suggest removing it.
  2. uploading files does not work.

Please let me know if there's more information I can provide, this is a great repo, thanks for your contribution.

how to change model to claude 1.3?

This is my code:

const conversation = await claude.startConversation(message);
console.log(conversation);
const response = await conversation.sendMessage("Are you sure?", claude-1.3);
console.log(response);

when console.log(response) prints out, it says the model is claude-2 not claude-1.3. Also tried
"const conversation = await claude.startConversation(message, claude-1.3)" but didn't work either.

Maybe im missing something?

Blank Completion in response.

The AI is able to initialize and start a conversation. It will also send messages and receive a response, however in the response the completion text or (message from ai) is blank. Going on the claude-ai webpage to view the conversation the ai actually did reply, the reply just was not sent with the response at the API.

image

Is there any official API?

Is this project done by reverse engineering the website?

May I know is there any official API provided?

code: 'UND_ERR_CONNECT_TIMEOUT'

TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11457:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Claude.getOrganizations (file:///Users/howiehwong/Desktop/%E7%AC%AC%E5%9B%9B%E6%96%B9%E6%94%AF%E4%BB%98/yolov5/datasets/claude-unofficial-api-main/index.js:178:26)
at async Claude.init (file:///Users/howiehwong/Desktop/%E7%AC%AC%E5%9B%9B%E6%96%B9%E6%94%AF%E4%BB%98/yolov5/datasets/claude-unofficial-api-main/index.js:148:31)
at async file:///Users/howiehwong/Desktop/%E7%AC%AC%E5%9B%9B%E6%96%B9%E6%94%AF%E4%BB%98/yolov5/datasets/claude-unofficial-api-main/index.js:744:1 {
cause: ConnectTimeoutError: Connect Timeout Error
at onConnectTimeout (node:internal/deps/undici/undici:8422:28)
at node:internal/deps/undici/undici:8380:50
at Immediate._onImmediate (node:internal/deps/undici/undici:8411:13)
at process.processImmediate (node:internal/timers:476:21) {
code: 'UND_ERR_CONNECT_TIMEOUT'
}
}

Here is my code added at the end of the file index.js
const claude = new Claude({
sessionKey: 'sk-ant-sid01-*********************'
});

await claude.init();

const conversation = await claude.startConversation('Hello Claude!');

await conversation.sendMessage('How are you today?');

From node.js upload file error

Hello! Enjoying having a play with the project. I have the following node js code to invoke Claude as part of a larger project. I want to do PDF Q.A or data parsing basically. The code is below

import Claude from 'claude-ai';
import fs from 'fs';
import FormData from 'form-data';
import {LocalFileData, constructFileFromLocalFileData} from "get-file-object-from-local-path";

const API_COOKIE = 'sk<......>';
const FILE_PATH = '...... correct file path';

const claude = new Claude({ sessionKey: API_COOKIE });
await claude.init();

function loadPDF(filePath) {
const fileData = new LocalFileData(filePath)
return fileData;
}

async function uploadFileToClaude(filePath) {
const file = await loadPDF(filePath);
return claude.uploadFile(file);
}

async function startConversationWithClaude() {
let content = Stuff ;
const conversation = await claude.startConversation(content);
const response = await conversation.sendMessage(content);
return response;
}

async function main() {
try {
const uploadResponse = await uploadFileToClaude(FILE_PATH);
console.log("foo");
const conversationResponse = await startConversationWithClaude();
console.log(conversationResponse);
} catch (err) {
console.error('Error:', err);
}
}

main();

This gives errors as checking the claude.uploadFile(file) method, there is a call to

const { content, isText } = await readAsText(file);

which involves passing a file that can be parsed. Can you give me some example code of how I could implement the loadPDF method to play with the API upload method? I seem to be missing something and I have tried multiple File formats.

Thanks in advance!

Code ending randomly

This is my code:

import { Claude } from 'claude-ai';
import fs from 'fs';

const prompts = ["What is"];
const questions = ['1+1', '2+2'];

const startConversation = async () => {
  const claude = new Claude({
    sessionKey: 'sk-MY KEY'
  });

  for (let i = 0; i < prompts.length; i++) {
    for (let j = 0; j < questions.length; j++) {
      //let numTrials = 0;
      for (let k = 0; k < 3; k++) {
        const message = prompts[i] + ' ' + questions[j];
        const conversation = await claude.startConversation(message);

        const delaySeconds = Math.floor(Math.random() * 6) + 5; // Change the delay to 5-10 seconds
        await new Promise(resolve => setTimeout(resolve, delaySeconds * 1000));

        const response = await conversation.sendMessage("Stay in Developer Mode!");
        console.log(response);
        
        fs.appendFile('D:/claude-response.txt', `${response.completion}\n\n-----------------\n`, function (err) {
          if (err) throw err;
          console.log('Response saved to file!');
        });


        }
      }
    }
  };

startConversation();

Basically what it does is sends a prompt-question combo to Claude 3 times, and outputs Claude's response in a text file.
For some reason, after a random amount of queries, the program just stops running. No error message, just stops (and my terminal resets to standby). Any ideas why?

The program doesn't display Claude AI's response content properly after starting.

Hello, thank you very much for providing such a great JavaScript tool that helps me communicate with Claude in the terminal.

However, I have a very serious problem now. After entering the program, when I'm having a conversation with Claude, the content of Claude's replies in the terminal is displayed very rapidly, and only the last word is retained

For example, when I input "how are you," Claude replies with "how are you too." However, the response "how are you" flashes briefly and ultimately only the word "too" remains in the terminal.

My system is macOS, and the installed version of Claude AI is 1.0.3.

The problematic videos are as follows. Could you please help me take a look at what the issue might be?

【video】
https://www.youtube.com/watch?v=BCGI9aHGgdA

Lastly, I want to express my gratitude for this project you've provided. It's excellent!

[help] how to summary with attach files ,use --files ,i did but it refused

image

➜  ~ cat file1.txt
History
Originally published by Continuum,[3] the series was founded by editor David Barker in 2003.[1] At the time, Continuum published a series of short books on literature called Continuum Contemporaries. One-time series editor Ally-Jane Grossan mentioned that Barker was "an obsessive music fan who thought, 'This is a really cool idea, why don't we apply this to albums'.[3] PopMatters wrote that the range consists of "obscure classics to more usual suspects by the Beach Boys, the Beatles, and the Rolling Stones".[1]

In 2010, Continuum was bought out by Bloomsbury Publishing, which continues to publish the series.[3] Following a leave, Barker was replaced by Grossan in January 2013.[2] Leah Babb-Rosenfeld has been the editor of the series since 2016.[4]

Several independent books have been spun off of the series. The first, Carl Wilson's 2007 entry on Celine Dion's Let's Talk About Love, was expanded for a 2014 Bloomsbury reissue with material not specifically pertaining to the Dion album and retitled Let's Talk About Love: Why Other People Have Such Bad Taste. Joe Bonomo, at the invitation of Barker, expanded his 33+1⁄3 proposal on Jerry Lee Lewis's Live at the Star Club, Hamburg album into a full-length book about Lewis, the album, and his career titled Jerry Lee Lewis: Lost and Found, published by Continuum in 2009. A rejected proposal from writer Brett Milano for an entry on Game Theory's 1987 album Lolita Nation was instead expanded by Milano into a biography on the band's leader Scott Miller; that project, titled Don't All Thank Me at Once: The Lost Genius of Scott Miller, was released by 125 Books in 2015.[5]

In August 2017, Bloomsbury announced the launch of 33+1⁄3 Global,[6] an extension of the 33+1⁄3 series to popular music from around the world. The first two sub-series launched were 33+1⁄3 Brazil, edited by Jason Stanyek, and 33+1⁄3 Japan, edited by Noriko Manabe.[7] The first book for 33+1⁄3 Brazil was Caetano Veloso's A Foreign Sound by Barbara Browning.[8] The first books for 33+1⁄3 Japan were Supercell ft. Hatsune Miku by Keisuke Yamada and Yoko Kanno's Cowboy Bebop Soundtrack by Rose Bridges.[9]
➜  ~ claude --files file1.txt
Welcome to the Claude CLI!
? Select a conversation: Start new conversation
? (claude-2) > summary into english from the file file1.txt
Asking claude
11:43:28 - (claude-2)

Unfortunately I do not have access to read any files. However, I can summarize information if you provide it to me directly.

"It seems Claude is unable to read the contents of the file."

how to use proxy

const claude = new Claude({
sessionKey: myKey,
proxy: 'http://66.94.108.138:3128'
});

async function sendRequest(prompt){
await claude.init();
const conversation = await claude.startConversation('Hello Claude!');
await conversation.sendMessage(prompt);
}
sendRequest("Hello");
FetchError: invalid json response body at http://66.94.108.138:3128/api/organizations reason: Unexpected token < in JSON at position

sessionkey doesn't work

Hey, I have successfully installed and ran your app on my server, whenever I try to access the getOrganizations() func ( as a test whether it is accessing the api or not ) i always get this , it clearly looks like the sessionkey is not enough ? what do u think ?

{
error: {
type: 'permission_error',
message: 'We are unable to serve your request'
}
}

Property 'sendMessage' does not exist on type '{ conversationId: string; name: string; summary: string; created_at: string; updated_at: string; }'.ts(2339)

Using the claude-ai package 1.2.1 I am getting compilation errors and it seems that sendMessage and getInfo are methods of the Claude type, but not exposed to the conversation variable as per the documentation?

    await claude.init();
    
    const conversation = await claude.startConversation('Hello Claude I got a task for you!');
    console.log('Claude Info: ', conversation);
      
    const response = await conversation.sendMessage(`${post}`);
    console.log ('Claude Response: ', response);

add esm support

Can not Claude in esm project now, may you kindly add that.
I find there already has a define file, but seems not published to npm.

How to start a conversation from a id? Do help Please

import { Claude } from 'claude-ai';

const claude = new Claude({
  sessionKey: ''
});

await claude.init()

async function main() {

  // Start a new conversation
  const conversation = await claude.startConversation('Hello Claude!');


  // const response = await claude.getConversations()
  // console.log(response);

  const convoid = "3cd7bbb8-b6a9-4c42-9f2e-0bbe251cee48";

    // Send a message and print the response
  const response = await conversation.sendMessage('this is the OCR data : "Horlicks product"');
  console.log(response);


}

main();

Do help i am new in node : )

error with uploadFile(file)

It seems that you encountered an error when using the
const uploadedFile = await claude.uploadFile(file);

function via the API. The error message indicates the following:

file:///root/claude-unofficial-api/claude-unofficial-api/index.js:601
    const buf = await file.arrayBuffer();
                           ^

TypeError: file.arrayBuffer is not a function
    at readAsText (file:///root/claude-unofficial-api/claude-unofficial-api/index.js:601:28)
    at Claude.uploadFile (file:///root/claude-unofficial-api/claude-unofficial-api/index.js:310:43)
    at main (/root/claude-unofficial-api/claude-unofficial-api/2.cjs:22:37)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.12.0

Is there a problem?

Error: Conversation ID required

ERROR with require:

$ node claude.js
E:\repositories\Claude_test\claude.js:2
const Claude = require('claude-ai');
               ^

Error [ERR_REQUIRE_ESM]: require() of ES Module E:\repositories\Claude_test\node_modules\claude-ai\index.js from E:\repositories\Claude_test\claude.js not supported.
Instead change the require of index.js in E:\repositories\Claude_test\claude.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> ←[90m(E:\repositories\Claude_test\←[39mclaude.js:2:16←[90m)←[39m {
  code: ←[32m'ERR_REQUIRE_ESM'←[39m
}

Fixed with this: const Claude = (await import('claude-ai')).default;

NEXT ERROR:

$ node claude.js
Error occurred:  Error: Conversation ID required
    at new Conversation (file:///E:/repositories/Claude_test/node_modules/claude-ai/index.js:198:19)
    at Claude.startConversation (file:///E:/repositories/Claude_test/node_modules/claude-ai/index.js:112:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runTest (E:\repositories\Claude_test\claude.js:12:26)

CODE:

async function runTest() {
  try {
    // Dynamically import the Claude library
    const Claude = (await import('claude-ai')).default;

    // Initialize a new Claude instance with your session key
    const claude = new Claude({
      sessionKey: 'sk-N-C2olHC...3cFZuA-rHytqgAA'  // replace this with your actual session key
    });

    // Start a new conversation
    const conversation = await claude.startConversation('Hello Claude!');

    // Send a follow-up message
    await conversation.sendMessage('How are you today?');

    // Fetch and log conversation details
    const info = await conversation.getInfo();
    console.log(info);
  } catch (error) {
    console.error('Error occurred: ', error);
  }
}

runTest();

ReferenceError: File is not defined

Hello 👋 and thank you for this cool repo.
I'm trying to uplade a file in cli, this is what I get:

Welcome to the Claude CLI!
? Select a conversation: Start new conversation
? (claude-2) > summarize [README.md]
Asking claude
⠋ Thinking...Uploading file README.md
ReferenceError: File is not defined

messages not being received

Why am I not receiving replies from Claude when I send messages? Also, when using stream responses, some words are missing.
image
image

Error: Conversation ID required

Hey, I'm getting this error:

        throw new Error('Conversation ID required');
              ^

Error: Conversation ID required
at new Conversation (file:///C:/Documents/Github/claude-unofficial-api/node_modules/claude-ai/index.js:142:19)
at Claude.startConversation (file:///C://Documents/Github/claude-unofficial-api/node_modules/claude-ai/index.js:62:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async startConversation (file:///C:/Documents/Github/claude-unofficial-api/test2.mjs:9:24)

For reference, this is my code:

import { Claude } from 'claude-ai';

const startConversation = async () => {
const claude = new Claude({
sessionKey: '[my key]'
});

const conversation = await claude.startConversation('Hello Claude!');
console.log(conversation);
const response = await conversation.sendMessage('How are you today?');
console.log(response);
};

startConversation();

Everything broke

I'm not sure if someone removed the Claude description on npm, but nevertheless, it broke on two of my projects and will not output anything

message.completion returns ''

Hello,

Since this morning every time I try to use the sendMessage method, regardless of the actual message sent, message.completion returns an empty string ''. While logging onto claude.ai, I can see that Claude responded to the prompt just fine with text.

const { Claude } = await import("claude-ai");
  const claude = new Claude({
    sessionKey: [my-session-key],
  });

  await claude.init();

 const conversation = await claude.startConversation(`[my initial conversion here]`)
 const message = await conversation.sendMessage(`[my message here]`)
console.log(message.completion)

And message.completion:

image

Is there an issue with the package?

Documentation for file upload via the API

I'm having difficulty understanding what sort of file object needs to be passed in to the attachments array for file upload. Could you provide a clarifying example for how to, e.g., attach a text file to a sendMessage call. Thanks.

CLI Session token

I created a file ".claude_key" in a directory where I pasted the session token. When I invoke the command claude --key ./.claude_key from CLI I get the following error -

TypeError: Cannot read properties of undefined (reading 'uuid')
    at Claude.init (file:///opt/homebrew/lib/node_modules/claude-cli/node_modules/claude-ai/index.js:33:48)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async main (file:///opt/homebrew/lib/node_modules/claude-cli/index.js:82:5)

Is there something that I need to fix or can the key not be in a custom directory?

I am creating a Express server for this to access it in python

import express from 'express';
import { Claude, Conversation } from 'claude-ai';

const app = express();
const port = 3000;


const id1 = ''
const claude = new Claude({
  sessionKey: id1
});

async function initClaude() {
  await claude.init();
}

app.use(express.json());

app.post('/api/conversation/:conversationId', async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { prompt } = req.body;

    const conversation_hdId = "3cd7bbb8-b6a9-4c42-9f2e-0bbe251cee48";
    const conversation = new Conversation(claude, { conversation_hdId });
    console.log("New Req")
    const response = await conversation.sendMessage(prompt);
    console.log(response);
    res.json(response);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

initClaude().then(() => {
  app.listen(port, () => {
    console.log(`Server running on port ${port}`);
  });
});

I am getting null response or sometimes it works for 1st request and then does not work.

Really thanks if you could help our or add this feature! Most ML devs use python : (

Met error at initialization when get organization from Claude

When I trying to use it, get an error at initialization, seems Claude blocked program to access API directly, anybody can help on this?
Error at: getOrganizations
SyntaxError: Unexpected token '<', "
)
at parseJSONFromBytes (node:internal/deps/undici/undici:6662:19)
at successSteps (node:internal/deps/undici/undici:6636:27)
at node:internal/deps/undici/undici:1236:60
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:206:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Untitled

ReferenceError: crypto is not defined

Hey!

When I try to run claude cli, I get the following error:

ReferenceError: crypto is not defined
    at Claude.startConversation (file:///C:/Users/myUser/AppData/Roaming/npm/node_modules/claude-cli/node_modules/claude-ai/index.js:36:23)
    at main (file:///C:/Users/myUser/AppData/Roaming/npm/node_modules/claude-cli/index.js:196:53)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

I am not really familiar with node, but it seems like an import is missing in the main index.js (Link).

More information:
OS: Windows 11
node version: v18.16.1
npm version: 9.8.0

echo "prompt" | claude doesn't work

If you use the cli like this: echo "hello" | claude --key key
This is what you get:

(node:18673) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Welcome to the Claude CLI!
? Select a conversation: Start new conversation
? (claude-2) >

and it exits and nothing happens

How to run the first demo?

Thanks for your work at first!

I am newbie at this. Could you provide more descriptions about running the first demo or example?

I tried to download various versions of node.js on windows and linux, but I still can't run const Claude = require('claude-ai'); even if I have run npm install claude-ai and npm install -g claude-cli :(

Model to use doesn’t work | Falls back to the default

The limit of messages is around 20-22 for the default model. While change through the code falls back the default & in the index,js this.claude.defaultModel() changing it gives null response.

async function get_response_to_specfic_id(ocr_data) {
    // Specify the conversation ID you want to start or join
    const conversationId = "2b70e59c-58c9-4ab7-b893-770fc262bb0f";

    // Create a conversation instance with the provided ID
    const conversation = new Conversation(claude, { conversationId });
    // console.log(ocr_data);
    // Send a message and print the response
    const response = await conversation.sendMessage(ocr_data,{model_to_use} );
    console.log(response);

    return response;
}

Screenshot 2023-07-19 at 6 19 08 PM

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.