AskYourPDF API Documentation

Introducing the AskYourPDF API

AskYourPDF is a cutting-edge solution revolutionising document interactions. Our API empowers developers with the ability to programmatically extract valuable information from PDF files and leverage it to create custom chatbots. By providing seamless access to the content within PDF documents, developers can build powerful applications that enable users to navigate, search, and engage with data effortlessly. This comprehensive guide will walk you through the API's features, pricing, authentication methods, and usage guidelines, opening up endless possibilities to enhance productivity and knowledge retrieval for your applications. Harness the potential of AskYourPDF API and embark on an innovative journey of intelligent document analysis and interactive experiences.

Uploading A Document

To upload a document, choose between generating a document ID on our website or using the API endpoint. We support various document formats, including '.pdf', '.txt', '.ppt', '.pptx', '.csv', '.epub', and '.rtf'. Additionally, you can upload PDFs using links. Moreover, the API enables interaction with any blog post or website by providing the link to the post.

Authentication

Authentication is required for all our API endpoints. To access them, you must generate API keys on your AskYourPDF account. These API keys need to be set in your request header as "x-api-key." It is essential to treat your API key as a secret and ensure its protection.

headers: {
    "x-api-key": "ask_xxxxx"
  }

1. Adding Document via URL

Download Pdf

Download a PDF file from a URL and save it to the database.

Args: user: The user who is uploading the file. url: The URL of the PDF file to download.

Returns: dict: The document ID of the downloaded file.

GET/v1/api/download_pdf
Authorization
Query parameters
Response

Successful Response

Body
docId*Docid
Request
const response = await fetch('/v1/api/download_pdf', {
    method: 'GET',
    headers: {},
});
const data = await response.json();
Response
{
  "docId": "text"
}

Query Parameters:

  • url (required): The link to the document. It could be a link to a PDF or a post on a website

Response:

  • 201 Successful Response

    • doc_id (string): The document ID of the uploaded document.

{ "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd" }

Examples:

cURL
curl -X GET 
'https://api.askyourpdf.com/v1/api/download_pdf?url=https://www.example.com/document.pdf' 
-H 'x-api-key: YOUR_API_KEY'
Python
import requests

headers = {
    'x-api-key': 'YOUR_API_KEY'
}

response = requests.get('https://api.askyourpdf.com/v1/api/download_pdf', 
headers=headers, 
params={'url': 'https://www.example.com/document.pdf'})

if response.status_code == 201:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'x-api-key': 'YOUR_API_KEY'
};

axios.get('https://api.askyourpdf.com/v1/api/download_pdf', {
  headers: headers,
  params: {
    url: 'https://www.example.com/document.pdf'
  }
})
.then((response) => {
  if (response.status === 201) {
    console.log(response.data);
  } else {
    console.log('Error:', response.status);
  }
})
.catch((error) => {
  console.error(error);
});

2. Adding Document via File Upload

Upload Pdf

Upload a PDF file and save it to the database.

Args: user: The user who is uploading the file. file: The PDF file to upload.

Returns: dict: The document ID of the uploaded file.

POST/v1/api/upload
Authorization
Body
file*File
Response

Successful Response

Body
docId*Docid
Request
const response = await fetch('/v1/api/upload', {
    method: 'POST',
    headers: {
      "Content-Type": "multipart/form-data"
    },
    body: JSON.stringify({
      "file": "binary"
    }),
});
const data = await response.json();
Response
{
  "docId": "text"
}

Request body:

The request body should be sent as a form of data with the name file (see example).

  • file (required): The raw bytes of the file to be uploaded.

Response:

  • 201 Successful Response

    • doc_id (string): The document ID of the uploaded document.

{ "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd" }

Examples:

cURL
curl -X POST 
-H 'x-api-key: YOUR_API_KEY' 
-F "file=@/path/to/yourfile.pdf" https://api.askyourpdf.com/v1/api/upload

Python
import requests

headers = {
    'x-api-key': 'YOUR_API_KEY'
}

