La generazione basata sul recupero delle informazioni è un insieme di tecniche in rapida crescita che sono state originariamente concepite come un'estensione dei large language model (LLM) ma sono sempre più viste come un paradigma alternativo che reimmagina completamente il ruolo dei modelli di AI.
Ti mostreremo come creare un motore RAG di base utilizzando il framework LlamaIndex, un LLM Mistral open-source, Jina Embeddings v2 e il database vettoriale AI-ready Qdrant.
tagRAG nel Contesto
In un sistema RAG, il ruolo del modello AI rimane centrale ma molto più limitato. Invece di rispondere ai prompt basandosi sulla sua conoscenza interna, derivata dai dati di training, gli vengono presentate le informazioni rilevanti nel prompt. Il ruolo del modello è quindi quello di comprendere e sintetizzare le informazioni in un output.
Questo sfrutta i punti di forza dei modelli AI e ne minimizza le debolezze.
Per esempio, potremmo dare al modello Mistral-Instruct il seguente prompt:
Answer the query. Please be brief, concise, and complete.
Query: Why is Taylor Swift planning to attend the Superbowl?
Answer:
Quando l'ho fatto, il modello ha risposto:
I don't have real-time information. However, as of my last update,
Taylor Swift is not officially confirmed to attend or perform at
the Superbowl. If there are any updates, I recommend checking the
latest news sources.I large language model sono costosi da aggiornare e riqualificare, quindi le loro informazioni interne non possono mai essere completamente aggiornate.
Inoltre, i large language model sono noti per "allucinare", ovvero inventare risposte plausibili che possono essere parzialmente o totalmente errate e devono essere verificate.
Answer the query. Please be brief, concise, and complete.
Query: What was Weird Al Yankovic's first Taylor Swift parody?
Answer:
Weird Al Yankovic's first Taylor Swift parody was "TMZ," a spoof
of Swift's song "Blank Space." The parody was released in 2014
as part of Yankovic's album "Mandatory Fun." The song humorously
addresses the obsession with celebrity gossip and scandals, as
reported by the tabloid news website TMZ.TMZ di Weird Al Yankovic è stato pubblicato nel 2011 nell'album Alpocalypse ed è una parodia di You Belong with Me di Swift.
La natura delle reti neurali rende l'allucinazione difficile, se non impossibile, da prevenire completamente e mina fortemente qualsiasi piano di utilizzare i modelli AI come fonti di informazione.
Nelle parole di Sam Altman, CEO di OpenAI:
"Penso che le persone commettano un grande errore quando pensano a questi modelli [LLM] come a un database. [...] Funzionerà, in un certo senso. Ma è tipo il database più costoso, più lento e meno accurato al mondo."
RAG minimizza la dipendenza dalla conoscenza interna dei fatti del mondo di un modello AI e sfrutta i suoi più grandi punti di forza: la comprensione del linguaggio naturale e la generazione fluente del linguaggio.
Prendiamo un altro esempio di una domanda a cui Mistral-Instruct non può rispondere:
Answer the query. Please be brief, concise, and complete.
Query: What is the title of Taylor Swift's next album?
Answer:
As of the time I am providing this answer, Taylor Swift has
not yet announced the title of her next album. She has released
several re-recorded albums, but the title of her next original
album remains unknown. I recommend checking her official social
media channels or website for the latest updates.Ora, un sistema RAG potrebbe avere un database di articoli di notizie recenti, o forse cercare su Internet testi relativi al titolo del prossimo album di Taylor Swift. Quindi, inserirebbe i testi che trova nel prompt.
Supponiamo che identifichi questo articolo AP come rilevante per la query e costruisca il seguente prompt:
Context information is below.
---------------------
February 6, 2024
LOS ANGELES (AP) — Forget her "Reputation." Taylor Swift has a
whole new album coming out.
Accepting the Grammy for best pop vocal album on Sunday night,
Taylor said she'd been keeping a secret for two years.
"My brand-new album comes out April 19. It's called 'The Tortured
Poets Department.' I'm going to go and post the cover right now
backstage," she announced.
And so she did.
---------------------
Given the context information and not prior knowledge, answer the query.
Please be brief, concise, and complete.
If the context information does not contain an answer to the query,
respond with "No information".
Query: What is the title of Taylor Swift's next album?
Answer:Mistral-Instruct ha risposto con:
The title of Taylor Swift's next album is 'The Tortured Poets Department'.Questo tipo di prompting riduce anche drasticamente la probabilità di allucinazioni. Per esempio:
Context information is below.
---------------------
Alpocalypse is the thirteenth studio album by American parody
musician "Weird Al" Yankovic, released on June 21, 2011.
Track List
1. Perform This Way (Parody of "Born This Way" by Lady Gaga)
2. CNR
3. TMZ (Parody of "You Belong with Me" by Taylor Swift)
4. Skipper Dan
5. Polka Face (Polka medley including songs by artists such as
Lady Gaga, Justin Bieber, Britney Spears, Ke$ha, and others)
6. Craigslist
7. Party in the CIA (Parody of "Party in the U.S.A." by Miley
Cyrus)
8. Ringtone
9. Another Tattoo (Parody of "Nothin' on You" by B.o.B featuring
Bruno Mars)
10. If That Isn't Love
11. Whatever You Like (Parody of "Whatever You Like" by T.I.)
12. Stop Forwarding That Crap to Me
---------------------
Given the context information and not prior knowledge, answer the
query. Please be brief, concise, and complete.
If the context information does not contain an answer to the query,
respond with "No information".
Query: What was Weird Al Yankovic's first Taylor Swift parody, what
year was it released, and what song was he parodying?
Answer:
Weird Al Yankovic's first Taylor Swift parody was "TMZ," and it was
released in 2011. He was parodying "You Belong with Me" by Taylor
Swift.tagAnatomia di un sistema RAG
Un sistema RAG ha, come minimo, due componenti:
- Un modello AI generativo.
- Un sistema di recupero delle informazioni.
In questo articolo, useremo Mistral-Instruct come modello AI generativo e vi accederemo tramite la Hugging Face Inference API. Useremo il database vettoriale Qdrant e Jina Embeddings insieme per il sistema di recupero delle informazioni.
Come fonte di dati, useremo il National Artificial Intelligence Research and Development Strategic Plan 2023 Update, pubblicato a maggio 2023 dal National Science and Technology Council, un organo che consiglia il Presidente degli Stati Uniti su questioni scientifiche e tecniche. Questo documento di circa 25.000 parole è un documento di politica e pianificazione strategica per la politica e lo sviluppo dell'AI americana.
È anche un classico documento governativo "troppo lungo, non l'ho letto". La maggior parte è molto noiosa e, a meno che non si abbia un interesse o un coinvolgimento diretto in questo settore, probabilmente non lo leggerete. Ma potreste comunque voler sapere cosa dice.
Questo articolo ti guiderà attraverso i passaggi per creare un sistema RAG in grado di rispondere a domande sul testo e sui suoi contenuti.
tagInstallare i Prerequisiti
Prima di tutto, assicurati di avere installate tutte le librerie Python pertinenti. Nel tuo ambiente Python, esegui quanto segue:
pip install llama-index qdrant-client
pip install pdfminer.six llama-index-vector-stores-qdrant
pip install llama-index-llms-openai llama-index-embeddings-jinaai
pip install llama-index-llms-huggingface "huggingface_hub[inference]"Useremo LlamaIndex per costruire un sistema RAG attorno al modello linguistico Mistral-Instruct e pdfminer.six per elaborare il file PDF in un vector store Qdrant.
tagConnettersi a Mistral-Instruct tramite l'API Inference di Hugging Face
Per prima cosa, configuriamo il LLM. Avrai bisogno di accedere all'API Inference di Hugging Face, incluso un token di accesso. Se hai un account Hugging Face, puoi ottenerne uno dalla pagina delle impostazioni del tuo account.
Se non hai un account, prima creane uno, poi crea un token di accesso.
Inserisci il tuo token in una variabile per uso futuro:
hf_inference_api_key = '<your HuggingFace Inference API token>'Successivamente, costruiamo un template per il prompt:
from llama_index.core import PromptTemplate
qa_prompt_tmpl = (
"Context information is below.\n"
"---------------------\n"
"{context_str}\\n"
"---------------------\n"
"Given the context information and not prior knowledge, "
"answer the query. Please be brief, concise, and complete.\n"
"If the context information does not contain an answer to the query, "
"respond with \"No information\".\n"
"Query: {query_str}\n"
"Answer: "
)
qa_prompt = PromptTemplate(qa_prompt_tmpl)Questo template istruisce il LLM a utilizzare solo le informazioni di contesto fornite nel prompt per rispondere alle domande. Questo prompt ha funzionato bene per noi nel lavorare con Mistral-Instruct, ma puoi sperimentare con altre formulazioni per vedere cosa funziona meglio per il tuo caso d'uso.
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
mixtral_llm = HuggingFaceInferenceAPI(
model_name="mistralai/Mixtral-8x7B-Instruct-v0.1",
token=hf_inference_api_key
)Infine, creiamo e inizializziamo un oggetto per il framework LlamaIndex che mantiene la connessione a Mistral-Instruct. Il codice seguente proviene dal post precedente sulla creazione di sistemi RAG usando LlamaIndex.
Questo mette la connessione al LLM Mistral nella variabile mistral_llm.
tagRecupero delle Informazioni con Qdrant e Jina Embeddings
Per configurare il sistema di recupero, avrai bisogno di una chiave API di Jina Embeddings. Puoi ottenerne una gratuitamente con un budget prepagato di 1 milione di token sul sito web di Jina Embeddings.

