AI Hints
Home›RAG Tutorial›Tables, Databases and Long Documents
RAG · Lesson 89 of 120

Two Sources

Documents and a database.

⏱ 2 min read▶ Video at 1:27:34🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

A customer asks, where is my order? That's not in the help centre. It's in the orders database. A good assistant searches documents for policies, and queries the database for live data.

Two Sources
From the video: Two Sources
  • Policies in documents
  • Orders in a database
  • Use both

Orders from SQLite

We make a small orders table in SQLite. Order status looks up one order by its number. Search help centre searches the policies, as before. Both are tools an agent can call.

two_sources.pypython
import sqlite3
from langchain.tools import tool
from rag_kit import load_docs, make_chunks, Index

db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE orders (id INT, status TEXT)")
db.executemany("INSERT INTO orders VALUES (?, ?)", [(1042, "shipped"), (1043, "packing")])
index = Index(make_chunks(load_docs()))

@tool
def order_status(order_id: int) -> str:
    """Look up the status of an order by its number."""
    row = db.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()
    return row[0] if row else "not found"

@tool
def search_help_centre(query: str) -> str:
    """Search Northwind's help centre for policies."""
    return "\n".join(c["text"] for s, c in index.search(query))

Asking about both

We create the agent with both tools, and ask about an order and the returns policy in one message. Run it. The agent used both tools, one for the order, one for the policy.

ask_both.pypython
from langchain.agents import create_agent
from two_sources import order_status, search_help_centre

agent = create_agent("google_genai:gemini-flash-lite-latest",
                     tools=[order_status, search_help_centre],
                     system_prompt="Use the tools. Be brief.")
q = "Has order 1042 shipped? And can I return it if I change my mind?"
out = agent.invoke({"messages": [{"role": "user", "content": q}]})

print("tools used:", [m.name for m in out["messages"] if m.type == "tool"])
print(out["messages"][-1].text)
Output
tools used: ['order_status', 'search_help_centre']
Yes, order 1042 has shipped.

You can return it if you change your mind—just log in to your account, open the order,
and select "Return an item" to start the process. Refunds are issued to the original
payment method within 7 working days of the item arriving back at the warehouse.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses two_sources.py
import sqlite3
from langchain.tools import tool
from rag_kit import load_docs, make_chunks, Index

db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE orders (id INT, status TEXT)")
db.executemany("INSERT INTO orders VALUES (?, ?)", [(1042, "shipped"), (1043, "packing")])
index = Index(make_chunks(load_docs()))

@tool
def order_status(order_id: int) -> str:
    """Look up the status of an order by its number."""
    row = db.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()
    return row[0] if row else "not found"

@tool
def search_help_centre(query: str) -> str:
    """Search Northwind's help centre for policies."""
    return "\n".join(c["text"] for s, c in index.search(query))

Summary

Search documents for policies, and query a database for live data. An agent can choose between them. Next, long documents.

Key takeaways
  • Documents: policies
  • Database: live data
  • Agent chooses
Next up: Long Documents — summaries as an index