file_data = open('/path/to/yourfile.pdf', 'rb')

response = requests.post('https://api.askyourpdf.com/v1/api/upload', headers=headers,
 files={'file': file_data})

if response.status_code == 201:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const headers = {
    'x-api-key': 'YOUR_API_KEY'
};

let form = new FormData();
form.append('file', fs.createReadStream('/path/to/yourfile.pdf'));

axios.post('https://api.askyourpdf.com/v1/api/upload', form, {
  headers: {
    ...headers,
    ...form.getHeaders()
  }
})
.then((response) => {
  if (response.status === 201) {
    console.log(response.data);
  } else {
    console.log('Error:', response.status);
  }
})
.catch((error) => {
  console.error(error);
});

3. Chat Endpoint

Endpoint for initiating a chat with a document. This endpoint requires API Key Header authentication.

Chat With Doc Endpoint

Chat with a single document.

Args: doc_id: The document id. model_name: The model name. messages: The list of messages. stream: Whether to stream the response or not.

Returns: ChatSerializer: The chat response.

POST/v1/chat/{doc_id}
Authorization
Path parameters
doc_id*Doc Id
Query parameters
Body
sender*Sender
message*Message
Response

Successful Response

Body
question*ChatResponse

ChatResponse response schema.

answer*ChatResponse

ChatResponse response schema.

createdCreated
Request
const response = await fetch('/v1/chat/{doc_id}', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify([
      {
        "sender": "text",
        "message": "text"
      }
    ]),
});
const data = await response.json();
Response
{
  "question": {
    "sender": "text",
    "message": "text",
    "type": "text"
  },
  "answer": {
    "sender": "text",
    "message": "text",
    "type": "text"
  },
  "created": "2024-05-02T19:49:48.587Z"
}

Path Parameters:

doc_id (string, required): The ID of the document for the conversation.

Query Parameters:

  • model_name: Available values are CLAUDE1, GPT3 AND GPT4(GPT4 Credits Required). Default is GPT3.

  • stream (boolean, optional): Flag for streaming. Default is false.

Request body:

  • sender (required): The sender of the chat message. The sender should be User

  • message (required): The chat message content.

The request body to ask a single question.

[
  {
    "sender": "User",
    "message": "What does this document say?"
  }
]

To ask a follow-up question and provide the model with context you can send your previous questions and responses in the following format.

[
    {   
    "sender": "user",
    "message": "What does the document say?"
    },
    {
    "sender": "bot",
    "message": "The document consists of words in different languages expressing gratitude"
     },
   {
    "sender": "user",
    "message": "What is the word expressing gratitude in Spanish?"
    }
]

Response:

The response when the query parameter stream = False

  • 200 Successful Response

    • question: The question posed by the user, with sender, message, and type.

      • sender

      • message

      • type

    • answer: The answer provided by the AI, with sender, message, and type.

      • sender

      • message

      • type

    • created (string): The time the chat was created.

{
  "question": {
    "sender": "user",
    "message": "What does this document say?",
    "type": "question"
  },
  "answer": {
    "sender": "bot",
    "message": "This document talks about AI",
    "type": "response"
  },
  "created": "2023-07-20T11:14:55.928Z"
}

By setting the query parameter stream = True, you can receive the response as a stream of token. An example of the response can be seen below.

Chunk: This
Chunk: document
Chunk: talks
Chunk: about
Chunk: AI

Example when stream = False:

cURL
curl -X POST 
-H 'Content-Type: application/json' 
-H 'x-api-key: YOUR_API_KEY' 
-d '[{"sender": "User","message": "What does this document say?"}]'
 https://api.askyourpdf.com/v1/chat/{YOUR_DOC_ID}

Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = [
    {
        "sender": "User",
        "message": "What does this document say?"
    }
]

response = requests.post(
'https://api.askyourpdf.com/v1/chat/{YOUR_DOC_ID}?model_name=GPT3', 
headers=headers, data=json.dumps(data))

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
};