Inserisci la tua chiave Jina Embeddings in una variabile per uso futuro:
jina_emb_api_key = "<your Jina Embeddings API key>"Quindi, crea un oggetto connettore usando LlamaIndex per il server Jina Embeddings, selezionando specificamente il modello monolingue inglese:
from llama_index.embeddings.jinaai import JinaEmbedding
jina_embedding_model = JinaEmbedding(
api_key=jina_emb_api_key,
model="jina-embeddings-v2-base-en",
)tagCaricamento dei dati testuali
Successivamente, caricheremo il documento e lo divideremo in paragrafi. Prima, scarichiamo il PDF dal sito della Casa Bianca nella variabile pdf_data:
import urllib.request
uri = "https://www.whitehouse.gov/wp-content/uploads/2023/05/National-Artificial-Intelligence-Research-and-Development-Strategic-Plan-2023-Update.pdf"
pdf_data = urllib.request.urlopen(uri).read()Poi, elaboreremo il PDF pagina per pagina, estraendo il testo e suddividendolo in paragrafi separando su doppie interruzioni di riga. Questi vengono memorizzati nella lista text_paras:
import regex as re
from io import BytesIO, StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
text_paras = []
parser = PDFParser(BytesIO(pdf_data))
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
for page in PDFPage.create_pages(doc):
output_string = StringIO()
device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
interpreter.process_page(page)
page_text = output_string.getvalue()
text_paras.extend(re.split(r'\n\s*\n', page_text))
Verifica che tutto sia stato caricato:
assert len(text_paras) == 615Successivamente, convertiremo questa lista di testi brevi in oggetti Document di LlamaIndex:
from llama_index.core.readers import StringIterableReader
rag_docs = StringIterableReader().load_data(text_paras)E puoi ispezionare il testo:
print(rag_docs[0].text)Risultato:
NATIONAL ARTIFICIAL INTELLIGENCE
RESEARCH AND DEVELOPMENT
STRATEGIC PLAN
2023 UPDATEtagConfigurazione di un Database Vettoriale Qdrant
In questo articolo, useremo il Qdrant Vector Search Cloud per implementare il database del sistema RAG. Il piano gratuito di Qdrant include 1GB di storage, che è più che sufficiente per questo tutorial.
Dovrai creare un account sul sito web di Qdrant Cloud prima di continuare.

