All Posts
OpenAI Integration: Build a RAG Chatbot That Answers Questions From Your PDFs

OpenAI Integration: Build a RAG Chatbot That Answers Questions From Your PDFs

β€’Cocoding Team

OpenAI Integration: Build a RAG Chatbot That Answers Questions From Your PDFs

Large Language Models are powerful, but they have a critical flaw: hallucinations. They confidently make up information that sounds plausible but is completely wrong. What if you could build an AI chatbot that ONLY answers from your documents, with zero made-up facts? With Cocoding AI's OpenAI integration, you can build a Retrieval-Augmented Generation (RAG) system that's grounded in truth.

The sections below walk through the build prompt, OpenAI (embeddings) and Groq (chat) API keys, wiring backend/.env, and testing your PDF chatbotβ€”end to end.

The Hallucination Problem

Standard chatbots have serious limitations:

  • Invented facts - LLMs confidently state false information
  • Outdated knowledge - Training data has cutoff dates
  • No source citations - Can't verify where answers come from
  • Generic responses - No access to your specific documents
  • Compliance risks - Wrong information can have legal consequences

RAG solves these problems by grounding AI responses in your actual documents.

What is RAG (Retrieval-Augmented Generation)?

RAG is a technique that combines:

  1. Retrieval: Find relevant information from your documents
  2. Augmentation: Add that information to the AI's context
  3. Generation: AI generates answers using ONLY retrieved content
Traditional Chatbot:
User Question β†’ LLM β†’ Answer (possibly hallucinated)

RAG Chatbot:
User Question β†’ Search Documents β†’ Find Relevant Chunks
    β†’ Send Chunks + Question to LLM β†’ Grounded Answer

Result: Answers that are factual, verifiable, and cite sources.

What You Can Build

Complete RAG Chatbot Application

Cocoding AI generates a full-featured system:

Application Features:
β”œβ”€β”€ Document Management
β”‚   β”œβ”€β”€ PDF drag-and-drop upload
β”‚   β”œβ”€β”€ Document library view
β”‚   β”œβ”€β”€ Delete documents
β”‚   └── Processing status
β”œβ”€β”€ AI Chat Interface
β”‚   β”œβ”€β”€ Natural language questions
β”‚   β”œβ”€β”€ Source citations
β”‚   β”œβ”€β”€ Conversation history
β”‚   └── Follow-up questions
β”œβ”€β”€ Vector Search Engine
β”‚   β”œβ”€β”€ OpenAI embeddings
β”‚   β”œβ”€β”€ Semantic similarity search
β”‚   β”œβ”€β”€ Configurable relevance
β”‚   └── PostgreSQL pgvector
└── User Authentication
    β”œβ”€β”€ Account creation
    β”œβ”€β”€ Secure login
    └── Personal document storage

Technical Architecture

Tech Stack:
β”œβ”€β”€ Frontend (React)
β”‚   β”œβ”€β”€ Document upload UI
β”‚   β”œβ”€β”€ Chat interface
β”‚   └── Document management
β”œβ”€β”€ Backend (NestJS)
β”‚   β”œβ”€β”€ PDF text extraction
β”‚   β”œβ”€β”€ OpenAI embeddings API
β”‚   β”œβ”€β”€ Groq LLM integration
β”‚   └── Vector similarity search
└── Database (PostgreSQL + pgvector)
    β”œβ”€β”€ User accounts
    β”œβ”€β”€ Document metadata
    └── Vector embeddings

How the RAG System Works

The 8-Step Process

Document Ingestion:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 1. Upload PDF                                                   β”‚
β”‚    ↓                                                            β”‚
β”‚ 2. Extract text from PDF                                        β”‚
β”‚    ↓                                                            β”‚
β”‚ 3. Split into ~1000 character chunks                           β”‚
β”‚    ↓                                                            β”‚
β”‚ 4. Generate OpenAI embeddings for each chunk                   β”‚
β”‚    ↓                                                            β”‚
β”‚ 5. Store embeddings in PostgreSQL with pgvector                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Query Processing:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 6. User asks question β†’ Generate embedding for query           β”‚
β”‚    ↓                                                            β”‚
β”‚ 7. Semantic search β†’ Find top 5 most similar chunks            β”‚
β”‚    ↓                                                            β”‚
β”‚ 8. Send chunks + question to Groq LLM β†’ Return grounded answer β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Vector Embeddings Explained

