惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
D
DataBreaches.Net
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
GbyAI
GbyAI
美团技术团队
云风的 BLOG
云风的 BLOG
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
宝玉的分享
宝玉的分享
阮一峰的网络日志
阮一峰的网络日志
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
U
Unit 42
P
Proofpoint News Feed
V
V2EX

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Build a RAG System with Claude & ChatGPT APIs
Gate of AI · 2026-06-26 · via DEV Community

Gate of AI

 > 🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here.

<span>Tutorial</span>
<span>Intermediate</span>
<span>⏱ 45 min read</span>
<span>© Gate of AI 2026-06-24</span>

Learn to build a smart, retrieval-augmented generation system using Claude and ChatGPT APIs to leverage the best of both models for enhanced AI interactions.

Prerequisites


  • Node.js v18.0 or higher
  • OpenAI API key and Anthropic API key
  • Intermediate programming skills in JavaScript

What We're Building

In this tutorial, we will build a Retrieval-Augmented Generation (RAG) system that combines the capabilities of Claude and ChatGPT APIs. This system will efficiently fetch relevant data from a document repository and generate contextually rich responses using advanced language models.

The final application will allow users to input queries, retrieve pertinent information from a pre-indexed document set, and use AI models to generate comprehensive answers. This integrated approach offers robust performance in applications requiring high accuracy and relevance, such as customer support systems and research assistants.

Setup and Installation

We will begin by setting up our development environment and installing necessary libraries. This involves setting up Node.js and installing the required SDKs for accessing the APIs.


npm install openai anthropic dotenv

Next, we'll configure our environment variables to securely store our API keys. Create a .env file in your project root and add the following variables:



OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key

Step 1: Setting Up the Document Repository

First, we need to establish a document repository that our RAG system can query. We'll use a simple JSON file to simulate this repository. Ensure the data is structured for quick access and relevance scoring.



const fs = require('fs');
const documents = JSON.parse(fs.readFileSync('documents.json', 'utf8'));

function getRelevantDocuments(query) {
// Simple keyword matching for relevance
return documents.filter(doc => doc.text.includes(query));
}

module.exports = { getRelevantDocuments };

This code reads a JSON file containing our documents and filters them based on the query. The getRelevantDocuments function will be used later to fetch relevant documents for any given query.

Step 2: Integrating Claude and ChatGPT APIs

Next, we'll set up the integration with Claude and ChatGPT APIs to process and generate responses. This involves configuring both APIs and establishing a connection to send and receive data.



require('dotenv').config();
const { OpenAI } = require('openai');
const { Anthropic } = require('anthropic');

const openAIClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const anthropicClient = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

async function generateResponseWithClaude(prompt) {
const response = await anthropicClient.chat.completions.create({
model: "claude-3-5-sonnet-20241022",
messages: [{ role: "user", content: prompt }]
});
return response.data.choices[0].message.content;
}

async function generateResponseWithChatGPT(prompt) {
const response = await openAIClient.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: prompt }]
});
return response.data.choices[0].message.content;
}

module.exports = { generateResponseWithClaude, generateResponseWithChatGPT };

This code establishes connections to both APIs using the modern SDKs. It defines functions to send a prompt to each service and receive a generated response, which will be used to produce the final answer.

Step 3: Building the Query Handling Logic

We'll now build the core logic to handle user queries. This involves retrieving relevant documents and using our integrated AI functions to generate a cohesive response.



const { getRelevantDocuments } = require('./documentRepository');
const { generateResponseWithClaude, generateResponseWithChatGPT } = require('./aiIntegrations');

async function handleUserQuery(query) {
const relevantDocs = getRelevantDocuments(query);
const combinedContext = relevantDocs.map(doc => doc.text).join('\n');
const prompt = Based on these documents:\n${combinedContext}\nAnswer the following question: ${query};

const claudeResponse = await generateResponseWithClaude(prompt);
const chatGPTResponse = await generateResponseWithChatGPT(prompt);

return {
claude: claudeResponse,
chatGPT: chatGPTResponse
};
}

module.exports = { handleUserQuery };

This function combines document retrieval and AI processing to form a complete query handling mechanism. It gathers context from relevant documents and sends it to both Claude and ChatGPT for response generation, allowing you to compare or combine their outputs as needed.

⚠️ Common Mistake: Ensure your environment variables are correctly set up and accessible. Misconfigured keys will lead to authentication errors with the APIs.

Testing Your Implementation

Once the setup is complete, it's crucial to test your application to ensure everything is functioning as expected. You can create a simple script to simulate user queries and verify the responses.



const { handleUserQuery } = require('./queryHandler');

(async () => {
const query = "How does the RAG system work?";
const responses = await handleUserQuery(query);

console.log("Claude's response:", responses.claude);
console.log("ChatGPT's response:", responses.chatGPT);
})();

Running this script should output responses from both Claude and ChatGPT, allowing you to assess their quality and relevance based on the provided document context.

What to Build Next


  • Integrate a user interface using React to make the RAG system interactive and user-friendly.
  • Add a feedback mechanism to improve the relevance and quality of the responses based on user input.
  • Implement advanced natural language processing techniques to enhance document retrieval accuracy.