Una volta che hai un account e hai effettuato l'accesso, dovrai creare un cluster. Segui le istruzioni "quick start" sul sito web di Qdrant per configurare un cluster gratuito e ottenere un'API e il nome del server host Qdrant.

Memorizza la chiave e l'hostname in variabili:
qdrant_api_key = "<your API key>"
qdrant_server = "https://<your server>"Successivamente, dovremo importare i componenti rilevanti dai pacchetti qdrant_client e llama_index:
import qdrant_client
from llama_index.vector_stores.qdrant import QdrantVectorStore
client = qdrant_client.QdrantClient(qdrant_server, api_key=qdrant_api_key)
vector_store = QdrantVectorStore(client=client, collection_name="NTSC")Questo crea una collezione chiamata NTSC nel tuo cluster gratuito.
Puoi consultare la documentazione di Qdrant per informazioni sulla costruzione di un archivio dati locale in memoria o su disco e sull'hosting della tua istanza server Qdrant in un container docker tramite API web.
tagCompletare il sistema RAG
Ora assembleremo questi componenti in un sistema RAG completo utilizzando il codice boilerplate per LlamaIndex:
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.retrievers import VectorIndexRetriever
from llama_index.core.storage.storage_context import StorageContext
from llama_index.core import (
VectorStoreIndex,
ServiceContext,
get_response_synthesizer,
)
# set up the service and storage contexts
service_context = ServiceContext.from_defaults(
llm=mixtral_llm, embed_model=jina_embedding_model
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# create an index
index = VectorStoreIndex.from_documents(
rag_docs, storage_context=storage_context, service_context=service_context
)
# configure retriever
retriever = VectorIndexRetriever(
index=index,
similarity_top_k=2,
)
# configure response synthesizer
response_synthesizer = get_response_synthesizer(
service_context=service_context,
text_qa_template=qa_prompt,
response_mode="compact",
)
# assemble query engine
query_engine = RetrieverQueryEngine(
retriever=retriever,
response_synthesizer=response_synthesizer,
)
Questo sistema utilizzerà Jina Embeddings per indicizzare i paragrafi dalla nostra fonte di testo e inserirà le due migliori corrispondenze nel contesto di ogni prompt. Per passare ad esempio alle tre migliori corrispondenze, basta modificare l'inizializzazione di VectorIndexRetriever sopra per avere un parametro similarity_top_k diverso:
# configure retriever
retriever = VectorIndexRetriever(
index=index,
similarity_top_k=3,
)Ora il sistema è pronto per l'uso.
tagInterrogare un Documento
Proviamo una query semplice:
response = query_engine.query("""
What is the Biden Administration's policy with regard to AI?
""")
print(response.response)Il risultato (il tuo potrebbe non essere identico):
The Biden Administration prioritizes responsible AI systems that
are ethical, trustworthy, and safe, and serve the public good.
The Administration has committed to substantial funding for AI
R&D, and has established the National AI Initiative Office to
coordinate AI activities across the federal government.
The Administration's AI policy focuses on developing evaluative
techniques for AI, workforce development, public-private
partnerships, and international collaboration in AI research.O qualcosa di più specifico:
response = query_engine.query("""
What protections does the AI Bill of Rights propose to offer?
""")
print(response.response)The AI Bill of Rights proposes five core protections: Safe and
Effective Systems; Algorithmic Discrimination Protections; Data
Privacy; Notice and Explanation; and Human Alternatives,
Consideration, and Fallback.O anche molto specifico:
response = query_engine.query("Who is Kei Koizumi?")
print(response.response)Kei Koizumi is the Principal Deputy Director for Policy at the Office
of Science and Technology Policy (OSTP).Puoi anche fare domande più fantasiose:
response = query_engine.query("""
What rights will AI's receive under President Biden's proposed
AI Bill of Rights?
""")
print(response.response)The proposed AI Bill of Rights does not grant rights to AI systems, but
rather outlines principles to ensure that AI technologies are
developed and used in a manner that respects human rights and values.
The principles include safety, transparency, fairness, disclosure,
data privacy, non-discrimination, and the ability for individuals to
opt out of certain AI systems.response = query_engine.query("""
Why is President Biden's proposing an AI Bill of Rights?
Does AI really need rights?
""")
print(response.response)President Biden's proposed AI Bill of Rights aims to ensure that AI
technologies are developed and used ethically, legally, and with
societal considerations in mind. The Bill of Rights is not granting
"rights" to AI, but rather setting guidelines for the responsible
development and deployment of AI systems to protect individuals and
communities from potential negative impacts.response = query_engine.query("""
Has Donald Trump weighed in on AI?
Will he Make Humans Great Again?
""")
print(response.response)
No information. The context information does not mention Donald
Trump's views on AI.tagJina AI e Qdrant
La finestra di contesto di 8k token di Jina Embeddings lo rende particolarmente adatto alla generazione aumentata dal recupero perché può lavorare con blocchi di testo molto più grandi. Mentre altre applicazioni RAG spesso devono memorizzare singole frasi o coppie di frasi, in questo tutorial abbiamo potuto utilizzare interi paragrafi senza preoccuparci della loro dimensione.
Questo riduce il numero di elementi di testo che devono essere memorizzati per trasportare le stesse informazioni, abbassando i costi di calcolo, risparmiando memoria e rendendo il recupero più veloce.
Il database vettoriale di Qdrant è semplice da configurare, veloce ed economico e, come hai visto, bastano poche righe di Python per integrarlo in un sistema RAG.
Per saperne di più sul database pronto per l'AI di Qdrant e sulle offerte cloud, puoi visitare il loro sito web.

tagContattaci
Jina AI si impegna a portare tecnologie di AI affidabili ed economiche alle imprese di ogni dimensione e tipo. Ci piacerebbe sentire i tuoi casi d'uso e aiutarti a integrare l'AI nei tuoi processi aziendali. Per maggiori informazioni sulle offerte di Jina AI e per contattarci, visita il sito web di Jina AI o unisciti alla nostra community su Discord.











