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

推荐订阅源

Google DeepMind News
Google DeepMind News
SecWiki News
SecWiki News
博客园 - Franky
V
V2EX
罗磊的独立博客
美团技术团队
大猫的无限游戏
大猫的无限游戏
Simon Willison's Weblog
Simon Willison's Weblog
S
Securelist
C
Cyber Attacks, Cyber Crime and Cyber Security
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
Webroot Blog
Webroot Blog
N
News | PayPal Newsroom
博客园 - 司徒正美
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cloudbric
Cloudbric
AI
AI
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
Recent Commits to openclaw:main
Recent Commits to openclaw:main
月光博客
月光博客
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Troy Hunt's Blog
Project Zero
Project Zero
Schneier on Security
Schneier on Security
TaoSecurity Blog
TaoSecurity Blog
博客园 - 【当耐特】
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
P
Privacy & Cybersecurity Law Blog
博客园_首页
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
J
Java Code Geeks
P
Proofpoint News Feed

GoPenAI - Medium

Group Relative Policy Optimization (GRPO) Your agent fleet can build trustworthy state with their own keys Epistemic Backbone #1: Why AI Systems Need Shared Memory, Not Just Models Transformers Beyond NLP: Fun and Trendy Use Cases Your First Transformer: The Road to Attention Part 4. From Seats to Agents: Early Evidence on the Future of Work in the Agentic AI Era The AI Trust Gap: Why Faster Code Is Creating Less Confidence From Bytes to BPE: A From-Scratch Tour of LLM Tokenization ️ Grok Voice Think Fast 1.0: The First Voice AI That Actually Thinks While Talking .NET 10.0.7 OOB Security Update: The Kind of Bug You Can’t Afford to Ignore Writing Custom Pallas Kernels for vLLM on TPU — A Step-by-Step Guide Contrastive Learning Day 39: Advanced Ensemble Learning Techniques — Stacking, Random Forest, AdaBoost, and Gradient… Localization: Beyond Translation, Into the Territory of Growth Hacking Can We Translate Our Sentiments? Training the first modern architecture encoder for South Slavic languages What Is Data, and Why Does It Matter for AI? A Complete Guide to Prompt Engineering: Best Practices & Tips DeepSeek TileKernels: The Hidden Tech Making AI Models Insanely Fast Can AI Growth Really Become Economic Growth? Evaluating API Test Generation Across Leading AI Tools Pin Clustering in .NET MAUI Maps: Finally Making Maps Usable (With Example) Unsupervised Learning What is an LLM? Tokens, Context Window, and Why They Matter Build a reactive AI agent harness — Part 1. Conversation. From Hallucination to Citation… CLI Coding Agents Tierlist Google Deep Research Max: Build Autonomous AI Research Agents Hermes Agent vs Every AI Assistant: Why Memory Changes Everything I Watched a Startup Burn $1,200 in a Week. The Culprit Was 800 Tokens. Fine-Tuning LLMs Explained: How Companies Teach AI to Think Like Them ️ xAI Just Dropped the Fastest Voice AI Ever Essential Code Patterns in Generative Artificial Intelligence Exploratory Data Analysis: A basic Understanding Day 36: Introduction to Ensemble Learning — Why Multiple Models Perform Better than One Concept to build a Student IQ — Agent Framework Workflow + Microsoft Foundry Agents 20 API Concepts Every Software Engineer Should Know From Human-Feedback Control to Declared No-Meta Agency: A Scientific Exposition GPT-5.5 Is Here — And It’s Not Just Smarter… It Works For You Test Cases in Data Science Projects: A Basic Understanding Q, K, V: The Three Matrices That Quietly Run Every Modern LLM Artificial Intelligence UseCases in Testing A Comprehensive Guide for Beginners into Artificial Intelligence Day 33: DBSCAN — Clustering Beyond Boundaries The Attention Breakthrough — How Language Models Finally Learned to Focus I rebuilt Strava (and Strava Premium) for fun, and now I want your feedback .NET April 2026 Updates: The Kind of Release You Should Never Ignore .NET 11 Preview 3: Small Changes That Quietly Improve Everything ChatGPT Images 2.0 Isn’t an Update — It’s a Revolution Claude Mythos: The AI Model Too Powerful to Release Basic Understanding of Key Parameters: Artificial Intelligence Part-2 Kimi K2.6: The Most Powerful Open-Source LLM Is Here (And It’s Not What You Expect) Elephant in the room — Openrouter’s Elephant-Alpha I Built a RAG System From Scratch in 4 Weeks — Here’s Everything I Learned Graphify: Build a Knowledge Graph From Your Entire Codebase — Without Sending Your Code to Anyone Deep Learning Interview Q&A Part -1 Deep Learning Interview Q&A Part -2 Anthropic Just Launched Claude Routines Microsoft Just Dropped a Cheaper AI Image Model — And This Changes Everything Building a Local-first Knowledge Management System with LLM and Obsidian Basic Understanding of Key Parameters: Artificial Intelligence Part-1 Copy These 7 Prompt Formulas and Never Struggle With AI Again Claude Opus 4.7 vs Mythos — The Benchmark Truth Nobody Explains The ROI on Reading is Broken. I Built an AI Learning OS to Fix It Beyond Scatter: Metrics That Allows to Measure Creativity in LLMs. Banish the RNN: The Road To Attention Part 3. You Typed a Few Words. The AI Painted a World. Here’s Exactly How. 46% of Code Is Now AI-Generated. The Other 54% Is the Part That Will Get You Fired. Claude Opus 4.7: The Quiet Leap Toward Autonomous AI Workflows Is bitnet.cpp the Game Changer for Running LLMs on Your Laptop? Machine Learning Algorithms : A Comprehensive Guide Building REPI (Real Estate Pain Point Intelligence Platform) — From Scraping 5 Noisy Data Sources… Hermes Agent: The AI That Actually Remembers You (Not Another OpenClaw) MiniMax M2.7 Just Went Open-Weight — Run a Powerful AI Agent on Your Own Machine XML Is Everywhere — You Just Never Noticed It The Missing Infrastructure for GUI Agents: Unpacking the ClawGUI Framework Wayfarer: Building an AI-Powered Travel Intelligence Platform with Agentic Orchestration, Bayesian… Attention from First Principles: DeltaNet Project Glasswing and Claude Mythos Preview: Anthropic’s Bet on AI-Powered Cyber Defense Deep Learning-Based Binary Classification of Forest Fires GenAI Q and A Interview Questions Part -2 How Google Maps Knows There Is Traffic Before You Even Reach There 5 AI Freelance Services Clients Actually Pay For I Accidentally Built a World Where AIs Govern Themselves (And I Have No Idea What’s Happening… Meta’s “Compute Desk” Is the Tell: When AI Stops Being Software and Becomes Resource Strategy The Last Human Stronghold Falls: Inside the GrandCode Multi-Agent System ASP.NET Core 2.3 End of Support: What It Really Means for Developers Andrej Karpathy’s LLM Wiki: The Idea That Could Kill RAG Forever I Built an Open-Source Kubernetes Control Plane for AI Agents. Here’s What It Took. GLM-5.1 Just Changed Coding Forever — The AI That Gets Smarter the Longer It Works Goodbye Llama? Meta Just Dropped Muse Spark — And It Changes Everything Anthropic Accidentally Leaked All of Claude Code’s Source Code Stop Sending Your Data to the Cloud — Build This Instead Today Physical AI Cosmos Reason2 2B World Model inference in Azure Machine Learning LangChain vs LlamaIndex vs LangGraph: The Difference Nobody Explains Clearly Cloud Services Interview Q and A Part- 1 Cloud Services Interview Q and A Part- 2 Gemma-4 — disabling thinking with gemma-4–26b-a4b-it Mixture of Experts Explained: The Secret Architecture Making AI 10x Smarter Without Using 10x More… Diffusion Models Demystified: How AI Paints Masterpieces from Pure Noise (No Math Needed)
RAG Made Simple: How AI Finds the Right Answers
Jigar Joshi · 2026-04-28 · via GoPenAI - Medium
Photo by Steve A Johnson on Unsplash RAG Made Simple: How AI Finds the Right Answers As AI becomes common in enterprises, responses need to be accurate and grounded in business data. Traditional LLMs can be generic or inaccurate because they rely on pretrained knowledge. RAG solves this by retrieving relevant information from trusted sources first, then using it to generate a better response. This code builds a simple RAG pipeline. It loads text from knowledge.txt, splits it into chunks, creates embeddings, stores them in FAISS for search, and uses FLAN-T5 to answer questions using the retrieved context. Step-by-Step Breakdown: Imports and Data Loading : Imports necessary libraries (FAISS for vector search, NumPy, text splitter, embeddings, and transformers). Reads the knowledge base text from knowledge.txt. Text Chunking : Uses RecursiveCharacterTextSplitter to divide the text into 300-character chunks with 50-character overlap, then prints the chunks for inspection. Embedding Generation : Loads the ‘all-MiniLM-L6-v2’ SentenceTransformer model (fast, local, 384-dimensional embeddings) and encodes all chunks into vectors. Vector Store Setup : Creates a FAISS IndexFlatL2 for exact L2 distance similarity search, adds the chunk embeddings (converted to float32), and confirms the index size. RAG Pipeline Function (answer_question): Retrieve: Embeds the user query, searches FAISS for the top 3 most similar chunks. Augment: Combines retrieved chunks into a context and creates a prompt instructing the model to answer using only that context. Generate: Tokenizes the prompt, generates a response using FLAN-T5 (seq2seq model) with constraints (300 max new tokens, temperature 0.7), and decodes the output. 6. Execution : In the main block, prompts for a user question and calls the function to generate an answer. The pipeline ensures answers are grounded in the provided knowledge, with fallback for unknown information. It runs entirely locally (no API calls). For testing, run the script and input a query. import faiss import numpy as np from langchain_text_splitters import RecursiveCharacterTextSplitter from sentence_transformers import SentenceTransformer with open("data/ITSupportKnowledge.txt", "r", encoding="utf-8") as f: knowledge = f.read() text_splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50, length_function=len) chunks = text_splitter.split_text(knowledge) print(f"Total chunks: {len(chunks)}") for i, chunk in enumerate(chunks): print(f"--- Chunk {i+1} ---\n{chunk}\n") # 1. Load the embedding model # 'all-MiniLM-L6-v2' is a fantastic, fast, and small model. # It runs 100% on your local machine. model = SentenceTransformer('all-MiniLM-L6-v2') # 2. Embed all our chunks # This will take a moment as it "reads" and "understands" each chunk. chunk_embeddings = model.encode(chunks) print(f"Shape of our embeddings: {chunk_embeddings.shape}") #Step 4: Vector Store with FAISS #We have our vectors. Now we need a database to store them in a way we can search by similarity. It is where FAISS comes in. Don’t be intimidated; it’s just a few lines of code: # Convert to float32 and normalize for cosine similarity search chunk_embeddings = np.array(chunk_embeddings).astype("float32") faiss.normalize_L2(chunk_embeddings) # Get the dimension of our vectors (e.g., 384) d = chunk_embeddings.shape[1] # 1. Create a FAISS index # IndexFlatIP is used with normalized vectors for cosine similarity search. index = faiss.IndexFlatIP(d) # 2. Add our chunk embeddings to the index index.add(chunk_embeddings) print(f"FAISS index created with {index.ntotal} vectors.") # Step 5: Retrieve, Augment, Generate from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # 1. Load a seq2seq model instead of pipeline('text-generation') tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base") generator = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base") # --- This is our RAG pipeline function --- def answer_question(query): # 1. RETRIEVE # Embed the user's query query_embedding = model.encode([query]).astype("float32") faiss.normalize_L2(query_embedding) # Search the FAISS index for the top k (e.g., k=3) most similar chunks k = 3 distances, indices = index.search(query_embedding, k) # Get the actual text chunks from our original 'chunks' list retrieved_chunks = [chunks[i] for i in indices[0]] context = "\n\n".join(retrieved_chunks) # 2. AUGMENT # This is the "magic prompt." We combine the retrieved context # with the user's query. prompt_template = f""" Answer the following question using only the provided context. Give a short, clear answer in 2 to 3 sentences. Do not repeat information. If the answer is not in the context, say exactly: I don't have that information. Context: {context} Question: {query} Answer: """ # 3. GENERATE # Feed the augmented prompt to our generative model inputs = tokenizer(prompt_template, return_tensors="pt", truncation=True, max_length=768) outputs = generator.generate( **inputs, max_new_tokens=300, temperature=0.7, repetition_penalty=1.2, no_repeat_ngram_size=3 ) answer = tokenizer.decode(outputs[0], skip_special_tokens=True).strip() answer = answer.split("\n")[0].strip() print("Retrieved indices:", indices[0]) print("Scores:", distances[0]) print(f"--- CONTEXT ---\n{context}\n") return answer if __name__ == "__main__": query = input("Ask a question: ") response = answer_question(query) print("Answer:", response) RAG Pipeline Summary: Loads IT support knowledge → splits into 300-char chunks → embeds locally with SentenceTransformer → stores in FAISS index using cosine similarity. When asked a question, it retrieves the 3 most relevant chunks, augments them into a prompt, and generates a 2–3 sentence answer using FLAN-T5 (local model). Everything runs offline — no API calls. RAG Made Simple: How AI Finds the Right Answers was originally published in GoPenAI on Medium, where people are continuing the conversation by highlighting and responding to this story.