const data = [
    {
        "sender": "User",
        "message": "What does this document say?"
    }
];

axios.post('https://api.askyourpdf.com/v1/chat/{YOUR_DOC_ID}?model_name=GPT3', 
data, {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log(response.data);
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

Example when stream = True:

Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = [
    {
        "sender": "User",
        "message": "What does this document say?"
    }
]

try:
    response = requests.post(
        'https://api.askyourpdf.com/v1/chat/YOUR_DOC_ID?stream=True&model_name=GPT3',
        headers=headers, data=json.dumps(data))
    response.raise_for_status()

    for chunk in response.iter_content(chunk_size=24):
        chunk_str = chunk.decode('utf-8')
        print("Chunk:", chunk_str)

except requests.exceptions.RequestException as error:
    print("Error:", error)
Javascript
const fetch = require('node-fetch');
const Readable = require('stream').Readable;


const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

const data = [
    {
        "sender": "User",
        "message": "What does this document say?"
    }
]

fetch('https://api.askyourpdf.com/v1/chat/YOUR_DOC_ID?stream=True&model_name=GPT3', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
    })
    .then(stream => {
        const reader = Readable.from(stream);
        reader.on('data', chunk => {
            console.log("Chunk:", chunk.toString('utf-8'));
        });
    })
    .catch(error => {
        console.log("Error:", error);
    });

4. Documents Retrieval Endpoint

This endpoint allows users to retrieve a paginated list of their uploaded documents.

Fetch Documents

Fetch all documents for the current user.

Returns: dict: A list of documents.

GET/v1/api/documents
Authorization
Query parameters
Response

Successful Response

Body
total_pagesTotal Pages
documents*Documents
Request
const response = await fetch('/v1/api/documents', {
    method: 'GET',
    headers: {},
});
const data = await response.json();
Response
{
  "documents": [
    {
      "name": "text",
      "doc_id": "text",
      "summary": "text",
      "language": "en",
      "shareable": true,
      "date_time": "2024-05-02T19:49:48.587Z"
    }
  ]
}

Query Parameters:

  • page (integer, optional): The page to return. Defaults to 1.

  • page_size (integer, optional): The number of documents to return per page. Defaults to 10.

Response:

  • 200 Successful Response

    • total_pages (Integer): The total number of pages available for querying

    • documents (Array): A list of document details belonging to the user.

      • name

      • doc_id

      • summary

      • language

      • pages

      • shareable

      • date_time

{
  "total_pages": 1,
  "documents": [
    {
      "name": "Nature.pdf",
      "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
      "summary": "This is a document about nature",
      "language": "en",
      "pages": 10,
      "shareable": true,
      "date_time": "2023-07-21T06:18:18.891Z"
    }
  ]
}

Examples:

cURL
curl -X GET 
-H 'x-api-key: YOUR_API_KEY' 
'https://api.askyourpdf.com/v1/api/documents?page=1&page_size=10'
Python
import requests

headers = {
    'x-api-key': 'YOUR_API_KEY'
}

params = {
    'page': 1,
    'page_size': 10
}

response = requests.get('https://api.askyourpdf.com/v1/api/documents', 
headers=headers, params=params)

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'x-api-key': 'YOUR_API_KEY'
};

const params = {
    'page': 1,
    'page_size': 10
};

axios.get('https://api.askyourpdf.com/v1/api/documents', 
{headers: headers, params: params})
.then((response) => {
  if (response.status === 200) {
    console.log(response.data);
  } else {
    console.log('Error:', response.status);
  }
})
.catch((error) => {
  console.error(error);
});

5. Single Document Retrieval Endpoint

This endpoint allows users to retrieve a single document.

Fetch Document

Fetch a user's documents using the doc_id.

Returns: dict: A single document.

GET/v1/api/documents/{doc_id}
Authorization
Path parameters
doc_id*Doc Id
Response

Successful Response

Body
name*Name
doc_id*Doc Id
summarySummary
languageLanguage
pagesPages
shareableShareable
date_timeDate Time
Request
const response = await fetch('/v1/api/documents/{doc_id}', {
    method: 'GET',
    headers: {},
});
const data = await response.json();
Response
{
  "name": "text",
  "doc_id": "text",
  "summary": "text",
  "language": "en",
  "shareable": true,
  "date_time": "2024-05-02T19:49:48.587Z"
}

Path Parameters:

doc_id (string, required): The ID of the document for the conversation.

Response:

  • 200 Successful Response

    • name

    • doc_id

    • summary

    • language

    • pages

    • shareable

    • date_time

  {
    "name": "Nature.pdf",
    "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "summary": "This is a document about nature",
    "language": "en",
    "pages": 10,
    "shareable": true,
    "date_time": "2023-07-21T06:18:18.891Z"
  }

Examples:

cURL
curl -X GET
 -H 'x-api-key: YOUR_API_KEY' 
 'https://api.askyourpdf.com/v1/api/documents/{YOUR_DOC_ID}'
Python
import requests

headers = {
    'x-api-key': 'YOUR_API_KEY'
}

response = requests.get('https://api.askyourpdf.com/v1/api/documents/{YOUR_DOC_ID}',
 headers=headers)

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'x-api-key': 'YOUR_API_KEY'
};

axios.get('https://api.askyourpdf.com/v1/api/documents/{YOUR_DOC_ID}',
 {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log(response.data);
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

6. Delete Document Endpoint

Allows users to delete a single document

Delete Document

Delete a document belonging to the authenticated user.

Args: user: The user who is deleting the file. doc_id: The document ID to delete.

Returns: dict: A success message.

DELETE/v1/api/documents/{doc_id}
Authorization
Path parameters
doc_id*Doc Id
Response

Successful Response

Body
Response Delete Document V1 Api Documents Doc Id Delete
Request
const response = await fetch('/v1/api/documents/{doc_id}', {
    method: 'DELETE',
    headers: {},
});
const data = await response.json();

Path Parameters:

doc_id (string, required): The ID of the document to be deleted.

Response:

  • 200 Successful Response

 {"message": "Document deleted successfully"}

Examples:

cURL
curl -X DELETE 
-H 'x-api-key: YOUR_API_KEY' 
'https://api.askyourpdf.com/v1/api/documents/DOC_ID'
Python
import requests

headers = {
    'x-api-key': 'YOUR_API_KEY'
}

response = requests.delete('https://api.askyourpdf.com/v1/api/documents/DOC_ID', headers=headers)

if response.status_code == 200:
    print('Document deleted successfully')
else:
    print('Error:', response.status_code)

Javascript
const axios = require('axios');

const headers = {
    'x-api-key': 'YOUR_API_KEY'
};

axios.delete('https://api.askyourpdf.com/v1/api/documents/DOC_ID', {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log('Document deleted successfully');
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

7. Summarise Document Endpoint

Allows users to summarise a single document (summarisation credits required).

Document Summary Endpoint

Summarise a document

Args: summary_prompt: The document id and prompt for summary. stream: Whether to stream the response or not. user: The user.

Returns: A stream of the generated summary.

POST/v1/api/summary
Authorization
Query parameters
Body
doc_id*Doc Id
lengthall of
formatall of
markdownMarkdown
promptPrompt
Response

Successful Response

Body
summarySummary
date_timeDate Time
promptPrompt
languageLanguage
document_nameDocument Name
pagesPages
Request
const response = await fetch('/v1/api/summary', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      "doc_id": "text"
    }),
});
const data = await response.json();
Response
{
  "summary": "text",
  "date_time": "2024-05-02T19:49:48.587Z",
  "prompt": "text",
  "language": "text",
  "document_name": "text"
}

Query Parameters:

  • stream (boolean, optional): Flag for streaming. Default is False.

Request body:

  • doc_id (String, required): The ID of the document to summarise.

  • length (String, required): How long the summary should be, with options AUTO, LONG and SHORT.

  • format (String, required): The arrangement of the summary with options AUTO, PARAGRAPH, BULLET and PAPER.

  • markdown (boolean, required): Flag for determining if the response should be in markdown. Default is false.

  • prompt (String, required): Additional instructions to be given for summarising the document.

The request body to summarise a document

{
  "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
  "length": "AUTO",
  "format": "AUTO",
  "markdown": true,
  "prompt": "Summarise the following context"
}

Response:

  • 200 Successful Response

    • summary (String): The summary of the document given based on the instructions from the request.

    • date_time (String): The time the summary was created.

    • prompt (String): The set of additional instructions given from the request body.

    • language (String): The language in which the summary is given.

    • document_name (String): The name of the document.

    • pages (Integer): The number of pages of the document.

{
  "summary": "This is a document that talks about nature",
  "date_time": "2023-10-01T12:42:50.675Z",
  "prompt": "Summarise the following context",
  "language": "en",
  "document_name": "Nature.pdf",
  "pages": 10
}

By setting the query parameter, stream = true, you can receive the response as a stream of token. An example of the response can be seen below.

Chunk: This
Chunk: is
Chunk: a
Chunk: document
Chunk: that
Chunk: talks
Chunk: about
Chunk: nature

Example when stream = False:

cURL
curl -X 'POST' \
  'https://api.askyourpdf.com/v1/api/summary' \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
  "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
  "length": "AUTO",
  "format": "AUTO",
  "markdown": true,
  "prompt": "Summarise the following context"
}'
Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
    "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "length": "AUTO",
    "format": "AUTO",
    "markdown": True,
    "prompt": "Summarise the following context"
}