Embeddings convert text into numerical representations:

Text: "The quarterly revenue increased by 15%"
       ↓ OpenAI Embedding API
Embedding: [0.023, -0.156, 0.892, ..., 0.445] (1536 dimensions)

Similar concepts have similar embeddings, enabling semantic searchβ€”finding relevant content even when exact words don't match.

QueryKeyword SearchSemantic Search
"How much did we make?"No resultsFinds "revenue", "profit", "earnings"
"Team size"No resultsFinds "employees", "headcount", "staff"
"Product launch date"Partial matchFinds "release", "go-live", "deployment"

Step-by-Step Setup Guide

Follow this sequence: describe the app, add keys, configure .env, then test.

Step 1: Tell Cocoding.ai What to Build

Copy and paste a specification like this into Cocoding.ai (adjust wording if you likeβ€”keep the RAG stack explicit):

Build a document-based chatbot application with these features:

Frontend (React):
- User authentication (register/login)
- PDF upload with drag-and-drop
- Document management page
- Chat interface with message history
- Modern UI with Tailwind CSS

Backend (NestJS):
- JWT authentication
- PDF text extraction
- Vector embeddings generation
- Semantic search using embeddings
- Chat API with Groq LLM integration
- PostgreSQL database with pgvector

Technical Requirements:
- Use Groq API for fast LLM responses
- Use OpenAI API for text embeddings
- Store documents and chat history in PostgreSQL
- Implement retrieval-augmented generation (RAG)
- Secure file upload validation
- CORS configuration for API access

RAG Workflow:
1. Extract text from uploaded PDFs
2. Split text into chunks
3. Generate embeddings for each chunk
4. Store embeddings in database
5. On query: find relevant chunks via semantic search
6. Send chunks + question to Groq LLM
7. Return AI-generated answer based only on document content

Cocoding.ai can generate the full stackβ€”frontend, backend, database, and RAG pipelineβ€”automatically.

Cocoding.ai build prompt or generated app context

Step 2: Get API Keys

2.1 OpenAI API Key (embeddings)

  1. Open platform.openai.com/api-keys
  2. Sign up or log in
  3. Click Create new secret key
  4. Name it (e.g. RAG Application) and copy it immediatelyβ€”keys typically start with sk-proj- or sk-

Approximate cost is about $0.02 per 1M tokens for embeddings (e.g. a large PDF is still cents). Add a payment method under Settings β†’ Billing if required and consider a low monthly limit.

OpenAI platform: API keys β€” create and copy a secret key

2.2 Groq API Key (chat)

  1. Open console.groq.com/keys
  2. Sign up or log in
  3. Create API Key and copy itβ€”keys usually start with gsk_

Groq offers free chat inference with generous limits for development and many production workloads.

Step 3: Configure Your App with API Keys

In your generated project, edit backend/.env (create it if the template lists placeholders):

GROQ_API_KEY=gsk_YOUR_ACTUAL_GROQ_KEY_HERE
OPENAI_API_KEY=sk-proj-YOUR_ACTUAL_OPENAI_KEY_HERE

Save the fileβ€”many setups restart the NestJS backend automatically when env changes.

backend/.env with Groq and OpenAI API keys

Also keep database and JWT variables your scaffold expects (for example DATABASE_URL, JWT_SECRET)β€”see your repo’s .env.example. Your app stores embeddings in PostgreSQL with pgvector and runs similarity search over chunk vectors.

Step 4: Test Your RAG App

Create an account β€” Open the URL Cocoding.ai provides, sign up with name, email, and password.

Upload a PDF β€” Use drag-and-drop or file picker, wait for extraction, chunking, embeddings, and storage (often tens of seconds for larger files).

