mirror of
https://github.com/neuml/txtai.git
synced 2026-10-12 02:19:52 +00:00
12 KiB
12 KiB
In [1]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[api] datasetsIn [2]:
%%writefile app.yml
# Embeddings index
writable: true
embeddings:
hybrid: true
content: true
# LLM pipeline
llm:
path: Qwen/Qwen3-4B-Instruct-2507Writing app.yml
In [3]:
%%writefile rag.py
from fastapi import APIRouter
from txtai.api import application, Extension
class RAG(Extension):
"""
API extension
"""
def __call__(self, app):
app.include_router(RAGRouter().router)
class RAGRouter:
"""
API router
"""
router = APIRouter()
@staticmethod
@router.get("/rag")
def rag(text: str):
"""
Runs a retrieval augmented generation (RAG) pipeline.
Args:
text: input text
Returns:
response
"""
# Run embeddings search
results = application.get().search(text, 3)
context = " ".join([x["text"] for x in results])
prompt = f"""
Answer the following question using only the context below.
Question: {text}
Context: {context}
"""
return {
"response": application.get().pipeline("llm", (prompt,))
}Writing rag.py
In [4]:
!CONFIG=app.yml EXTENSIONS=rag.RAG nohup uvicorn "txtai.api:app" &> api.log &
!sleep 60In [ ]:
from datasets import load_dataset
import requests
ds = load_dataset("ag_news", split="train")
# API endpoint
url = "http://localhost:8000"
headers = {"Content-Type": "application/json"}
# Add data
batch = []
for text in ds["text"]:
batch.append({"text": text})
if len(batch) == 4096:
requests.post(f"{url}/add", headers=headers, json=batch, timeout=120)
batch = []
if batch:
requests.post(f"{url}/add", headers=headers, json=batch, timeout=120)
# Build index
index = requests.get(f"{url}/index")In [14]:
def rag(text):
return requests.get(f"{url}/rag?text={text}").json()["response"]
rag("Who is the current President?")Out [14]:
'George W. Bush'
In [15]:
rag("Who lost the presidential election?")Out [15]:
'John Kerry'
In [16]:
rag("Who won the World Series?")Out [16]:
'Boston'
In [17]:
rag("Who did the Red Sox beat to win the world series?")Out [17]:
'Cardinals'
In [18]:
rag("What major hurricane hit the USA?")Out [18]:
'Charley'
In [19]:
rag("What mobile phone manufacturer has the largest current marketshare?")Out [19]:
'Nokia'