response = requests.post('https://api.askyourpdf.com/v1/api/summary', 
headers=headers, data=json.dumps(data))

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
};

const data = {
    "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "length": "AUTO",
    "format": "AUTO",
    "markdown": true,
    "prompt": "Summarise the following context"
};

axios.post('https://api.askyourpdf.com/v1/api/summary', data, {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log(response.data);
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

Example when stream = True:

Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
    "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "length": "AUTO",
    "format": "AUTO",
    "markdown": True,
    "prompt": "Summarise the following context"
}


try:
    response = requests.post(
        'https://api.askyourpdf.com/v1/api/summary?stream=True',
        headers=headers, data=json.dumps(data))
    response.raise_for_status()

    for chunk in response.iter_content(chunk_size=24):
        chunk_str = chunk.decode('utf-8')
        print("Chunk:", chunk_str)

except requests.exceptions.RequestException as error:
    print("Error:", error)
Javascript
const fetch = require('node-fetch');
const Readable = require('stream').Readable;


const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

const data = {
    "doc_id": "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "length": "AUTO",
    "format": "AUTO",
    "markdown": true,
    "prompt": "Summarise the following context"
};

fetch('https://api.askyourpdf.com/v1/api/summary?stream=True', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
    })
    .then(stream => {
        const reader = Readable.from(stream);
        reader.on('data', chunk => {
            console.log("Chunk:", chunk.toString('utf-8'));
        });
    })
    .catch(error => {
        console.log("Error:", error);
    });

8. Summarise Text Endpoint

Allows users to summarise text (summarisation credits required).

Text Summary Endpoint

Summarise a document

Args: summary_prompt: The text for summary. stream: Whether to stream the response or not. user: The user.

Returns: A stream of the generated summary.

POST/v1/api/text_summary
Authorization
Query parameters
Body
lengthall of
formatall of
markdownMarkdown
summary_text*Summary Text
Response

Successful Response

Body
summarySummary
date_timeDate Time
Request
const response = await fetch('/v1/api/text_summary', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      "summary_text": "text"
    }),
});
const data = await response.json();
Response
{
  "summary": "text",
  "date_time": "2024-05-02T19:49:48.587Z"
}

Query Parameters:

  • stream (boolean, optional): Flag for streaming. Default is False.