Chat with your document β€” Open chat on the document and ask grounded questions (for example β€œWhat is this document about?” or β€œSummarize the main points”). Answers should follow your uploaded content, not generic model guesses.

If anything fails, check key prefixes (sk- / sk-proj-, gsk_), stray spaces in .env, billing on OpenAI, and restart the backend.

Reference: pgvector (usually already scaffolded)

Generated apps typically already enable pgvector and similarity search. If you are wiring SQL yourself, store chunk embeddings for cosine search and tune chunk size, embedding model, and β€œtop K” retrieved chunks in your backend services as needed.

Building the User Experience

Document Upload Interface

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Upload Documents                        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚                                              β”‚   β”‚
β”‚  β”‚     πŸ“„ Drag and drop PDFs here              β”‚   β”‚
β”‚  β”‚                                              β”‚   β”‚
β”‚  β”‚         or click to browse                   β”‚   β”‚
β”‚  β”‚                                              β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                      β”‚
β”‚  Uploaded Documents:                                 β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ πŸ“„ Company_Handbook.pdf     βœ… Ready   [πŸ—‘οΈ] β”‚   β”‚
β”‚  β”‚ πŸ“„ Q4_Financial_Report.pdf  βœ… Ready   [πŸ—‘οΈ] β”‚   β”‚
β”‚  β”‚ πŸ“„ Product_Manual.pdf       ⏳ Processing   β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Chat Interface

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Document Q&A                            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                      β”‚
β”‚  πŸ‘€ What is our vacation policy?                    β”‚
β”‚                                                      β”‚
β”‚  πŸ€– According to the Company Handbook, employees    β”‚
β”‚     are entitled to:                                 β”‚
β”‚                                                      β”‚
β”‚     β€’ 15 days of paid vacation per year             β”‚
β”‚     β€’ 5 additional days after 3 years of service    β”‚
β”‚     β€’ Unused days can roll over (max 5 days)        β”‚
β”‚                                                      β”‚
β”‚     πŸ“š Sources:                                      β”‚
β”‚     - Company_Handbook.pdf (page 23)                β”‚
β”‚     - Company_Handbook.pdf (page 24)                β”‚
β”‚                                                      β”‚
β”‚  ─────────────────────────────────────────────────  β”‚
β”‚                                                      β”‚
β”‚  πŸ‘€ How do I request time off?                      β”‚
β”‚                                                      β”‚
β”‚  πŸ€– To request time off, follow these steps:        β”‚
β”‚     1. Submit request through HR portal             β”‚
β”‚     2. Request must be submitted 2 weeks in advance β”‚
β”‚     3. Manager approval required for 3+ days        β”‚
β”‚                                                      β”‚
β”‚     πŸ“š Sources:                                      β”‚
β”‚     - Company_Handbook.pdf (page 25)                β”‚
β”‚                                                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚ β”‚ Ask a question about your documents...       β”‚    β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                                      [ Send ]       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Configuration Options

Embedding Models

ModelDimensionsCostBest For
text-embedding-3-small1536$0.02/1M tokensCost-effective
text-embedding-3-large3072$0.13/1M tokensMaximum accuracy
text-embedding-ada-0021536$0.10/1M tokensLegacy support

LLM Options (via Groq)

ModelSpeedQualityBest For
llama-3.3-70bFastExcellentGeneral use
llama-3.1-405bMediumBestComplex reasoning
mixtral-8x7bVery fastGoodQuick responses
gemma2-9bFastestGoodHigh volume

Chunking Parameters

ParameterDefaultRangeImpact
Chunk size1000 chars500-2000Larger = more context per chunk
Chunk overlap200 chars0-500Higher = better continuity
Top K results53-10More = broader context

Use Cases

Knowledge Base / Help Desk

Documents: Product manuals, FAQs, support articles Use: Customer self-service, support agent assistance

Example:

  • "How do I reset my password?"
  • "What's the return policy?"
  • "How do I set up two-factor authentication?"

Documents: Contracts, policies, regulations Use: Quick clause lookup, compliance checking

Example:

  • "What are the termination conditions in this contract?"
  • "Does this policy comply with GDPR?"
  • "What are our liability limits?"

Research Assistant

Documents: Academic papers, reports, studies Use: Literature review, fact-checking

Example:

  • "What methodology did the Smith study use?"
  • "What were the key findings on customer retention?"
  • "How does this compare to previous research?"

Employee Onboarding

Documents: Handbooks, procedures, training materials Use: New hire questions, policy lookup

Example:

  • "What benefits am I eligible for?"
  • "How do I submit expense reports?"
  • "What's the dress code?"

Technical Documentation

Documents: API docs, architecture guides, runbooks Use: Developer assistance, troubleshooting

Example:

  • "How do I authenticate with the API?"
  • "What's the database schema for users?"
  • "How do I deploy to production?"

Cost Analysis

Extremely Affordable

Document SizeEmbedding CostChat Cost
10-page PDF$0.0001FREE (Groq)
100-page PDF$0.001FREE (Groq)
500-page PDF$0.005FREE (Groq)

Monthly Cost Examples

Usage LevelDocumentsQuestions/MonthTotal Cost
Light50 pages500< $0.50
Moderate500 pages5,000< $2.00
Heavy5,000 pages50,000< $10.00

Compare to: Enterprise knowledge base tools at $50-500/month

Advanced Features

Query across all uploaded documents:

"Compare the vacation policies in the US and UK handbooks"
β†’ Retrieves chunks from both documents
β†’ Synthesizes comparison answer

Conversation Memory

Maintain context across questions:

User: "What's the refund policy?"
Bot: "Refunds are available within 30 days..."

User: "What about for digital products?"
Bot: "For digital products specifically, the policy states..."

Custom Prompts

Tune the AI's response style:

System Prompt Options:
β”œβ”€β”€ Concise: Brief, bullet-point answers
β”œβ”€β”€ Detailed: Comprehensive explanations
β”œβ”€β”€ Technical: Include technical details
β”œβ”€β”€ Simple: Plain language, no jargon
└── Formal: Professional business tone

Source Highlighting

Show exactly where answers come from:

Answer with highlights:
"According to Section 4.2 of the Employee Handbook:
'[Employees are entitled to 15 days of paid vacation]
per calendar year, with [5 additional days granted]
after three years of continuous employment.'"

Security Best Practices

API Key Protection

  • Store keys in environment variables only
  • Never commit keys to version control
  • Rotate keys periodically
  • Set usage limits in OpenAI dashboard

Document Security

  • User authentication required
  • Documents isolated per user
  • Encryption at rest
  • Secure file handling

Production Checklist

  • Change JWT secret to strong random value
  • Set CORS to your domain only
  • Enable rate limiting
  • Use HTTPS everywhere
  • Monitor API usage
  • Set up database backups

Comparing Solutions

FeatureCocoding + OpenAIChatGPT PlusEnterprise RAG
Custom documentsYesLimitedYes
Source citationsYesSometimesYes
Data privacyYour serversOpenAI serversYour servers
Monthly cost< $10$20/user$1000s
CustomizationFullNoneLimited
Setup timeMinutesN/AWeeks

Getting Started Today

Build your knowledge assistant:

  1. Sign up at cocoding.ai
  2. Get OpenAI and Groq API keys
  3. Describe your RAG chatbot needs
  4. Generate your application
  5. Upload documents and start asking questions

Conclusion

The era of AI hallucinations doesn't have to be your reality. With Cocoding AI's OpenAI integration, you can build a RAG chatbot that only answers from your documentsβ€”no made-up facts, no outdated information, just accurate answers with source citations.

Whether you're building a customer support bot, internal knowledge base, research assistant, or document Q&A system, RAG technology ensures your AI is grounded in truth.

For less than the cost of a coffee per month, you can have an AI assistant that knows your documents inside and out.

Stop hallucinating. Start retrieving.


Ready to build your document-powered chatbot? Our team is here to help you create the perfect RAG solution.

Share this article

Try Cocoding AI Today