mirror of
https://github.com/neuml/txtai.git
synced 2026-10-12 02:19:52 +00:00
92 KiB
92 KiB
In [ ]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[graph]
# Install translation pipeline dependencies for later examples
!pip install sentencepiece sacremoses staticvectorsIn [5]:
%%capture
from txtai import Embeddings
# Works with a list, dataset or generator
data = [
"US tops 5 million confirmed virus cases",
"Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
"Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
"The National Park Service warns against sacrificing slower friends in a bear attack",
"Maine man wins $1M from $25 lottery ticket",
"Make huge profits without work, earn up to $100,000 a day"
]
# Create an embeddings
embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2")In [2]:
# Create an index for the list of text
embeddings.index(data)
print("%-20s %s" % ("Query", "Best Match"))
print("-" * 50)
# Run an embeddings search for each query
for query in ("feel good story", "climate change", "public health story", "war", "wildlife", "asia", "lucky", "dishonest junk"):
# Extract uid of first result
# search result format: (uid, score)
uid = embeddings.search(query, 1)[0][0]
# Print text
print("%-20s %s" % (query, data[uid]))Query Best Match -------------------------------------------------- feel good story Maine man wins $1M from $25 lottery ticket climate change Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg public health story US tops 5 million confirmed virus cases war Beijing mobilises invasion craft along coast as Taiwan tensions escalate wildlife The National Park Service warns against sacrificing slower friends in a bear attack asia Beijing mobilises invasion craft along coast as Taiwan tensions escalate lucky Maine man wins $1M from $25 lottery ticket dishonest junk Make huge profits without work, earn up to $100,000 a day
In [3]:
# Run initial query
uid = embeddings.search("feel good story", 1)[0][0]
print("Initial: ", data[uid])
# Create a copy of data to modify
udata = data.copy()
# Update data
udata[0] = "See it: baby panda born"
embeddings.upsert([(0, udata[0], None)])
uid = embeddings.search("feel good story", 1)[0][0]
print("After update: ", udata[uid])
# Remove record just added from index
embeddings.delete([0])
# Ensure value matches previous value
uid = embeddings.search("feel good story", 1)[0][0]
print("After delete: ", udata[uid])Initial: Maine man wins $1M from $25 lottery ticket After update: See it: baby panda born After delete: Maine man wins $1M from $25 lottery ticket
In [4]:
embeddings.save("index")
embeddings = Embeddings()
embeddings.load("index")
uid = embeddings.search("climate change", 1)[0][0]
print(data[uid])Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg
In [5]:
# Create an embeddings
embeddings = Embeddings(hybrid=True, path="sentence-transformers/nli-mpnet-base-v2")
# Create an index for the list of text
embeddings.index(data)
print("%-20s %s" % ("Query", "Best Match"))
print("-" * 50)
# Run an embeddings search for each query
for query in ("feel good story", "climate change", "public health story", "war", "wildlife", "asia", "lucky", "dishonest junk"):
# Extract uid of first result
# search result format: (uid, score)
uid = embeddings.search(query, 1)[0][0]
# Print text
print("%-20s %s" % (query, data[uid]))Query Best Match -------------------------------------------------- feel good story Maine man wins $1M from $25 lottery ticket climate change Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg public health story US tops 5 million confirmed virus cases war Beijing mobilises invasion craft along coast as Taiwan tensions escalate wildlife The National Park Service warns against sacrificing slower friends in a bear attack asia Beijing mobilises invasion craft along coast as Taiwan tensions escalate lucky Maine man wins $1M from $25 lottery ticket dishonest junk Make huge profits without work, earn up to $100,000 a day
In [6]:
# Create an embeddings
embeddings = Embeddings(keyword=True)
# Create an index for the list of text
embeddings.index(data)
print(embeddings.search("feel good story"))
print(embeddings.search("lottery"))[] [(4, 0.5234998733628726)]
In [7]:
# Create embeddings with content enabled. The default behavior is to only store indexed vectors.
embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2", content=True, objects=True)
# Create an index for the list of text
embeddings.index(data)
print(embeddings.search("feel good story", 1)[0]["text"])Maine man wins $1M from $25 lottery ticket
In [8]:
# Create an index for the list of text
embeddings.index([{"text": text, "length": len(text)} for text in data])
# Filter by score
print(embeddings.search("select text, score from txtai where similar('hiking danger') and score >= 0.15"))
# Filter by metadata field 'length'
print(embeddings.search("select text, length, score from txtai where similar('feel good story') and score >= 0.05 and length >= 40"))
# Run aggregate queries
print(embeddings.search("select count(*), min(length), max(length), sum(length) from txtai"))[{'text': 'The National Park Service warns against sacrificing slower friends in a bear attack', 'score': 0.3151372969150543}]
[{'text': 'Maine man wins $1M from $25 lottery ticket', 'length': 42, 'score': 0.08329025655984879}]
[{'count(*)': 6, 'min(length)': 39, 'max(length)': 94, 'sum(length)': 387}]
In [9]:
import urllib
from IPython.display import Image
# Get an image
request = urllib.request.urlopen("https://raw.githubusercontent.com/neuml/txtai/master/demo.gif")
# Upsert new record having both text and an object
embeddings.upsert([("txtai", {"text": "txtai executes machine-learning workflows to transform data and build AI-powered semantic search applications.", "object": request.read()}, None)])
# Query txtai for the most similar result to "machine learning" and get associated object
result = embeddings.search("select object from txtai where similar('machine learning') limit 1")[0]["object"]
# Display image
Image(result.getvalue(), width=600)Out [9]:
<IPython.core.display.Image object>
In [7]:
# Create embeddings with a graph index
embeddings = Embeddings(
path="sentence-transformers/nli-mpnet-base-v2",
content=True,
functions=[
{"name": "graph", "function": "graph.attribute"},
],
expressions=[
{"name": "category", "expression": "graph(indexid, 'category')"},
{"name": "topic", "expression": "graph(indexid, 'topic')"},
],
graph={
"topics": {
"level": "first",
"categories": ["health", "climate", "finance", "world politics"]
}
}
)
embeddings.index(data)
embeddings.search("select topic, category, text from txtai")
Out [7]:
[{'topic': 'virus_confirmed_us_million',
'category': 'health',
'text': 'US tops 5 million confirmed virus cases'},
{'topic': 'collapsed_has_forming_ice',
'category': 'climate',
'text': "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg"},
{'topic': 'along_escalate_mobilises_tensions',
'category': 'world politics',
'text': 'Beijing mobilises invasion craft along coast as Taiwan tensions escalate'}]In [11]:
# Create embeddings with subindexes
embeddings = Embeddings(
content=True,
defaults=False,
indexes={
"keyword": {
"keyword": True
},
"dense": {
"path": "sentence-transformers/nli-mpnet-base-v2"
}
}
)
embeddings.index(data)In [12]:
embeddings.search("feel good story", limit=1, index="keyword")Out [12]:
[]
In [13]:
embeddings.search("feel good story", limit=1, index="dense")Out [13]:
[{'id': '4',
'text': 'Maine man wins $1M from $25 lottery ticket',
'score': 0.08329025655984879}]In [ ]:
from txtai import RAG
# Create embeddings
embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2", content=True, autoid="uuid5")
# Create an index for the list of text
embeddings.index(data)
# RAG Prompt Template
template = """
Answer the following question using the provided context.
Question:
{question}
Context:
{context}
"""
# Create and run RAG instance
rag = RAG(embeddings, "Qwen/Qwen3-0.6B", template=template, output="reference")
rag("What country is having issues with climate change?"){'answer': 'Canada is having issues with climate change.',
'reference': 'da633124-33ff-58d6-8ecb-14f7a44c042a'}In [15]:
uid = rag("What country is having issues with climate change?")["reference"]
embeddings.search(f"select id, text from txtai where id = '{uid}'")Out [15]:
[{'id': 'da633124-33ff-58d6-8ecb-14f7a44c042a',
'text': "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg"}]In [1]:
from txtai import LLM
# Default LLM is granite-4.0-350m
# Supports any LLM (Hugging Face, llama.cpp, Ollama, vLLM, OpenAI, Claude etc)
# See https://neuml.github.io/txtai/pipeline/llm/llm
llm = LLM()
llm("Say the name of 1 place to visit in Washington, DC")Out [1]:
'One of the most popular and iconic places to visit in Washington, DC is the National Mall.'
In [3]:
%%writefile embeddings.yml
# Embeddings instance
writable: true
embeddings:
path: sentence-transformers/nli-mpnet-base-v2
content: true
functions:
- {name: translation, argcount: 2, function: translation}
# Translation pipeline
translation:
# Workflow definitions
workflow:
search:
tasks:
- search
- action: translation
args:
target: fr
task: template
template: "{text}"Writing embeddings.yml
In [18]:
from txtai import Application
# Build index
app = Application("embeddings.yml")
app.add(data)
app.index()
# Run workflow
list(app.workflow("search", ["select text from txtai where similar('feel good story') limit 1"]))Out [18]:
['Maine homme gagne $1M à partir de $25 billet de loterie']
In [19]:
app.search("select translation(text, 'fr') text from txtai where similar('feel good story') limit 1")Out [19]:
[{'text': 'Maine homme gagne $1M à partir de $25 billet de loterie'}]In [2]:
%%writefile workflow.yml
llm:
path: Qwen/Qwen3-4B-Instruct-2507
workflow:
chain:
tasks:
- task: template
template: Translate text '{statement}' to {language} if the text is English, otherwise keep the original text
action: llm
- task: template
template: What language is the following text. Only print the answer? {text}
action: llmWriting workflow.yml
In [ ]:
inputs = [
{"statement": "Hello, how are you", "language": "French"},
{"statement": "Hallo, wie geht's dir", "language": "French"}
]
app = Application("workflow.yml")
list(app.workflow("chain", inputs))['French', 'German']