How to input PDF with a prompt to GPT API

In the age of digital transformation, the ability to extract and process information from various document formats, including PDFs, has become invaluable. This Answer will guide you through the process of inputting a PDF document with a user prompt to the GPT API, leveraging the capabilities of both OpenAI and AskYourPDF.

Introduction to AskYourPDF and OpenAI GPT

AskYourPDF is a cutting-edge solution that allows developers to programmatically extract valuable information from PDF files and create custom chatbots. On the other hand, OpenAI GPT is a powerful language model that can generate human-like text based on prompts.

Setting up your environment

Before diving into the code, ensure you have the necessary API keys:

These keys are essential for authentication and accessing the respective services.

Uploading the PDF to AskYourPDF

To interact with the content of a PDF, you first need to upload it to AskYourPDF. This can be done using the upload endpoint of AskYourPDF.

def upload_pdf_to_askyourpdf(file_path):
headers = {
'x-api-key': ASKYOURPDF_API_KEY
}
with open(file_path, 'rb') as file_data:
response = requests.post('https://api.askyourpdf.com/v1/api/upload', headers=headers, files={'file': file_data})
if response.status_code == 201:
return response.json()['doc_id']
else:
raise Exception(f"Error uploading PDF: {response.status_code}")

Generating a query for AskYourPDF using GPT

To extract specific information from the PDF, you can use OpenAI GPT to generate a query based on the user's input.

extraction_prompt = f"I have a plugin that can extract information from a PDF. Based on the user's query '{user_prompt}', what should I ask the plugin to extract from the document?"
extraction_query = openai.Completion.create(engine="davinci", prompt=extraction_prompt, max_tokens=100).choices[0].text.strip()

Extracting content from the PDF

Once you have the query, you can use the chat endpoint of AskYourPDF to extract the desired content.

def chat_with_document(doc_id, message):
headers = {
'Content-Type': 'application/json',
'x-api-key': ASKYOURPDF_API_KEY
}
data = [
{
"sender": "User",
"message": message
}
]
response = requests.post(f'https://api.askyourpdf.com/v1/chat/{doc_id}', headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()['answer']['message']
else:
raise Exception(f"Error chatting with document: {response.status_code}")

Generating a response using OpenAI GPT

With the extracted content, you can now generate a coherent response using OpenAI GPT.

answer_prompt = f"The user asked: '{user_prompt}'. The extracted content from the document is: '{extracted_content}'. How should I respond?"
answer = openai.Completion.create(engine="davinci", prompt=answer_prompt, max_tokens=200).choices[0].text.strip()

Bringing it all together

Finally, you can combine all the steps in a main function to create a seamless interaction where the user provides a query and a PDF, and the system returns a relevant answer.

import requests
import openai
import json
import os
# Initialize OpenAI API
openai.api_key = os.environ['SECRET_KEY_OPENAI']
# AskYourPDF API Key
ASKYOURPDF_API_KEY = os.environ['SECRET_KEY_AskYourPDF']
def upload_pdf_to_askyourpdf(file_path):
headers = {
'x-api-key': ASKYOURPDF_API_KEY
}
with open(file_path, 'rb') as file_data:
response = requests.post('https://api.askyourpdf.com/v1/api/upload', headers=headers, files={'file': file_data})
if response.status_code == 201:
return response.json()['doc_id']
else:
raise Exception(f"Error uploading PDF: {response.status_code}")
def chat_with_document(doc_id, message):
headers = {
'Content-Type': 'application/json',
'x-api-key': ASKYOURPDF_API_KEY
}
data = [
{
"sender": "User",
"message": message
}
]
response = requests.post(f'https://api.askyourpdf.com/v1/chat/{doc_id}', headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()['answer']['message']
else:
raise Exception(f"Error chatting with document: {response.status_code}")
def main():
# Get user input
user_prompt = input("Enter your query about the PDF: ")
pdf_file_path = input("Provide the path to your PDF file: ")
# Use OpenAI GPT to generate a query for AskYourPDF
extraction_prompt = f"I have a plugin that can extract information from a PDF. Based on the user's query '{user_prompt}', what should I ask the plugin to extract from the document?"
extraction_query = openai.Completion.create(engine="davinci", prompt=extraction_prompt, max_tokens=100).choices[0].text.strip()
# Upload the PDF to AskYourPDF
doc_id = upload_pdf_to_askyourpdf(pdf_file_path)
# Extract the content based on GPT's query
extracted_content = chat_with_document(doc_id, extraction_query)
# Use GPT to generate an answer based on extracted content and user's initial prompt
answer_prompt = f"The user asked: '{user_prompt}'. The extracted content from the document is: '{extracted_content}'. How should I respond?"
answer = openai.Completion.create(engine="davinci", prompt=answer_prompt, max_tokens=200).choices[0].text.strip()
# Print the answer
print(f"Answer: {answer}")
if __name__ == "__main__":
main()

Conclusion

By integrating AskYourPDF with OpenAI GPT, you can create powerful applications that extract and process information from PDFs based on user prompts. This approach not only enhances user experience but also opens up new avenues for document analysis and interaction.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved