Explosion-Scratch / claude-unofficial-api

Unofficial API for Claude-2 via Claude Web (Also CLI)
https://npmjs.com/package/claude-ai
The Unlicense
729 stars 78 forks source link

Documentation for file upload via the API #28

Closed lightscalar closed 1 year ago

lightscalar commented 1 year ago

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.

Explosion-Scratch commented 1 year ago

First, extract the file content via await claude.uploadFile(js file object) which returns an attachment object you can pass to sendMessage. Here's an example:

import { Claude } from './index.js';

const claude = new Claude({
  sessionKey: 'sk-123', // replace with your session key
});

await claude.init();

// Create a text file
const file = new File(['Hello World!'], 'hello.txt', {type: 'text/plain'}); 

// Upload the file
const uploadedFile = await claude.uploadFile(file);

// Send a message referencing the uploaded file  
const response = await claude.sendMessage('What does this text file say?', {
  attachments: [uploadedFile] 
});

console.log(response);

If you're simply doing a plain text attachment though you don't even need the call to await uploadFile:

const fileContents = `Hello world! This is some text in a plain text file.`;

const fileAttachment = {
  file_name: 'test.txt',
  file_type: 'text/plain',
  file_size: fileContents.length,
  extracted_content: fileContents 
};

await claude.sendMessage('What does this text file say?', {
  attachments: [fileAttachment] 
});
Explosion-Scratch commented 1 year ago

You can always just ask claude how to do things as well, for example:

echo "Based on [index.js] show me how to upload a file and send it as an attachment" | claude