mirror of
https://github.com/neuml/txtai.git
synced 2026-10-11 21:39:55 +00:00
116 KiB
116 KiB
In [ ]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[api,graph,pipeline-train] datasetsIn [ ]:
from datasets import load_dataset
import txtai
# Load dataset
ds = load_dataset("fka/awesome-chatgpt-prompts", split="train")
def stream():
for row in ds:
yield (row["act"], f"{row['act']} {row['prompt']}")
# Build sparse keyword index
embeddings = txtai.Embeddings(content=True, graph={"approximate": False})
embeddings.index(stream())
graph = embeddings.search("Linux terminal", 5, graph=True)In [ ]:
import matplotlib.pyplot as plt
import networkx as nx
def plot(graph):
labels = {x: f"{graph.attribute(x, 'id')} ({x})" for x in graph.scan()}
options = {
"node_size": 1500,
"node_color": "#0277bd",
"edge_color": "#454545",
"font_color": "#fff",
"font_size": 9,
"alpha": 1.0
}
fig, ax = plt.subplots(figsize=(16, 5))
pos = nx.spring_layout(graph.backend, seed=0, k=0.9, iterations=50)
nx.draw_networkx(graph.backend, pos=pos, labels=labels, **options)
ax.set_facecolor("#303030")
ax.axis("off")
fig.set_facecolor("#303030")
plt.show()
plot(graph)In [ ]:
g = embeddings.graph.search("""
MATCH P=({id: "Poet"})-[*1..2]->({id: "Rapper"})
RETURN P
LIMIT 5
""", graph=True)
plot(g)In [ ]:
from txtai import LLM
llm = LLM("Qwen/Qwen3-4B-Instruct-2507")
def rag(question, text):
prompt = f"""<|im_start|>system
You are a friendly assistant. You answer questions from users.<|im_end|>
<|im_start|>user
Answer the following question using only the context below. Only include information specifically discussed.
question: {question}
context: {text} <|im_end|>
<|im_start|>assistant
"""
return llm(prompt, maxlength=4096)
context = "\n".join(g.attribute(node, "text") for node in list(g.scan()))
print(rag("What roles are similar to both a rapper and poet?", context))
The roles that are similar to both a rapper and poet are: 1. Composer: A composer creates music for various forms of art, including songs and poems. They work with different instruments and tools to bring the lyrics to life, making the music harmonious and engaging. 2. Novelist: A novelist creates captivating stories with engaging characters and plotlines. They can write in various genres, such as science fiction, romance, or historical fiction. The goal is to write a story that keeps readers engaged and entertained. 3. Movie Critic: A movie critic evaluates and reviews movies, discussing aspects like plot, themes, acting, direction, and more. They aim to express their feelings about the movie and how it impacted them, while also providing constructive criticism. 4. Motivational Speaker: A motivational speaker inspires and empowers their audience by sharing words of wisdom and encouragement. They can talk about various topics, but the goal is to make their audience feel motivated and inspired to achieve their goals.
In [ ]:
question = "What roles are most similar role to both a rapper and poet?"
context = "\n".join(x["text"] for x in embeddings.search(question, limit=6))
print(rag(question, context))The roles most similar to both a rapper and poet are the Composer and the Song Recommender. Both roles involve creating music or recommending songs based on given lyrics or themes.
In [ ]:
import json
import pickle
from txtai import Embeddings
# Create a default index
embeddings = Embeddings()
embeddings.index(["test1", "test2"])
embeddings.save("index")
# Read standard configuration
with open("index/config.json") as f:
print(json.dumps(json.load(f), sort_keys=True, default=str, indent=2))
# Read ids
with open("index/ids", "rb") as f:
print("ID List:", pickle.load(f)){
"autoid": 2,
"backend": "faiss",
"build": {
"create": "2024-02-21T16:23:26Z",
"python": "3.8.18",
"settings": {
"components": "IDMap,Flat"
},
"system": "Linux (x86_64)",
"txtai": "7.0.0"
},
"dimensions": 384,
"offset": 2,
"path": "sentence-transformers/all-MiniLM-L6-v2",
"update": "2024-02-21T16:23:26Z"
}
ID List: [0, 1]
In [ ]:
from txtai.pipeline import HFTrainer
trainer = HFTrainer()
model, _ = trainer(
"ahxt/LiteLlama-460M-1T",
[{"label": 0, "text": "sample text"}],
maxlength=16,
task="language-generation",
quantize=True,
lora=True,
)trainable params: 8,355,840 || all params: 470,041,600 || trainable%: 1.7776809541963945
0%| | 0/3 [00:00<?, ?it/s]
{'train_runtime': 0.3832, 'train_samples_per_second': 7.829, 'train_steps_per_second': 7.829, 'train_loss': 9.008923212687174, 'epoch': 3.0}
In [ ]:
%%writefile index.yml
embeddings:Overwriting index.yml
In [ ]:
!CONFIG=index.yml nohup uvicorn "txtai.api:app" &> api.log &
!sleep 90In [ ]:
import requests
requests.post("http://localhost:8000/add", json=["test"])
requests.get("http://localhost:8000/index")
print(requests.get("http://localhost:8000/count", headers={"Accept": "application/json"}).content)
print(requests.get("http://localhost:8000/count", headers={"Accept": "application/msgpack"}).content)b'0' b'\x00'
In [ ]:
import msgpack
print(msgpack.loads(requests.get("http://localhost:8000/count", headers={"Accept": "application/msgpack"}).content))0