mirror of
https://github.com/neuml/txtai.git
synced 2026-10-12 02:19:52 +00:00
13 KiB
13 KiB
In [1]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[pipeline-llm]In [7]:
from txtai import Embeddings, RAG, LLM
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 embeddings
embeddings = Embeddings(content=True, autoid="uuid5")
# Create an index for the list of text
embeddings.index(data)
# Create LLM with llama.cpp - GGUF file is automatically downloaded
llm = LLM("unsloth/Qwen3-4B-Instruct-2507-GGUF/Qwen3-4B-Instruct-2507-Q4_K_M.gguf", verbose=True)
template = """<|im_start|>system
You are a friendly assistant. You answer questions from users.<|im_end|>
<|im_start|>user
Find the best matching text in the context for the question. The response should be the text from the context only.
Question:
{question}
Context:
{context}
Text:
<|im_end|>
<|im_start|>assistant
"""
# Create and run RAG instance
rag = RAG(embeddings, llm, output="reference", separator="\n", template=template)
result = rag("Tell me about someone lucky")
print("ANSWER:", result["answer"])
print("REFERENCE:", embeddings.search("select id, text from txtai where id = :id", parameters={"id": result["reference"]}))
ANSWER: Maine man wins $1M from $25 lottery ticket
REFERENCE: [{'id': '37e5fae7-74c2-5f1c-bf69-2962dd7470d1', 'text': 'Maine man wins $1M from $25 lottery ticket'}]
In [14]:
# Hugging Face Inference API
llm = LLM("huggingface/roneneldan/TinyStories-1M")
print(llm("The cat and the dog.", maxlength=5))They are friends.
In [4]:
%%capture
!pip install mamba-ssm
# Link CUDA libraries into environment
!export LC_ALL="en_US.UTF-8"
!export LD_LIBRARY_PATH="/usr/lib64-nvidia"
!export LIBRARY_PATH="/usr/local/cuda/lib64/stubs"
!ldconfig /usr/lib64-nvidiaIn [5]:
import torch
from transformers import AutoTokenizer
from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
from txtai.pipeline import Generation
class MambaGeneration(Generation):
def __init__(self, path, template=None, **kwargs):
super().__init__(path, template, **kwargs)
self.tokenizer = AutoTokenizer.from_pretrained(path)
self.tokenizer.eos_token = "<|endoftext|>"
self.tokenizer.pad_token = self.tokenizer.eos_token
self.model = MambaLMHeadModel.from_pretrained(path, device="cuda", dtype=torch.float16)
def execute(self, texts, maxlength, **kwargs):
results = []
for text in texts:
# Tokenize prompt
tokens = self.tokenizer(text, return_tensors="pt").to("cuda")["input_ids"]
# Run inference
output = self.model.generate(input_ids=tokens, max_length=maxlength, eos_token_id=self.tokenizer.eos_token_id, **kwargs)
# Decode results
output = self.tokenizer.batch_decode(output)
output = output[0].split("<|assistant|>\n")[-1].replace("<|endoftext|>", "").strip()
results.append(output)
return resultsIn [6]:
llm = LLM("havenhq/mamba-chat", method="__main__.MambaGeneration")
template = """<|system|>You are a friendly assistant. You answer questions from users.</s>
<|user|>
Find the best matching text in the context for the question. The response should be the text from the context only.
Question:
{question}
Context:
{context}
</s>
<|assistant|>
"""
# Create and run RAG instance
rag = RAG(embeddings, llm, output="reference", separator="\n", template=template)
result = rag("Tell me something about about wildlife")
print("ANSWER:", result["answer"])
print("REFERENCE:", embeddings.search("select id, text from txtai where id = :id", parameters={"id": result["reference"]}))ANSWER: The National Park Service warns against sacrificing slower friends in a bear attack.
REFERENCE: [{'id': '7224f159-658b-5891-b06c-9a96cfa6a54d', 'text': 'The National Park Service warns against sacrificing slower friends in a bear attack'}]