Request body:

  • length (String, required): How long the summary should be, with options AUTO, LONG and SHORT.

  • format (String, required): The arrangement of the summary with options AUTO, PARAGRAPH, BULLET and PAPER.

  • markdown (boolean, required): Flag for determining if the response should be in markdown. Default is false.

  • summary_text (String, required): The text to summarise.

The request body to summarise a document

{
  "length": "AUTO",
  "format": "AUTO",
  "markdown": true,
  "summary_text": "Sunlight fuels life through photosynthesis."
}

Response:

  • 200 Successful Response

    • summary (String): The summary of the text from the request.

    • date_time (String): The time the summary was created.

{
  "summary": "The text given talks about photosynthesis",
  "date_time": "2023-10-01T13:52:43.288Z",
}

By setting the query parameter, stream = true, you can receive the response as a stream of token. An example of the response can be seen below.

Chunk: The
Chunk: text
Chunk: given
Chunk: talks
Chunk: about
Chunk: photosynthesis

Example when stream = False:

cURL
curl -X 'POST' \
  'https://api.askyourpdf.com/v1/api/text_summary' \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
  "length": "AUTO",
  "format": "AUTO",
  "markdown": true,
  "summary_text": "Sunlight fuels life through photosynthesis."
}'
Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
    "length": "AUTO",
    "format": "AUTO",
    "markdown": True,
    "summary_text": "Sunlight fuels life through photosynthesis."
}


response = requests.post('https://api.askyourpdf.com/v1/api/text_summary', 
headers=headers, data=json.dumps(data))

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
};

const data = {
    "length": "AUTO",
    "format": "AUTO",
    "markdown": true,
    "summary_text": "Sunlight fuels life through photosynthesis."
};

axios.post('https://api.askyourpdf.com/v1/api/text_summary', data, {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log(response.data);
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

Example when stream = True:

Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
    "length": "AUTO",
    "format": "AUTO",
    "markdown": True,
    "summary_text": "Sunlight fuels life through photosynthesis."
}


try:
    response = requests.post(
        'https://api.askyourpdf.com/v1/api/text_summary?stream=True',
        headers=headers, data=json.dumps(data))
    response.raise_for_status()

    for chunk in response.iter_content(chunk_size=24):
        chunk_str = chunk.decode('utf-8')
        print("Chunk:", chunk_str)

except requests.exceptions.RequestException as error:
    print("Error:", error)
Javascript
const fetch = require('node-fetch');
const Readable = require('stream').Readable;


const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

const data = {
    "length": "AUTO",
    "format": "AUTO",
    "markdown": true,
    "summary_text": "Sunlight fuels life through photosynthesis."
};

fetch('https://api.askyourpdf.com/v1/api/text_summary?stream=True', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
    })
    .then(stream => {
        const reader = Readable.from(stream);
        reader.on('data', chunk => {
            console.log("Chunk:", chunk.toString('utf-8'));
        });
    })
    .catch(error => {
        console.log("Error:", error);
    });

9. Knowledge Base Endpoint

Endpoint for initiating a chat with multiple documents. This endpoint requires API Key Header authentication.

Chat With Multiple Documents

Chat with multiple document.

Args: knowledge_base: The knowledge base request payload containing the list of documents and messages. model_name: The model name. stream: Whether to stream the response or not.

Returns: ChatSerializer: The chat response.

POST/v1/api/knowledge_base_chat
Authorization
Query parameters
Body
documents*Documents
messages*Messages
Response

Successful Response

Body
question*ChatResponse

ChatResponse response schema.

answer*ChatResponse

ChatResponse response schema.

createdCreated
Request
const response = await fetch('/v1/api/knowledge_base_chat', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      "documents": [
        "text"
      ],
      "messages": [
        {
          "sender": "text",
          "message": "text"
        }
      ]
    }),
});
const data = await response.json();
Response
{
  "question": {
    "sender": "text",
    "message": "text",
    "type": "text"
  },
  "answer": {
    "sender": "text",
    "message": "text",
    "type": "text"
  },
  "created": "2024-05-02T19:49:48.587Z"
}

Query Parameters:

  • model_name: Available values are CLAUDE1, GPT3 AND GPT4(GPT4 Credits Required). Default is GPT3.

  • stream (boolean, optional): Flag for streaming. Default is False.

Request body:

  • documents (Array, required): A list of documents from which a response will be generated. Takes in multiple document IDs.

  • messages (Array, required): A list of messages to send.

    • sender (String, required): The sender of the chat message. The sender should be User

    • message (String, required): The chat message content.

The request body to ask a single question.

{
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "User",
      "message": "What is the common theme of the documents?"
    }
  ]
}

To ask a follow-up question and provide the model with context, you can send your previous questions and responses in the following format.

{
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    },
    {
      "sender": "bot",
      "message": "These documents talk about words and their synonyms across various languages."
    },
    {
      "sender": "user",
      "message": "What are the words for expressing gratitude in Spanish?"
    }
  ]
}

Response:

The response when the query parameter stream = False

  • 200 Successful Response

    • question: The question posed by the user, with sender, message, and type.

      • sender (String)

      • message (String)

      • type (String)

    • answer: The answer provided by the AI, with sender, message, and type.

      • sender (String)

      • message (String)

      • type (String)

    • created (String): The time the chat was created.

{
  "question": {
    "sender": "user",
    "message": "What is the common theme of the documents?",
    "type": "question"
  },
  "answer": {
    "sender": "bot",
    "message": "These documents talk about words and their synonyms across various languages.",
    "type": "response"
  },
  "created": "2023-07-20T11:14:55.928Z"
}

By setting the query parameter stream = True, you can receive the response as a stream of token. An example of the response can be seen below.

Chunk: These
Chunk: documents
Chunk: talk
Chunk: about
Chunk: words
Chunk: and
Chunk: their
Chunk: synonyms
Chunk: across
Chunk: various
Chunk: languages.

Example when stream = False:

cURL
curl -X 'POST' \
  'https://api.askyourpdf.com/v1/api/knowledge_base_chat?model_name=GPT3' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    }
  ]
}'
Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    }
  ]
}

response = requests.post(
'https://api.askyourpdf.com/v1/api/knowledge_base_chat?model_name=GPT3', 
headers=headers, data=json.dumps(data))

if response.status_code == 200:
    print(response.json())
else:
    print('Error:', response.status_code)
Javascript
const axios = require('axios');

const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
};

const data = {
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    }
  ]
};

axios.post('https://api.askyourpdf.com/v1/api/knowledge_base_chat?model_name=GPT3', 
data, {headers: headers})
.then((response) => {
    if (response.status === 200) {
        console.log(response.data);
    } else {
        console.log('Error:', response.status);
    }
})
.catch((error) => {
    console.error(error);
});

Example when stream = True:

Python
import requests
import json

headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

data = {
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    }
  ]
}

try:
    response = requests.post(
        'https://api.askyourpdf.com/v1/api/knowledge_base_chat?stream=True',
        headers=headers, data=json.dumps(data))
    response.raise_for_status()

    for chunk in response.iter_content(chunk_size=24):
        chunk_str = chunk.decode('utf-8')
        print("Chunk:", chunk_str)

except requests.exceptions.RequestException as error:
    print("Error:", error)
Javascript
const fetch = require('node-fetch');
const Readable = require('stream').Readable;


const headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YOUR_API_KEY'
}

const data = {
  "documents": [
    "6e60e87c-6154-4dff-8e62-ff10d8ed16dd",
    "7f71f98d-7265-5egg-9f73-gg21e9fe27ee"
  ],
  "messages": [
    {
      "sender": "user",
      "message": "What is the common theme of the documents?"
    }
  ]
}

fetch('https://api.askyourpdf.com/v1/api/knowledge_base_chat?stream=True', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
    })
    .then(stream => {
        const reader = Readable.from(stream);
        reader.on('data', chunk => {
            console.log("Chunk:", chunk.toString('utf-8'));
        });
    })
    .catch(error => {
        console.log("Error:", error);
    });

Last updated