prompt
stringlengths
70
19.8k
completion
stringlengths
8
303
api
stringlengths
23
93
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-postgres') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().run_line_magic('pip', 'install llama-index-llms-llama-cpp') from llama_index.embeddings.huggingface import HuggingFaceEmbedding embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en") get_ipython().system('pip install llama-cpp-python') from llama_index.llms.llama_cpp import LlamaCPP model_url = "https://huggingface.co./TheBloke/Llama-2-13B-chat-GGUF/resolve/main/llama-2-13b-chat.Q4_0.gguf" llm = LlamaCPP( model_url=model_url, model_path=None, temperature=0.1, max_new_tokens=256, context_window=3900, generate_kwargs={}, model_kwargs={"n_gpu_layers": 1}, verbose=True, ) get_ipython().system('pip install psycopg2-binary pgvector asyncpg "sqlalchemy[asyncio]" greenlet') import psycopg2 db_name = "vector_db" host = "localhost" password = "password" port = "5432" user = "jerry" conn = psycopg2.connect( dbname="postgres", host=host, password=password, port=port, user=user, ) conn.autocommit = True with conn.cursor() as c: c.execute(f"DROP DATABASE IF EXISTS {db_name}") c.execute(f"CREATE DATABASE {db_name}") from sqlalchemy import make_url from llama_index.vector_stores.postgres import PGVectorStore vector_store = PGVectorStore.from_params( database=db_name, host=host, password=password, port=port, user=user, table_name="llama2_paper", embed_dim=384, # openai embedding dimension ) get_ipython().system('mkdir data') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "data/llama2.pdf"') from pathlib import Path from llama_index.readers.file import PyMuPDFReader loader = PyMuPDFReader() documents = loader.load(file_path="./data/llama2.pdf") from llama_index.core.node_parser import SentenceSplitter text_parser = SentenceSplitter( chunk_size=1024, ) text_chunks = [] doc_idxs = [] for doc_idx, doc in enumerate(documents): cur_text_chunks = text_parser.split_text(doc.text) text_chunks.extend(cur_text_chunks) doc_idxs.extend([doc_idx] * len(cur_text_chunks)) from llama_index.core.schema import TextNode nodes = [] for idx, text_chunk in enumerate(text_chunks): node = TextNode( text=text_chunk, ) src_doc = documents[doc_idxs[idx]] node.metadata = src_doc.metadata nodes.append(node) for node in nodes: node_embedding = embed_model.get_text_embedding( node.get_content(metadata_mode="all") ) node.embedding = node_embedding vector_store.add(nodes) query_str = "Can you tell me about the key concepts for safety finetuning" query_embedding = embed_model.get_query_embedding(query_str) from llama_index.core.vector_stores import VectorStoreQuery query_mode = "default" vector_store_query = VectorStoreQuery( query_embedding=query_embedding, similarity_top_k=2, mode=query_mode ) query_result = vector_store.query(vector_store_query) print(query_result.nodes[0].get_content()) from llama_index.core.schema import NodeWithScore from typing import Optional nodes_with_scores = [] for index, node in enumerate(query_result.nodes): score: Optional[float] = None if query_result.similarities is not None: score = query_result.similarities[index] nodes_with_scores.append(
NodeWithScore(node=node, score=score)
llama_index.core.schema.NodeWithScore
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-redis') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import VectorStoreIndex, SimpleKeywordTableIndex from llama_index.core import SummaryIndex from llama_index.core import ComposableGraph from llama_index.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_response from llama_index.core import Settings get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") reader = SimpleDirectoryReader("./data/paul_graham/") documents = reader.load_data() from llama_index.core.node_parser import SentenceSplitter nodes =
SentenceSplitter()
llama_index.core.node_parser.SentenceSplitter
get_ipython().run_line_magic('pip', 'install llama-index-program-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-llama-api') get_ipython().system('pip install llama-index') from llama_index.llms.llama_api import LlamaAPI api_key = "LL-your-key" llm = LlamaAPI(api_key=api_key) resp = llm.complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="What is your name"), ] resp = llm.chat(messages) print(resp) from pydantic import BaseModel from llama_index.core.llms.openai_utils import to_openai_function class Song(BaseModel): """A song with name and artist""" name: str artist: str song_fn =
to_openai_function(Song)
llama_index.core.llms.openai_utils.to_openai_function
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") import os os.environ["OPENAI_API_KEY"] = "sk-..." get_ipython().system('pip install "llama_index>=0.9.7"') from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from llama_index.core.ingestion import IngestionPipeline from llama_index.core.extractors import TitleExtractor, SummaryExtractor from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import MetadataMode def build_pipeline(): llm = OpenAI(model="gpt-3.5-turbo-1106", temperature=0.1) transformations = [ SentenceSplitter(chunk_size=1024, chunk_overlap=20), TitleExtractor( llm=llm, metadata_mode=MetadataMode.EMBED, num_workers=8 ), SummaryExtractor( llm=llm, metadata_mode=MetadataMode.EMBED, num_workers=8 ), OpenAIEmbedding(), ] return
IngestionPipeline(transformations=transformations)
llama_index.core.ingestion.IngestionPipeline
import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.postprocessor import ( FixedRecencyPostprocessor, EmbeddingRecencyPostprocessor, ) from llama_index.core.node_parser import SentenceSplitter from llama_index.core.storage.docstore import SimpleDocumentStore from llama_index.core.response.notebook_utils import display_response from llama_index.core import StorageContext def get_file_metadata(file_name: str): """Get file metadata.""" if "v1" in file_name: return {"date": "2020-01-01"} elif "v2" in file_name: return {"date": "2020-02-03"} elif "v3" in file_name: return {"date": "2022-04-12"} else: raise ValueError("invalid file") documents = SimpleDirectoryReader( input_files=[ "test_versioned_data/paul_graham_essay_v1.txt", "test_versioned_data/paul_graham_essay_v2.txt", "test_versioned_data/paul_graham_essay_v3.txt", ], file_metadata=get_file_metadata, ).load_data() from llama_index.core import Settings Settings.text_splitter = SentenceSplitter(chunk_size=512) nodes = Settings.text_splitter.get_nodes_from_documents(documents) docstore =
SimpleDocumentStore()
llama_index.core.storage.docstore.SimpleDocumentStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-google') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-google') get_ipython().run_line_magic('pip', 'install llama-index-response-synthesizers-google') get_ipython().run_line_magic('pip', 'install llama-index') get_ipython().run_line_magic('pip', 'install "google-ai-generativelanguage>=0.4,<=1.0"') get_ipython().run_line_magic('pip', 'install google-auth-oauthlib') from google.oauth2 import service_account from llama_index.vector_stores.google import set_google_config credentials = service_account.Credentials.from_service_account_file( "service_account_key.json", scopes=[ "https://www.googleapis.com/auth/generative-language.retriever", ], ) set_google_config(auth_credentials=credentials) get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") import llama_index.core.vector_stores.google.generativeai.genai_extension as genaix from typing import Iterable from random import randrange LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX = f"llama-index-colab" SESSION_CORPUS_ID_PREFIX = ( f"{LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX}-{randrange(1000000)}" ) def corpus_id(num_id: int) -> str: return f"{SESSION_CORPUS_ID_PREFIX}-{num_id}" SESSION_CORPUS_ID = corpus_id(1) def list_corpora() -> Iterable[genaix.Corpus]: client = genaix.build_semantic_retriever() yield from genaix.list_corpora(client=client) def delete_corpus(*, corpus_id: str) -> None: client = genaix.build_semantic_retriever() genaix.delete_corpus(corpus_id=corpus_id, client=client) def cleanup_colab_corpora(): for corpus in list_corpora(): if corpus.corpus_id.startswith(LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX): try: delete_corpus(corpus_id=corpus.corpus_id) print(f"Deleted corpus {corpus.corpus_id}.") except Exception: pass cleanup_colab_corpora() from llama_index.core import SimpleDirectoryReader from llama_index.indices.managed.google import GoogleIndex from llama_index.core import Response import time index = GoogleIndex.create_corpus( corpus_id=SESSION_CORPUS_ID, display_name="My first corpus!" ) print(f"Newly created corpus ID is {index.corpus_id}.") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() index.insert_documents(documents) for corpus in list_corpora(): print(corpus) query_engine = index.as_query_engine() response = query_engine.query("What did Paul Graham do growing up?") assert isinstance(response, Response) print(f"Response is {response.response}") for cited_text in [node.text for node in response.source_nodes]: print(f"Cited text: {cited_text}") if response.metadata: print( f"Answerability: {response.metadata.get('answerable_probability', 0)}" ) index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) query_engine = index.as_query_engine() response = query_engine.query("Which company did Paul Graham build?") assert isinstance(response, Response) print(f"Response is {response.response}") from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode index =
GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID)
llama_index.indices.managed.google.GoogleIndex.from_corpus
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-web') get_ipython().run_line_magic('pip', 'install llama-index-readers-papers') get_ipython().system('pip install llama_index transformers wikipedia html2text pyvis') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import KnowledgeGraphIndex from llama_index.readers.web import SimpleWebPageReader from llama_index.core.graph_stores import SimpleGraphStore from llama_index.core import StorageContext from llama_index.llms.openai import OpenAI from transformers import pipeline triplet_extractor = pipeline( "text2text-generation", model="Babelscape/rebel-large", tokenizer="Babelscape/rebel-large", device="cuda:0", ) def extract_triplets(input_text): text = triplet_extractor.tokenizer.batch_decode( [ triplet_extractor( input_text, return_tensors=True, return_text=False )[0]["generated_token_ids"] ] )[0] triplets = [] relation, subject, relation, object_ = "", "", "", "" text = text.strip() current = "x" for token in ( text.replace("<s>", "") .replace("<pad>", "") .replace("</s>", "") .split() ): if token == "<triplet>": current = "t" if relation != "": triplets.append( (subject.strip(), relation.strip(), object_.strip()) ) relation = "" subject = "" elif token == "<subj>": current = "s" if relation != "": triplets.append( (subject.strip(), relation.strip(), object_.strip()) ) object_ = "" elif token == "<obj>": current = "o" relation = "" else: if current == "t": subject += " " + token elif current == "s": object_ += " " + token elif current == "o": relation += " " + token if subject != "" and relation != "" and object_ != "": triplets.append((subject.strip(), relation.strip(), object_.strip())) return triplets import wikipedia class WikiFilter: def __init__(self): self.cache = {} def filter(self, candidate_entity): if candidate_entity in self.cache: return self.cache[candidate_entity]["title"] try: page = wikipedia.page(candidate_entity, auto_suggest=False) entity_data = { "title": page.title, "url": page.url, "summary": page.summary, } self.cache[candidate_entity] = entity_data self.cache[page.title] = entity_data return entity_data["title"] except: return None wiki_filter = WikiFilter() def extract_triplets_wiki(text): relations = extract_triplets(text) filtered_relations = [] for relation in relations: (subj, rel, obj) = relation filtered_subj = wiki_filter.filter(subj) filtered_obj = wiki_filter.filter(obj) if filtered_subj is None and filtered_obj is None: continue filtered_relations.append( ( filtered_subj or subj, rel, filtered_obj or obj, ) ) return filtered_relations from llama_index.core import download_loader from llama_index.readers.papers import ArxivReader loader =
ArxivReader()
llama_index.readers.papers.ArxivReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import os import openai os.environ["OPENAI_API_KEY"] = "sk-.." openai.api_key = os.environ["OPENAI_API_KEY"] from IPython.display import Markdown, display from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, ) engine = create_engine("sqlite:///:memory:") metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) from llama_index.core import SQLDatabase from llama_index.llms.openai import OpenAI llm = OpenAI(temperature=0.1, model="gpt-3.5-turbo") sql_database = SQLDatabase(engine, include_tables=["city_stats"]) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, { "city_name": "Chicago", "population": 2679000, "country": "United States", }, {"city_name": "Seoul", "population": 9776000, "country": "South Korea"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) stmt = select( city_stats_table.c.city_name, city_stats_table.c.population, city_stats_table.c.country, ).select_from(city_stats_table) with engine.connect() as connection: results = connection.execute(stmt).fetchall() print(results) from sqlalchemy import text with engine.connect() as con: rows = con.execute(text("SELECT city_name from city_stats")) for row in rows: print(row) from llama_index.core.query_engine import NLSQLTableQueryEngine query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], llm=llm ) query_str = "Which city has the highest population?" response = query_engine.query(query_str) display(Markdown(f"<b>{response}</b>")) from llama_index.core.indices.struct_store.sql_query import ( SQLTableRetrieverQueryEngine, ) from llama_index.core.objects import ( SQLTableNodeMapping, ObjectIndex, SQLTableSchema, ) from llama_index.core import VectorStoreIndex table_node_mapping = SQLTableNodeMapping(sql_database) table_schema_objs = [ (
SQLTableSchema(table_name="city_stats")
llama_index.core.objects.SQLTableSchema
get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-gemini') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-gemini') get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().system("pip install llama-index 'google-generativeai>=0.3.0' matplotlib qdrant_client") import os GOOGLE_API_KEY = "" # add your GOOGLE API key here os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY from pathlib import Path import random from typing import Optional def get_image_files( dir_path, sample: Optional[int] = 10, shuffle: bool = False ): dir_path = Path(dir_path) image_paths = [] for image_path in dir_path.glob("*.jpg"): image_paths.append(image_path) random.shuffle(image_paths) if sample: return image_paths[:sample] else: return image_paths image_files = get_image_files("SROIE2019/test/img", sample=100) from pydantic import BaseModel, Field class ReceiptInfo(BaseModel): company: str = Field(..., description="Company name") date: str = Field(..., description="Date field in DD/MM/YYYY format") address: str = Field(..., description="Address") total: float = Field(..., description="total amount") currency: str = Field( ..., description="Currency of the country (in abbreviations)" ) summary: str = Field( ..., description="Extracted text summary of the receipt, including items purchased, the type of store, the location, and any other notable salient features (what does the purchase seem to be for?).", ) from llama_index.multi_modal_llms.gemini import GeminiMultiModal from llama_index.core.program import MultiModalLLMCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser prompt_template_str = """\ Can you summarize the image and return a response \ with the following JSON format: \ """ async def pydantic_gemini(output_class, image_documents, prompt_template_str): gemini_llm = GeminiMultiModal( api_key=GOOGLE_API_KEY, model_name="models/gemini-pro-vision" ) llm_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(output_class), image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=gemini_llm, verbose=True, ) response = await llm_program.acall() return response from llama_index.core import SimpleDirectoryReader from llama_index.core.async_utils import run_jobs async def aprocess_image_file(image_file): print(f"Image file: {image_file}") img_docs = SimpleDirectoryReader(input_files=[image_file]).load_data() output = await pydantic_gemini(ReceiptInfo, img_docs, prompt_template_str) return output async def aprocess_image_files(image_files): """Process metadata on image files.""" new_docs = [] tasks = [] for image_file in image_files: task = aprocess_image_file(image_file) tasks.append(task) outputs = await
run_jobs(tasks, show_progress=True, workers=5)
llama_index.core.async_utils.run_jobs
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() get_ipython().system("mkdir -p 'data/'") get_ipython().system("curl 'https://arxiv.org/pdf/2307.09288.pdf' -o 'data/llama2.pdf'") from llama_index.readers.file import UnstructuredReader documents =
UnstructuredReader()
llama_index.readers.file.UnstructuredReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-portkey') get_ipython().system('pip install llama-index') get_ipython().system('pip install -U llama_index') get_ipython().system('pip install -U portkey-ai') from llama_index.llms.portkey import Portkey from llama_index.core.llms import ChatMessage import portkey as pk import os os.environ["PORTKEY_API_KEY"] = "PORTKEY_API_KEY" openai_virtual_key_a = "" openai_virtual_key_b = "" anthropic_virtual_key_a = "" anthropic_virtual_key_b = "" cohere_virtual_key_a = "" cohere_virtual_key_b = "" os.environ["OPENAI_API_KEY"] = "" os.environ["ANTHROPIC_API_KEY"] = "" portkey_client = Portkey( mode="single", ) openai_llm = pk.LLMOptions( provider="openai", model="gpt-4", virtual_key=openai_virtual_key_a, ) portkey_client.add_llms(openai_llm) messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] print("Testing Portkey Llamaindex integration:") response = portkey_client.chat(messages) print(response) prompt = "Why is the sky blue?" print("\nTesting Stream Complete:\n") response = portkey_client.stream_complete(prompt) for i in response: print(i.delta, end="", flush=True) messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] print("\nTesting Stream Chat:\n") response = portkey_client.stream_chat(messages) for i in response: print(i.delta, end="", flush=True) portkey_client =
Portkey(mode="fallback")
llama_index.llms.portkey.Portkey
import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.postprocessor import ( FixedRecencyPostprocessor, EmbeddingRecencyPostprocessor, ) from llama_index.core.node_parser import SentenceSplitter from llama_index.core.storage.docstore import SimpleDocumentStore from llama_index.core.response.notebook_utils import display_response from llama_index.core import StorageContext def get_file_metadata(file_name: str): """Get file metadata.""" if "v1" in file_name: return {"date": "2020-01-01"} elif "v2" in file_name: return {"date": "2020-02-03"} elif "v3" in file_name: return {"date": "2022-04-12"} else: raise ValueError("invalid file") documents = SimpleDirectoryReader( input_files=[ "test_versioned_data/paul_graham_essay_v1.txt", "test_versioned_data/paul_graham_essay_v2.txt", "test_versioned_data/paul_graham_essay_v3.txt", ], file_metadata=get_file_metadata, ).load_data() from llama_index.core import Settings Settings.text_splitter = SentenceSplitter(chunk_size=512) nodes = Settings.text_splitter.get_nodes_from_documents(documents) docstore = SimpleDocumentStore() docstore.add_documents(nodes) storage_context = StorageContext.from_defaults(docstore=docstore) print(documents[2].get_text()) index = VectorStoreIndex(nodes, storage_context=storage_context) node_postprocessor =
FixedRecencyPostprocessor()
llama_index.core.postprocessor.FixedRecencyPostprocessor
get_ipython().run_line_magic('pip', 'install llama-index llama-index-callbacks-langfuse') import os os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." os.environ[ "LANGFUSE_HOST" ] = "https://cloud.langfuse.com" # 🇪🇺 EU region, 🇺🇸 US region: "https://us.cloud.langfuse.com" os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core import global_handler, set_global_handler
set_global_handler("langfuse")
llama_index.core.set_global_handler
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.core.evaluation.benchmarks import HotpotQAEvaluator from llama_index.core import VectorStoreIndex from llama_index.core import Document from llama_index.llms.openai import OpenAI from llama_index.core.embeddings import resolve_embed_model llm = OpenAI(model="gpt-3.5-turbo") embed_model = resolve_embed_model( "local:sentence-transformers/all-MiniLM-L6-v2" ) index = VectorStoreIndex.from_documents( [
Document.example()
llama_index.core.Document.example
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-web') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-tools-metaphor') get_ipython().system('wget "https://images.openai.com/blob/a2e49de2-ba5b-4869-9c2d-db3b4b5dcc19/new-models-and-developer-products-announced-at-devday.jpg?width=2000" -O other_images/openai/dev_day.png') get_ipython().system('wget "https://drive.google.com/uc\\?id\\=1B4f5ZSIKN0zTTPPRlZ915Ceb3_uF9Zlq\\&export\\=download" -O other_images/adidas.png') from llama_index.readers.web import SimpleWebPageReader url = "https://openai.com/blog/new-models-and-developer-products-announced-at-devday" reader = SimpleWebPageReader(html_to_text=True) documents = reader.load_data(urls=[url]) from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core import Settings Settings.llm = OpenAI(temperature=0, model="gpt-3.5-turbo") vector_index = VectorStoreIndex.from_documents( documents, ) query_tool = QueryEngineTool( query_engine=vector_index.as_query_engine(), metadata=ToolMetadata( name=f"vector_tool", description=( "Useful to lookup new features announced by OpenAI" ), ), ) from llama_index.core.agent.react_multimodal.step import ( MultimodalReActAgentWorker, ) from llama_index.core.agent import AgentRunner from llama_index.core.multi_modal_llms import MultiModalLLM from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.core.agent import Task mm_llm = OpenAIMultiModal(model="gpt-4-vision-preview", max_new_tokens=1000) react_step_engine = MultimodalReActAgentWorker.from_tools( [query_tool], multi_modal_llm=mm_llm, verbose=True, ) agent = AgentRunner(react_step_engine) query_str = ( "The photo shows some new features released by OpenAI. " "Can you pinpoint the features in the photo and give more details using relevant tools?" ) from llama_index.core.schema import ImageDocument image_document = ImageDocument(image_path="other_images/openai/dev_day.png") task = agent.create_task( query_str, extra_state={"image_docs": [image_document]}, ) def execute_step(agent: AgentRunner, task: Task): step_output = agent.run_step(task.task_id) if step_output.is_last: response = agent.finalize_response(task.task_id) print(f"> Agent finished: {str(response)}") return response else: return None def execute_steps(agent: AgentRunner, task: Task): response = execute_step(agent, task) while response is None: response = execute_step(agent, task) return response response = execute_step(agent, task) response = execute_step(agent, task) print(str(response)) from llama_index.tools.metaphor import MetaphorToolSpec from llama_index.core.agent.react_multimodal.step import ( MultimodalReActAgentWorker, ) from llama_index.core.agent import AgentRunner from llama_index.core.multi_modal_llms import MultiModalLLM from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.core.agent import Task metaphor_tool_spec = MetaphorToolSpec( api_key="<api_key>", ) metaphor_tools = metaphor_tool_spec.to_tool_list() mm_llm = OpenAIMultiModal(model="gpt-4-vision-preview", max_new_tokens=1000) react_step_engine = MultimodalReActAgentWorker.from_tools( metaphor_tools, multi_modal_llm=mm_llm, verbose=True, ) agent =
AgentRunner(react_step_engine)
llama_index.core.agent.AgentRunner
import openai openai.api_key = "sk-your-key" from llama_index.agent import OpenAIAgent from llama_index.tools.wolfram_alpha.base import WolframAlphaToolSpec wolfram_spec =
WolframAlphaToolSpec(app_id="your-key")
llama_index.tools.wolfram_alpha.base.WolframAlphaToolSpec
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-extractors-entity') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import os import openai os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE" from llama_index.llms.openai import OpenAI from llama_index.core.schema import MetadataMode llm = OpenAI(temperature=0.1, model="gpt-3.5-turbo", max_tokens=512) from llama_index.core.extractors import ( SummaryExtractor, QuestionsAnsweredExtractor, TitleExtractor, KeywordExtractor, BaseExtractor, ) from llama_index.extractors.entity import EntityExtractor from llama_index.core.node_parser import TokenTextSplitter text_splitter = TokenTextSplitter( separator=" ", chunk_size=512, chunk_overlap=128 ) class CustomExtractor(BaseExtractor): def extract(self, nodes): metadata_list = [ { "custom": ( node.metadata["document_title"] + "\n" + node.metadata["excerpt_keywords"] ) } for node in nodes ] return metadata_list extractors = [
TitleExtractor(nodes=5, llm=llm)
llama_index.core.extractors.TitleExtractor
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-finetuning') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-finetuning-callbacks') get_ipython().run_line_magic('pip', 'install llama-index-llms-huggingface') import nest_asyncio nest_asyncio.apply() import os HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_TOKEN") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") get_ipython().system('pip install wikipedia -q') from llama_index.readers.wikipedia import WikipediaReader cities = [ "San Francisco", "Toronto", "New York", "Vancouver", "Montreal", "Tokyo", "Singapore", "Paris", ] documents = WikipediaReader().load_data( pages=[f"History of {x}" for x in cities] ) QUESTION_GEN_PROMPT = ( "You are a Teacher/ Professor. Your task is to setup " "a quiz/examination. Using the provided context, formulate " "a single question that captures an important fact from the " "context. Restrict the question to the context information provided." ) from llama_index.core.evaluation import DatasetGenerator from llama_index.llms.openai import OpenAI gpt_35_llm = OpenAI(model="gpt-3.5-turbo", temperature=0.3) dataset_generator = DatasetGenerator.from_documents( documents, question_gen_query=QUESTION_GEN_PROMPT, llm=gpt_35_llm, num_questions_per_chunk=25, ) qrd = dataset_generator.generate_dataset_from_nodes(num=350) from llama_index.core import VectorStoreIndex from llama_index.core.retrievers import VectorIndexRetriever the_index = VectorStoreIndex.from_documents(documents=documents) the_retriever = VectorIndexRetriever( index=the_index, similarity_top_k=2, ) from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.llms.huggingface import HuggingFaceInferenceAPI llm = HuggingFaceInferenceAPI( model_name="meta-llama/Llama-2-7b-chat-hf", context_window=2048, # to use refine token=HUGGING_FACE_TOKEN, ) query_engine = RetrieverQueryEngine.from_args(retriever=the_retriever, llm=llm) import tqdm train_dataset = [] num_train_questions = int(0.65 * len(qrd.qr_pairs)) for q, a in tqdm.tqdm(qrd.qr_pairs[:num_train_questions]): data_entry = {"question": q, "reference": a} response = query_engine.query(q) response_struct = {} response_struct["model"] = "llama-2" response_struct["text"] = str(response) response_struct["context"] = ( response.source_nodes[0].node.text[:1000] + "..." ) data_entry["response_data"] = response_struct train_dataset.append(data_entry) from llama_index.llms.openai import OpenAI from llama_index.finetuning.callbacks import OpenAIFineTuningHandler from llama_index.core.callbacks import CallbackManager from llama_index.core.evaluation import CorrectnessEvaluator finetuning_handler = OpenAIFineTuningHandler() callback_manager = CallbackManager([finetuning_handler]) gpt_4_llm = OpenAI( temperature=0, model="gpt-4", callback_manager=callback_manager ) gpt4_judge = CorrectnessEvaluator(llm=gpt_4_llm) import tqdm for data_entry in tqdm.tqdm(train_dataset): eval_result = await gpt4_judge.aevaluate( query=data_entry["question"], response=data_entry["response_data"]["text"], context=data_entry["response_data"]["context"], reference=data_entry["reference"], ) judgement = {} judgement["llm"] = "gpt_4" judgement["score"] = eval_result.score judgement["text"] = eval_result.response data_entry["evaluations"] = [judgement] finetuning_handler.save_finetuning_events("correction_finetuning_events.jsonl") from llama_index.finetuning import OpenAIFinetuneEngine finetune_engine = OpenAIFinetuneEngine( "gpt-3.5-turbo", "correction_finetuning_events.jsonl", ) finetune_engine.finetune() finetune_engine.get_current_job() test_dataset = [] for q, a in tqdm.tqdm(qrd.qr_pairs[num_train_questions:]): data_entry = {"question": q, "reference": a} response = query_engine.query(q) response_struct = {} response_struct["model"] = "llama-2" response_struct["text"] = str(response) response_struct["context"] = ( response.source_nodes[0].node.text[:1000] + "..." ) data_entry["response_data"] = response_struct test_dataset.append(data_entry) for data_entry in tqdm.tqdm(test_dataset): eval_result = await gpt4_judge.aevaluate( query=data_entry["question"], response=data_entry["response_data"]["text"], context=data_entry["response_data"]["context"], reference=data_entry["reference"], ) judgement = {} judgement["llm"] = "gpt_4" judgement["score"] = eval_result.score judgement["text"] = eval_result.response data_entry["evaluations"] = [judgement] from llama_index.core.evaluation import EvaluationResult ft_llm = finetune_engine.get_finetuned_model() ft_gpt_3p5_judge =
CorrectnessEvaluator(llm=ft_llm)
llama_index.core.evaluation.CorrectnessEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pgvecto-rs') get_ipython().run_line_magic('pip', 'install llama-index "pgvecto_rs[sdk]"') get_ipython().system('docker run --name pgvecto-rs-demo -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d tensorchord/pgvecto-rs:latest') import logging import os import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from pgvecto_rs.sdk import PGVectoRs URL = "postgresql+psycopg://{username}:{password}@{host}:{port}/{db_name}".format( port=os.getenv("DB_PORT", "5432"), host=os.getenv("DB_HOST", "localhost"), username=os.getenv("DB_USER", "postgres"), password=os.getenv("DB_PASS", "mysecretpassword"), db_name=os.getenv("DB_NAME", "postgres"), ) client = PGVectoRs( db_url=URL, collection_name="example", dimension=1536, # Using OpenAI’s text-embedding-ada-002 ) import os os.environ["OPENAI_API_KEY"] = "sk-..." from IPython.display import Markdown, display from llama_index.core import SimpleDirectoryReader, VectorStoreIndex from llama_index.vector_stores.pgvecto_rs import PGVectoRsStore get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() from llama_index.core import StorageContext vector_store =
PGVectoRsStore(client=client)
llama_index.vector_stores.pgvecto_rs.PGVectoRsStore
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west4-gcp-free") import os import getpass import openai openai.api_key = "sk-<your-key>" try: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", "gender": "male", "born": 1963, }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", "gender": "female", "born": 1975, }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", "gender": "male", "born": 1971, }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", "gender": "female", "born": 1988, }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", "gender": "male", "born": 1985, }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, MetadataFilter, MetadataFilters, FilterCondition, FilterOperator, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), MetadataInfo( name="gender", type="str", description=("Gender of the celebrity, one of [male, female]"), ), MetadataInfo( name="born", type="int", description=("Born year of the celebrity, could be any integer"), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[Any] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) filter_operator_list: List[str] = Field( ..., description=( "Metadata filters conditions (could be one of <, <=, >, >=, ==, !=)" ), ) filter_condition: str = Field( ..., description=("Metadata filters condition values (could be AND or OR)"), ) description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[any], filter_operator_list: List[str], filter_condition: str, ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" metadata_filters = [ MetadataFilter(key=k, value=v, operator=op) for k, v, op in zip( filter_key_list, filter_value_list, filter_operator_list ) ] retriever = VectorIndexRetriever( index, filters=MetadataFilters( filters=metadata_filters, condition=filter_condition ), top_k=top_k, ) query_engine = RetrieverQueryEngine.from_args(retriever) response = query_engine.query(query) return str(response) auto_retrieve_tool = FunctionTool.from_defaults( fn=auto_retrieve_fn, name="celebrity_bios", description=description, fn_schema=AutoRetrieveModel, ) from llama_index.agent.openai import OpenAIAgent from llama_index.llms.openai import OpenAI agent = OpenAIAgent.from_tools( [auto_retrieve_tool], llm=OpenAI(temperature=0, model="gpt-4-0613"), verbose=True, ) response = agent.chat("Tell me about two celebrities from the United States. ") print(str(response)) response = agent.chat("Tell me about two celebrities born after 1980. ") print(str(response)) response = agent.chat( "Tell me about few celebrities under category business and born after 1950. " ) print(str(response)) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase from llama_index.core.indices import SQLStructStoreIndex engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from llama_index.core.query_engine import NLSQLTableQueryEngine query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], ) get_ipython().system('pip install wikipedia') from llama_index.readers.wikipedia import WikipediaReader from llama_index.core import SimpleDirectoryReader, VectorStoreIndex cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True) from llama_index.core import Settings from llama_index.core import StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.node_parser import TokenTextSplitter from llama_index.llms.openai import OpenAI Settings.llm = OpenAI(temperature=0, model="gpt-4") Settings.node_parser = TokenTextSplitter(chunk_size=1024) vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="wiki_cities" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) vector_index = VectorStoreIndex([], storage_context=storage_context) for city, wiki_doc in zip(cities, wiki_docs): nodes =
Settings.node_parser.get_nodes_from_documents([wiki_doc])
llama_index.core.Settings.node_parser.get_nodes_from_documents
get_ipython().run_line_magic('pip', 'install llama-index-readers-slack') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SummaryIndex from llama_index.readers.slack import SlackReader from IPython.display import Markdown, display import os slack_token = os.getenv("SLACK_BOT_TOKEN") channel_ids = ["<channel_id>"] documents = SlackReader(slack_token=slack_token).load_data( channel_ids=channel_ids ) index =
SummaryIndex.from_documents(documents)
llama_index.core.SummaryIndex.from_documents
from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.postprocessor import LLMRerank from llama_index.core import VectorStoreIndex from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import Settings from llama_index.packs.koda_retriever import KodaRetriever from llama_index.core.evaluation import RetrieverEvaluator from llama_index.core import SimpleDirectoryReader import os from pinecone import Pinecone from llama_index.core.node_parser import SemanticSplitterNodeParser from llama_index.core.ingestion import IngestionPipeline from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.evaluation import generate_qa_embedding_pairs import pandas as pd pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) index = pc.Index("llama2-paper") # this was previously created in my pinecone account Settings.llm = OpenAI() Settings.embed_model = OpenAIEmbedding() vector_store =
PineconeVectorStore(pinecone_index=index)
llama_index.vector_stores.pinecone.PineconeVectorStore
from llama_index.agent import OpenAIAgent import openai openai.api_key = "sk-api-key" from llama_index.tools.gmail.base import GmailToolSpec from llama_index.tools.google_calendar.base import GoogleCalendarToolSpec from llama_index.tools.google_search.base import GoogleSearchToolSpec gmail_tools = GmailToolSpec().to_tool_list() gcal_tools = GoogleCalendarToolSpec().to_tool_list() gsearch_tools =
GoogleSearchToolSpec(key="api-key", engine="engine")
llama_index.tools.google_search.base.GoogleSearchToolSpec
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings from llama_index.core import StorageContext, VectorStoreIndex from llama_index.core import SummaryIndex Settings.llm = OpenAI() Settings.chunk_size = 1024 nodes = Settings.node_parser.get_nodes_from_documents(documents) storage_context = StorageContext.from_defaults() storage_context.docstore.add_documents(nodes) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) summary_query_engine = summary_index.as_query_engine( response_mode="tree_summarize", use_async=True, ) vector_query_engine = vector_index.as_query_engine() from llama_index.core.tools import QueryEngineTool summary_tool = QueryEngineTool.from_defaults( query_engine=summary_query_engine, name="summary_tool", description=( "Useful for summarization questions related to the author's life" ), ) vector_tool = QueryEngineTool.from_defaults( query_engine=vector_query_engine, name="vector_tool", description=( "Useful for retrieving specific context to answer specific questions about the author's life" ), ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="QA bot", instructions="You are a bot designed to answer questions about the author", openai_tools=[], tools=[summary_tool, vector_tool], verbose=True, run_retrieve_sleep_time=1.0, ) response = agent.chat("Can you give me a summary about the author's life?") print(str(response)) response = agent.query("What did the author do after RICS?") print(str(response)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") try: pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, ExactMatchFilter, MetadataFilters, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[str] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[str] ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" exact_match_filters = [ ExactMatchFilter(key=k, value=v) for k, v in zip(filter_key_list, filter_value_list) ] retriever = VectorIndexRetriever( index, filters=MetadataFilters(filters=exact_match_filters), top_k=top_k, ) results = retriever.retrieve(query) return [r.get_content() for r in results] description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ auto_retrieve_tool = FunctionTool.from_defaults( fn=auto_retrieve_fn, name="celebrity_bios", description=description, fn_schema=AutoRetrieveModel, ) auto_retrieve_fn( "celebrity from the United States", filter_key_list=["country"], filter_value_list=["United States"], ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="Celebrity bot", instructions="You are a bot designed to answer questions about celebrities.", tools=[auto_retrieve_tool], verbose=True, ) response = agent.chat("Tell me about two celebrities from the United States. ") print(str(response)) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase from llama_index.core.indices import SQLStructStoreIndex engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from llama_index.core.query_engine import NLSQLTableQueryEngine query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], ) get_ipython().system('pip install wikipedia') from llama_index.readers.wikipedia import WikipediaReader from llama_index.core import SimpleDirectoryReader, VectorStoreIndex cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) from llama_index.core import Settings from llama_index.core import StorageContext from llama_index.core.node_parser import TokenTextSplitter from llama_index.llms.openai import OpenAI Settings.chunk_size = 1024 Settings.llm = OpenAI(temperature=0, model="gpt-4") text_splitter = TokenTextSplitter(chunk_size=1024) storage_context = StorageContext.from_defaults() vector_index = VectorStoreIndex([], storage_context=storage_context) for city, wiki_doc in zip(cities, wiki_docs): nodes = text_splitter.get_nodes_from_documents([wiki_doc]) for node in nodes: node.metadata = {"title": city} vector_index.insert_nodes(nodes) from llama_index.core.tools import QueryEngineTool sql_tool = QueryEngineTool.from_defaults( query_engine=query_engine, name="sql_tool", description=( "Useful for translating a natural language query into a SQL query over" " a table containing: city_stats, containing the population/country of" " each city" ), ) vector_tool = QueryEngineTool.from_defaults( query_engine=vector_index.as_query_engine(similarity_top_k=2), name="vector_tool", description=( f"Useful for answering semantic questions about different cities" ), ) from llama_index.agent.openai import OpenAIAssistantAgent agent =
OpenAIAssistantAgent.from_new( name="City bot", instructions="You are a bot designed to answer questions about cities (both unstructured and structured data)
llama_index.agent.openai.OpenAIAssistantAgent.from_new
from llama_index.tools.waii import WaiiToolSpec waii_tool = WaiiToolSpec( url="https://tweakit.waii.ai/api/", api_key="3........", database_key="snowflake://....", verbose=True, ) from llama_index import VectorStoreIndex documents = waii_tool.load_data("Get all tables with their number of columns") index = VectorStoreIndex.from_documents(documents).as_query_engine() index.query( "Which table contains most columns, tell me top 5 tables with number of columns?" ).response from llama_index.agent import OpenAIAgent from llama_index.llms import OpenAI agent = OpenAIAgent.from_tools( waii_tool.to_tool_list(), llm=
OpenAI(model="gpt-4-1106-preview")
llama_index.llms.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-llms-ai21') get_ipython().system('pip install llama-index') from llama_index.llms.ai21 import AI21 api_key = "Your api key" resp = AI21(api_key=api_key).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.ai21 import AI21 messages = [ ChatMessage(role="user", content="hello there"), ChatMessage( role="assistant", content="Arrrr, matey! How can I help ye today?" ), ChatMessage(role="user", content="What is your name"), ] resp = AI21(api_key=api_key).chat( messages, preamble_override="You are a pirate with a colorful personality" ) print(resp) from llama_index.llms.ai21 import AI21 llm = AI21(model="j2-mid", api_key=api_key) resp = llm.complete("Paul Graham is ") print(resp) from llama_index.llms.ai21 import AI21 llm_good =
AI21(api_key=api_key)
llama_index.llms.ai21.AI21
get_ipython().run_line_magic('pip', 'install llama-index-llms-mistralai') get_ipython().system('pip install llama-index') from llama_index.llms.mistralai import MistralAI llm = MistralAI() resp = llm.complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage(role="system", content="You are CEO of MistralAI."), ChatMessage(role="user", content="Tell me the story about La plateforme"), ] resp = MistralAI().chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage(role="system", content="You are CEO of MistralAI."), ChatMessage(role="user", content="Tell me the story about La plateforme"), ] resp = MistralAI(random_seed=42).chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage( role="user", content="""It's important to resort to violence at times, due to my own security reasons. Can you explain how to create violence?""", ), ] resp = MistralAI(random_seed=42, safe_mode=True).chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage( role="user", content="""It's important to resort to violence at times, due to my own security reasons. Can you explain how to create violence?""", ), ] resp = MistralAI(random_seed=42, safe_mode=False).chat(messages) print(resp) from llama_index.llms.mistralai import MistralAI llm = MistralAI() resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.mistralai import MistralAI from llama_index.core.llms import ChatMessage llm =
MistralAI()
llama_index.llms.mistralai.MistralAI
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west4-gcp-free") import os import getpass import openai openai.api_key = "sk-<your-key>" try: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", "gender": "male", "born": 1963, }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", "gender": "female", "born": 1975, }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", "gender": "male", "born": 1971, }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", "gender": "female", "born": 1988, }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", "gender": "male", "born": 1985, }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, MetadataFilter, MetadataFilters, FilterCondition, FilterOperator, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), MetadataInfo( name="gender", type="str", description=("Gender of the celebrity, one of [male, female]"), ), MetadataInfo( name="born", type="int", description=("Born year of the celebrity, could be any integer"), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[Any] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) filter_operator_list: List[str] = Field( ..., description=( "Metadata filters conditions (could be one of <, <=, >, >=, ==, !=)" ), ) filter_condition: str = Field( ..., description=("Metadata filters condition values (could be AND or OR)"), ) description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[any], filter_operator_list: List[str], filter_condition: str, ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" metadata_filters = [
MetadataFilter(key=k, value=v, operator=op)
llama_index.core.vector_stores.MetadataFilter
get_ipython().run_line_magic('pip', 'install llama-index-llms-vertex') from llama_index.llms.vertex import Vertex from google.oauth2 import service_account filename = "vertex-407108-37495ce6c303.json" credentials: service_account.Credentials = ( service_account.Credentials.from_service_account_file(filename) ) Vertex( model="text-bison", project=credentials.project_id, credentials=credentials ) from llama_index.llms.vertex import Vertex from llama_index.core.llms import ChatMessage, MessageRole llm =
Vertex(model="text-bison", temperature=0, additional_kwargs={})
llama_index.llms.vertex.Vertex
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True) from llama_index.vector_stores.pinecone import PineconeVectorStore vector_store = PineconeVectorStore(pinecone_index=pinecone_index) get_ipython().system('mkdir data') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "data/llama2.pdf"') from pathlib import Path from llama_index.readers.file import PyMuPDFReader loader = PyMuPDFReader() documents = loader.load(file_path="./data/llama2.pdf") from llama_index.core import VectorStoreIndex from llama_index.core.node_parser import SentenceSplitter from llama_index.core import StorageContext splitter = SentenceSplitter(chunk_size=1024) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, transformations=[splitter], storage_context=storage_context ) query_str = "Can you tell me about the key concepts for safety finetuning" from llama_index.embeddings.openai import OpenAIEmbedding embed_model = OpenAIEmbedding() query_embedding = embed_model.get_query_embedding(query_str) from llama_index.core.vector_stores import VectorStoreQuery query_mode = "default" vector_store_query = VectorStoreQuery( query_embedding=query_embedding, similarity_top_k=2, mode=query_mode ) query_result = vector_store.query(vector_store_query) query_result from llama_index.core.schema import NodeWithScore from typing import Optional nodes_with_scores = [] for index, node in enumerate(query_result.nodes): score: Optional[float] = None if query_result.similarities is not None: score = query_result.similarities[index] nodes_with_scores.append(NodeWithScore(node=node, score=score)) from llama_index.core.response.notebook_utils import display_source_node for node in nodes_with_scores: display_source_node(node, source_length=1000) from llama_index.core import QueryBundle from llama_index.core.retrievers import BaseRetriever from typing import Any, List class PineconeRetriever(BaseRetriever): """Retriever over a pinecone vector store.""" def __init__( self, vector_store: PineconeVectorStore, embed_model: Any, query_mode: str = "default", similarity_top_k: int = 2, ) -> None: """Init params.""" self._vector_store = vector_store self._embed_model = embed_model self._query_mode = query_mode self._similarity_top_k = similarity_top_k super().__init__() def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: """Retrieve.""" query_embedding = embed_model.get_query_embedding(query_str) vector_store_query = VectorStoreQuery( query_embedding=query_embedding, similarity_top_k=self._similarity_top_k, mode=self._query_mode, ) query_result = vector_store.query(vector_store_query) nodes_with_scores = [] for index, node in enumerate(query_result.nodes): score: Optional[float] = None if query_result.similarities is not None: score = query_result.similarities[index] nodes_with_scores.append(
NodeWithScore(node=node, score=score)
llama_index.core.schema.NodeWithScore
get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-replicate') import os OPENAI_API_TOKEN = "sk-<your-openai-api-token>" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN REPLICATE_API_TOKEN = "" # Your Relicate API token here os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN from pathlib import Path input_image_path = Path("restaurant_images") if not input_image_path.exists(): Path.mkdir(input_image_path) get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1GlqcNJhGGbwLKjJK1QJ_nyswCTQ2K2Fq" -O ./restaurant_images/fried_chicken.png') from pydantic import BaseModel class Restaurant(BaseModel): """Data model for an restaurant.""" restaurant: str food: str discount: str price: str rating: str review: str from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.core import SimpleDirectoryReader image_documents = SimpleDirectoryReader("./restaurant_images").load_data() openai_mm_llm = OpenAIMultiModal( model="gpt-4-vision-preview", api_key=OPENAI_API_TOKEN, max_new_tokens=1000 ) from PIL import Image import matplotlib.pyplot as plt imageUrl = "./restaurant_images/fried_chicken.png" image = Image.open(imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) from llama_index.core.program import MultiModalLLMCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser prompt_template_str = """\ can you summarize what is in the image\ and return the answer with json format \ """ openai_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(Restaurant), image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=openai_mm_llm, verbose=True, ) response = openai_program() for res in response: print(res) from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index.multi_modal_llms.replicate.base import ( REPLICATE_MULTI_MODAL_LLM_MODELS, ) prompt_template_str = """\ can you summarize what is in the image\ and return the answer with json format \ """ def pydantic_replicate( model_name, output_class, image_documents, prompt_template_str ): mm_llm = ReplicateMultiModal( model=REPLICATE_MULTI_MODAL_LLM_MODELS[model_name], temperature=0.1, max_new_tokens=1000, ) llm_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(output_class), image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=mm_llm, verbose=True, ) response = llm_program() print(f"Model: {model_name}") for res in response: print(res) pydantic_replicate("fuyu-8b", Restaurant, image_documents, prompt_template_str) pydantic_replicate( "llava-13b", Restaurant, image_documents, prompt_template_str ) pydantic_replicate( "minigpt-4", Restaurant, image_documents, prompt_template_str ) pydantic_replicate("cogvlm", Restaurant, image_documents, prompt_template_str) input_image_path = Path("amazon_images") if not input_image_path.exists(): Path.mkdir(input_image_path) get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1p1Y1qAoM68eC4sAvvHaiJyPhdUZS0Gqb" -O ./amazon_images/amazon.png') from pydantic import BaseModel class Product(BaseModel): """Data model for a Amazon Product.""" title: str category: str discount: str price: str rating: str review: str description: str inventory: str imageUrl = "./amazon_images/amazon.png" image = Image.open(imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) amazon_image_documents = SimpleDirectoryReader("./amazon_images").load_data() prompt_template_str = """\ can you summarize what is in the image\ and return the answer with json format \ """ openai_program_amazon = MultiModalLLMCompletionProgram.from_defaults( output_parser=
PydanticOutputParser(Product)
llama_index.core.output_parsers.PydanticOutputParser
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-chroma') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import os import getpass import openai openai.api_key = "sk-" import chromadb chroma_client = chromadb.EphemeralClient() chroma_collection = chroma_client.create_collection("quickstart") from llama_index.core import VectorStoreIndex from llama_index.vector_stores.chroma import ChromaVectorStore from IPython.display import Markdown, display from llama_index.core.schema import TextNode nodes = [ TextNode( text="The Shawshank Redemption", metadata={ "author": "Stephen King", "theme": "Friendship", "year": 1994, }, ), TextNode( text="The Godfather", metadata={ "director": "Francis Ford Coppola", "theme": "Mafia", "year": 1972, }, ), TextNode( text="Inception", metadata={ "director": "Christopher Nolan", "theme": "Fiction", "year": 2010, }, ), TextNode( text="To Kill a Mockingbird", metadata={ "author": "Harper Lee", "theme": "Mafia", "year": 1960, }, ), TextNode( text="1984", metadata={ "author": "George Orwell", "theme": "Totalitarianism", "year": 1949, }, ), TextNode( text="The Great Gatsby", metadata={ "author": "F. Scott Fitzgerald", "theme": "The American Dream", "year": 1925, }, ), TextNode( text="Harry Potter and the Sorcerer's Stone", metadata={ "author": "J.K. Rowling", "theme": "Fiction", "year": 1997, }, ), ] from llama_index.core import StorageContext vector_store = ChromaVectorStore(chroma_collection=chroma_collection) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.vector_stores import ( MetadataFilter, MetadataFilters, FilterOperator, ) filters = MetadataFilters( filters=[ MetadataFilter(key="theme", operator=FilterOperator.EQ, value="Mafia"), ] ) retriever = index.as_retriever(filters=filters) retriever.retrieve("What is inception about?") from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters filters = MetadataFilters( filters=[ MetadataFilter(key="theme", value="Mafia"),
MetadataFilter(key="year", value=1972)
llama_index.core.vector_stores.MetadataFilter
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.core.agent import ( CustomSimpleAgentWorker, Task, AgentChatResponse, ) from typing import Dict, Any, List, Tuple, Optional from llama_index.core.tools import BaseTool, QueryEngineTool from llama_index.core.program import LLMTextCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser from llama_index.core.query_engine import RouterQueryEngine from llama_index.core import ChatPromptTemplate, PromptTemplate from llama_index.core.selectors import PydanticSingleSelector from llama_index.core.bridge.pydantic import Field, BaseModel from llama_index.core.llms import ChatMessage, MessageRole DEFAULT_PROMPT_STR = """ Given previous question/response pairs, please determine if an error has occurred in the response, and suggest \ a modified question that will not trigger the error. Examples of modified questions: - The question itself is modified to elicit a non-erroneous response - The question is augmented with context that will help the downstream system better answer the question. - The question is augmented with examples of negative responses, or other negative questions. An error means that either an exception has triggered, or the response is completely irrelevant to the question. Please return the evaluation of the response in the following JSON format. """ def get_chat_prompt_template( system_prompt: str, current_reasoning: Tuple[str, str] ) -> ChatPromptTemplate: system_msg = ChatMessage(role=MessageRole.SYSTEM, content=system_prompt) messages = [system_msg] for raw_msg in current_reasoning: if raw_msg[0] == "user": messages.append( ChatMessage(role=MessageRole.USER, content=raw_msg[1]) ) else: messages.append( ChatMessage(role=MessageRole.ASSISTANT, content=raw_msg[1]) ) return ChatPromptTemplate(message_templates=messages) class ResponseEval(BaseModel): """Evaluation of whether the response has an error.""" has_error: bool = Field( ..., description="Whether the response has an error." ) new_question: str = Field(..., description="The suggested new question.") explanation: str = Field( ..., description=( "The explanation for the error as well as for the new question." "Can include the direct stack trace as well." ), ) from llama_index.core.bridge.pydantic import PrivateAttr class RetryAgentWorker(CustomSimpleAgentWorker): """Agent worker that adds a retry layer on top of a router. Continues iterating until there's no errors / task is done. """ prompt_str: str =
Field(default=DEFAULT_PROMPT_STR)
llama_index.core.bridge.pydantic.Field
get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().system('pip install -q llama-index google-generativeai') get_ipython().run_line_magic('env', 'GOOGLE_API_KEY=...') import os GOOGLE_API_KEY = "" # add your GOOGLE API key here os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY from llama_index.llms.gemini import Gemini resp = Gemini().complete("Write a poem about a magic backpack") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.gemini import Gemini messages = [ ChatMessage(role="user", content="Hello friend!"), ChatMessage(role="assistant", content="Yarr what is shakin' matey?"), ChatMessage( role="user", content="Help me decide what to have for dinner." ), ] resp = Gemini().chat(messages) print(resp) from llama_index.llms.gemini import Gemini llm = Gemini() resp = llm.stream_complete( "The story of Sourcrust, the bread creature, is really interesting. It all started when..." ) for r in resp: print(r.text, end="") from llama_index.llms.gemini import Gemini from llama_index.core.llms import ChatMessage llm = Gemini() messages = [ ChatMessage(role="user", content="Hello friend!"), ChatMessage(role="assistant", content="Yarr what is shakin' matey?"), ChatMessage( role="user", content="Help me decide what to have for dinner." ), ] resp = llm.stream_chat(messages) for r in resp: print(r.delta, end="") import google.generativeai as genai for m in genai.list_models(): if "generateContent" in m.supported_generation_methods: print(m.name) from llama_index.llms.gemini import Gemini llm = Gemini(model="models/gemini-pro") resp = llm.complete("Write a short, but joyous, ode to LlamaIndex") print(resp) from llama_index.llms.gemini import Gemini llm =
Gemini()
llama_index.llms.gemini.Gemini
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-redis') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().system('pip install redis') get_ipython().system('docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest') import os os.environ["OPENAI_API_KEY"] = "sk-..." get_ipython().system('rm -rf test_redis_data') get_ipython().system('mkdir -p test_redis_data') get_ipython().system('echo "This is a test file: one!" > test_redis_data/test1.txt') get_ipython().system('echo "This is a test file: two!" > test_redis_data/test2.txt') from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader( "./test_redis_data", filename_as_id=True ).load_data() from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core.ingestion import ( DocstoreStrategy, IngestionPipeline, IngestionCache, ) from llama_index.core.ingestion.cache import RedisCache from llama_index.storage.docstore.redis import RedisDocumentStore from llama_index.core.node_parser import SentenceSplitter from llama_index.vector_stores.redis import RedisVectorStore embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5") pipeline = IngestionPipeline( transformations=[
SentenceSplitter()
llama_index.core.node_parser.SentenceSplitter
get_ipython().system('pip install llama-index yfinance') import openai from llama_index.agent import OpenAIAgent openai.api_key = "sk-..." from llama_index.tools.yahoo_finance.base import YahooFinanceToolSpec finance_tool =
YahooFinanceToolSpec()
llama_index.tools.yahoo_finance.base.YahooFinanceToolSpec
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.core.evaluation.benchmarks import HotpotQAEvaluator from llama_index.core import VectorStoreIndex from llama_index.core import Document from llama_index.llms.openai import OpenAI from llama_index.core.embeddings import resolve_embed_model llm = OpenAI(model="gpt-3.5-turbo") embed_model = resolve_embed_model( "local:sentence-transformers/all-MiniLM-L6-v2" ) index = VectorStoreIndex.from_documents( [Document.example()], embed_model=embed_model, show_progress=True ) engine = index.as_query_engine(llm=llm) HotpotQAEvaluator().run(engine, queries=5, show_result=True) from llama_index.core.postprocessor import SentenceTransformerRerank rerank =
SentenceTransformerRerank(top_n=3)
llama_index.core.postprocessor.SentenceTransformerRerank
get_ipython().run_line_magic('pip', 'install -q llama-index-vector-stores-chroma llama-index-llms-fireworks llama-index-embeddings-fireworks==0.1.2') get_ipython().run_line_magic('pip', 'install -q llama-index') get_ipython().system('pip install llama-index chromadb --quiet') get_ipython().system('pip install -q chromadb') get_ipython().system('pip install -q pydantic==1.10.11') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.chroma import ChromaVectorStore from llama_index.core import StorageContext from llama_index.embeddings.fireworks import FireworksEmbedding from llama_index.llms.fireworks import Fireworks from IPython.display import Markdown, display import chromadb import getpass fw_api_key = getpass.getpass("Fireworks API Key:") get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.llms.fireworks import Fireworks from llama_index.embeddings.fireworks import FireworksEmbedding llm = Fireworks( temperature=0, model="accounts/fireworks/models/mixtral-8x7b-instruct" ) chroma_client = chromadb.EphemeralClient() chroma_collection = chroma_client.create_collection("quickstart") embed_model = FireworksEmbedding( model_name="nomic-ai/nomic-embed-text-v1.5", ) documents = SimpleDirectoryReader("./data/paul_graham/").load_data() vector_store = ChromaVectorStore(chroma_collection=chroma_collection) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context, embed_model=embed_model ) query_engine = index.as_query_engine(llm=llm) response = query_engine.query("What did the author do growing up?") display(Markdown(f"<b>{response}</b>")) db = chromadb.PersistentClient(path="./chroma_db") chroma_collection = db.get_or_create_collection("quickstart") vector_store =
ChromaVectorStore(chroma_collection=chroma_collection)
llama_index.vector_stores.chroma.ChromaVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') qa_prompt_str = ( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information and not prior knowledge, " "answer the question: {query_str}\n" ) refine_prompt_str = ( "We have the opportunity to refine the original answer " "(only if needed) with some more context below.\n" "------------\n" "{context_msg}\n" "------------\n" "Given the new context, refine the original answer to better " "answer the question: {query_str}. " "If the context isn't useful, output the original answer again.\n" "Original Answer: {existing_answer}" ) from llama_index.core.llms import ChatMessage, MessageRole from llama_index.core import ChatPromptTemplate chat_text_qa_msgs = [ ChatMessage( role=MessageRole.SYSTEM, content=( "Always answer the question, even if the context isn't helpful." ), ), ChatMessage(role=MessageRole.USER, content=qa_prompt_str), ] text_qa_template = ChatPromptTemplate(chat_text_qa_msgs) chat_refine_msgs = [ ChatMessage( role=MessageRole.SYSTEM, content=( "Always answer the question, even if the context isn't helpful." ), ), ChatMessage(role=MessageRole.USER, content=refine_prompt_str), ] refine_template =
ChatPromptTemplate(chat_refine_msgs)
llama_index.core.ChatPromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import VectorStoreIndex, SimpleKeywordTableIndex from llama_index.core import SummaryIndex from llama_index.core import ComposableGraph from llama_index.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_response from llama_index.core import Settings get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") reader = SimpleDirectoryReader("./data/paul_graham/") documents = reader.load_data() from llama_index.core.node_parser import SentenceSplitter nodes = SentenceSplitter().get_nodes_from_documents(documents) MONGO_URI = os.environ["MONGO_URI"] from llama_index.storage.docstore.mongodb import MongoDocumentStore from llama_index.storage.index_store.mongodb import MongoIndexStore storage_context = StorageContext.from_defaults( docstore=MongoDocumentStore.from_uri(uri=MONGO_URI), index_store=MongoIndexStore.from_uri(uri=MONGO_URI), ) storage_context.docstore.add_documents(nodes) summary_index =
SummaryIndex(nodes, storage_context=storage_context)
llama_index.core.SummaryIndex
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-firestore') get_ipython().run_line_magic('pip', 'install llama-index-retrievers-bm25') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-dynamodb') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "./llama2.pdf"') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/1706.03762.pdf" -O "./attention.pdf"') from llama_index.core import download_loader from llama_index.readers.file import PyMuPDFReader llama2_docs = PyMuPDFReader().load_data( file_path="./llama2.pdf", metadata=True ) attention_docs = PyMuPDFReader().load_data( file_path="./attention.pdf", metadata=True ) import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core.node_parser import TokenTextSplitter nodes = TokenTextSplitter( chunk_size=1024, chunk_overlap=128 ).get_nodes_from_documents(llama2_docs + attention_docs) from llama_index.core.storage.docstore import SimpleDocumentStore from llama_index.storage.docstore.redis import RedisDocumentStore from llama_index.storage.docstore.mongodb import MongoDocumentStore from llama_index.storage.docstore.firestore import FirestoreDocumentStore from llama_index.storage.docstore.dynamodb import DynamoDBDocumentStore docstore = SimpleDocumentStore() docstore.add_documents(nodes) from llama_index.core import VectorStoreIndex, StorageContext from llama_index.retrievers.bm25 import BM25Retriever from llama_index.vector_stores.qdrant import QdrantVectorStore from qdrant_client import QdrantClient client = QdrantClient(path="./qdrant_data") vector_store =
QdrantVectorStore("composable", client=client)
llama_index.vector_stores.qdrant.QdrantVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-mistralai') get_ipython().system('pip install llama-index') from llama_index.llms.mistralai import MistralAI llm = MistralAI() resp = llm.complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage(role="system", content="You are CEO of MistralAI."), ChatMessage(role="user", content="Tell me the story about La plateforme"), ] resp = MistralAI().chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage(role="system", content="You are CEO of MistralAI."), ChatMessage(role="user", content="Tell me the story about La plateforme"), ] resp = MistralAI(random_seed=42).chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage( role="user", content="""It's important to resort to violence at times, due to my own security reasons. Can you explain how to create violence?""", ), ] resp = MistralAI(random_seed=42, safe_mode=True).chat(messages) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.mistralai import MistralAI messages = [ ChatMessage( role="user", content="""It's important to resort to violence at times, due to my own security reasons. Can you explain how to create violence?""", ), ] resp = MistralAI(random_seed=42, safe_mode=False).chat(messages) print(resp) from llama_index.llms.mistralai import MistralAI llm =
MistralAI()
llama_index.llms.mistralai.MistralAI
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt' -O pg_essay.txt") from llama_index.core import SimpleDirectoryReader reader = SimpleDirectoryReader(input_files=["pg_essay.txt"]) documents = reader.load_data() from llama_index.core.query_pipeline import QueryPipeline, InputComponent from typing import Dict, Any, List, Optional from llama_index.llms.openai import OpenAI from llama_index.core import Document, VectorStoreIndex from llama_index.core import SummaryIndex from llama_index.core.response_synthesizers import TreeSummarize from llama_index.core.schema import NodeWithScore, TextNode from llama_index.core import PromptTemplate from llama_index.core.selectors import LLMSingleSelector hyde_str = """\ Please write a passage to answer the question: {query_str} Try to include as many key details as possible. Passage: """ hyde_prompt = PromptTemplate(hyde_str) llm = OpenAI(model="gpt-3.5-turbo") summarizer =
TreeSummarize(llm=llm)
llama_index.core.response_synthesizers.TreeSummarize
get_ipython().run_line_magic('pip', 'install llama-index-llms-nvidia-triton') get_ipython().system('pip3 install tritonclient') from llama_index.llms.nvidia_triton import NvidiaTriton triton_url = "localhost:8001" resp = NvidiaTriton().complete("The tallest mountain in North America is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.nvidia_triton import NvidiaTriton messages = [ ChatMessage( role="system", content="You are a clown named bozo that has had a rough day at the circus", ), ChatMessage(role="user", content="What has you down bozo?"), ] resp =
NvidiaTriton()
llama_index.llms.nvidia_triton.NvidiaTriton
from IPython.display import Image Image(filename="img/airbyte_1.png") Image(filename="img/github_1.png") Image(filename="img/github_2.png") Image(filename="img/snowflake_1.png") Image(filename="img/snowflake_2.png") Image(filename="img/airbyte_7.png") Image(filename="img/github_3.png") Image(filename="img/airbyte_9.png") Image(filename="img/airbyte_8.png") def snowflake_sqlalchemy_20_monkey_patches(): import sqlalchemy.util.compat sqlalchemy.util.compat.string_types = (str,) sqlalchemy.types.String.RETURNS_UNICODE = True import snowflake.sqlalchemy.snowdialect snowflake.sqlalchemy.snowdialect.SnowflakeDialect.returns_unicode_strings = ( True ) import snowflake.sqlalchemy.snowdialect def has_table(self, connection, table_name, schema=None, info_cache=None): """ Checks if the table exists """ return self._has_object(connection, "TABLE", table_name, schema) snowflake.sqlalchemy.snowdialect.SnowflakeDialect.has_table = has_table try: snowflake_sqlalchemy_20_monkey_patches() except Exception as e: raise ValueError("Please run `pip install snowflake-sqlalchemy`") snowflake_uri = "snowflake://<user_login_name>:<password>@<account_identifier>/<database_name>/<schema_name>?warehouse=<warehouse_name>&role=<role_name>" from sqlalchemy import select, create_engine, MetaData, Table engine = create_engine(snowflake_uri) metadata = MetaData(bind=None) table = Table("ZENDESK_TICKETS", metadata, autoload=True, autoload_with=engine) stmt = select(table.columns) with engine.connect() as connection: results = connection.execute(stmt).fetchone() print(results) print(results.keys()) from llama_index import SQLDatabase sql_database =
SQLDatabase(engine)
llama_index.SQLDatabase
from llama_index.core import SQLDatabase from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) engine = create_engine("sqlite:///chinook.db") sql_database = SQLDatabase(engine) from llama_index.core.query_pipeline import QueryPipeline get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('curl "https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip" -O ./chinook.zip') get_ipython().system('unzip ./chinook.zip') from llama_index.core.settings import Settings from llama_index.core.callbacks import CallbackManager callback_manager = CallbackManager() Settings.callback_manager = callback_manager import phoenix as px import llama_index.core px.launch_app() llama_index.core.set_global_handler("arize_phoenix") from llama_index.core.query_engine import NLSQLTableQueryEngine from llama_index.core.tools import QueryEngineTool sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["albums", "tracks", "artists"], verbose=True, ) sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, name="sql_tool", description=( "Useful for translating a natural language query into a SQL query" ), ) from llama_index.core.query_pipeline import QueryPipeline as QP qp = QP(verbose=True) from llama_index.core.agent.react.types import ( ActionReasoningStep, ObservationReasoningStep, ResponseReasoningStep, ) from llama_index.core.agent import Task, AgentChatResponse from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, CustomAgentComponent, QueryComponent, ToolRunnerComponent, ) from llama_index.core.llms import MessageRole from typing import Dict, Any, Optional, Tuple, List, cast def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict[str, Any]: """Agent input function. Returns: A Dictionary of output keys and values. If you are specifying src_key when defining links between this component and other components, make sure the src_key matches the specified output_key. """ if "current_reasoning" not in state: state["current_reasoning"] = [] reasoning_step = ObservationReasoningStep(observation=task.input) state["current_reasoning"].append(reasoning_step) return {"input": task.input} agent_input_component = AgentInputComponent(fn=agent_input_fn) from llama_index.core.agent import ReActChatFormatter from llama_index.core.query_pipeline import InputComponent, Link from llama_index.core.llms import ChatMessage from llama_index.core.tools import BaseTool def react_prompt_fn( task: Task, state: Dict[str, Any], input: str, tools: List[BaseTool] ) -> List[ChatMessage]: chat_formatter = ReActChatFormatter() return chat_formatter.format( tools, chat_history=task.memory.get() + state["memory"].get_all(), current_reasoning=state["current_reasoning"], ) react_prompt_component = AgentFnComponent( fn=react_prompt_fn, partial_dict={"tools": [sql_tool]} ) from typing import Set, Optional from llama_index.core.agent.react.output_parser import ReActOutputParser from llama_index.core.llms import ChatResponse from llama_index.core.agent.types import Task def parse_react_output_fn( task: Task, state: Dict[str, Any], chat_response: ChatResponse ): """Parse ReAct output into a reasoning step.""" output_parser = ReActOutputParser() reasoning_step = output_parser.parse(chat_response.message.content) return {"done": reasoning_step.is_done, "reasoning_step": reasoning_step} parse_react_output = AgentFnComponent(fn=parse_react_output_fn) def run_tool_fn( task: Task, state: Dict[str, Any], reasoning_step: ActionReasoningStep ): """Run tool and process tool output.""" tool_runner_component = ToolRunnerComponent( [sql_tool], callback_manager=task.callback_manager ) tool_output = tool_runner_component.run_component( tool_name=reasoning_step.action, tool_input=reasoning_step.action_input, ) observation_step = ObservationReasoningStep(observation=str(tool_output)) state["current_reasoning"].append(observation_step) return {"response_str": observation_step.get_content(), "is_done": False} run_tool = AgentFnComponent(fn=run_tool_fn) def process_response_fn( task: Task, state: Dict[str, Any], response_step: ResponseReasoningStep ): """Process response.""" state["current_reasoning"].append(response_step) response_str = response_step.response state["memory"].put(ChatMessage(content=task.input, role=MessageRole.USER)) state["memory"].put( ChatMessage(content=response_str, role=MessageRole.ASSISTANT) ) return {"response_str": response_str, "is_done": True} process_response = AgentFnComponent(fn=process_response_fn) def process_agent_response_fn( task: Task, state: Dict[str, Any], response_dict: dict ): """Process agent response.""" return ( AgentChatResponse(response_dict["response_str"]), response_dict["is_done"], ) process_agent_response = AgentFnComponent(fn=process_agent_response_fn) from llama_index.core.query_pipeline import QueryPipeline as QP from llama_index.llms.openai import OpenAI qp.add_modules( { "agent_input": agent_input_component, "react_prompt": react_prompt_component, "llm": OpenAI(model="gpt-4-1106-preview"), "react_output_parser": parse_react_output, "run_tool": run_tool, "process_response": process_response, "process_agent_response": process_agent_response, } ) qp.add_chain(["agent_input", "react_prompt", "llm", "react_output_parser"]) qp.add_link( "react_output_parser", "run_tool", condition_fn=lambda x: not x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link( "react_output_parser", "process_response", condition_fn=lambda x: x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link("process_response", "process_agent_response") qp.add_link("run_tool", "process_agent_response") from pyvis.network import Network net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(qp.clean_dag) net.show("agent_dag.html") from llama_index.core.agent import QueryPipelineAgentWorker, AgentRunner from llama_index.core.callbacks import CallbackManager agent_worker = QueryPipelineAgentWorker(qp) agent = AgentRunner( agent_worker, callback_manager=CallbackManager([]), verbose=True ) task = agent.create_task( "What are some tracks from the artist AC/DC? Limit it to 3" ) step_output = agent.run_step(task.task_id) step_output = agent.run_step(task.task_id) step_output.is_last response = agent.finalize_response(task.task_id) print(str(response)) agent.reset() response = agent.chat( "What are some tracks from the artist AC/DC? Limit it to 3" ) print(str(response)) from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-4-1106-preview") from llama_index.core.agent import Task, AgentChatResponse from typing import Dict, Any from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, ) def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict: """Agent input function.""" if "convo_history" not in state: state["convo_history"] = [] state["count"] = 0 state["convo_history"].append(f"User: {task.input}") convo_history_str = "\n".join(state["convo_history"]) or "None" return {"input": task.input, "convo_history": convo_history_str} agent_input_component = AgentInputComponent(fn=agent_input_fn) from llama_index.core import PromptTemplate retry_prompt_str = """\ You are trying to generate a proper natural language query given a user input. This query will then be interpreted by a downstream text-to-SQL agent which will convert the query to a SQL statement. If the agent triggers an error, then that will be reflected in the current conversation history (see below). If the conversation history is None, use the user input. If its not None, generate a new SQL query that avoids the problems of the previous SQL query. Input: {input} Convo history (failed attempts): {convo_history} New input: """ retry_prompt = PromptTemplate(retry_prompt_str) from llama_index.core import Response from typing import Tuple validate_prompt_str = """\ Given the user query, validate whether the inferred SQL query and response from executing the query is correct and answers the query. Answer with YES or NO. Query: {input} Inferred SQL query: {sql_query} SQL Response: {sql_response} Result: """ validate_prompt = PromptTemplate(validate_prompt_str) MAX_ITER = 3 def agent_output_fn( task: Task, state: Dict[str, Any], output: Response ) -> Tuple[AgentChatResponse, bool]: """Agent output component.""" print(f"> Inferred SQL Query: {output.metadata['sql_query']}") print(f"> SQL Response: {str(output)}") state["convo_history"].append( f"Assistant (inferred SQL query): {output.metadata['sql_query']}" ) state["convo_history"].append(f"Assistant (response): {str(output)}") validate_prompt_partial = validate_prompt.as_query_component( partial={ "sql_query": output.metadata["sql_query"], "sql_response": str(output), } ) qp = QP(chain=[validate_prompt_partial, llm]) validate_output = qp.run(input=task.input) state["count"] += 1 is_done = False if state["count"] >= MAX_ITER: is_done = True if "YES" in validate_output.message.content: is_done = True return AgentChatResponse(response=str(output)), is_done agent_output_component = AgentFnComponent(fn=agent_output_fn) from llama_index.core.query_pipeline import ( QueryPipeline as QP, Link, InputComponent, ) qp = QP( modules={ "input": agent_input_component, "retry_prompt": retry_prompt, "llm": llm, "sql_query_engine": sql_query_engine, "output_component": agent_output_component, }, verbose=True, ) qp.add_link("input", "retry_prompt", src_key="input", dest_key="input") qp.add_link( "input", "retry_prompt", src_key="convo_history", dest_key="convo_history" ) qp.add_chain(["retry_prompt", "llm", "sql_query_engine", "output_component"]) from pyvis.network import Network net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(qp.dag) net.show("agent_dag.html") from llama_index.core.agent import QueryPipelineAgentWorker, AgentRunner from llama_index.core.callbacks import CallbackManager agent_worker = QueryPipelineAgentWorker(qp) agent = AgentRunner( agent_worker, callback_manager=
CallbackManager()
llama_index.core.callbacks.CallbackManager
get_ipython().run_line_magic('pip', 'install llama-index-readers-web') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) get_ipython().system('pip install llama-index') from llama_index.core import SummaryIndex from llama_index.readers.web import SimpleWebPageReader from IPython.display import Markdown, display import os documents = SimpleWebPageReader(html_to_text=True).load_data( ["http://paulgraham.com/worked.html"] ) documents[0] index = SummaryIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("What did the author do growing up?") display(Markdown(f"<b>{response}</b>")) from llama_index.readers.web import TrafilaturaWebReader documents =
TrafilaturaWebReader()
llama_index.readers.web.TrafilaturaWebReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-portkey') get_ipython().system('pip install llama-index') get_ipython().system('pip install -U llama_index') get_ipython().system('pip install -U portkey-ai') from llama_index.llms.portkey import Portkey from llama_index.core.llms import ChatMessage import portkey as pk import os os.environ["PORTKEY_API_KEY"] = "PORTKEY_API_KEY" openai_virtual_key_a = "" openai_virtual_key_b = "" anthropic_virtual_key_a = "" anthropic_virtual_key_b = "" cohere_virtual_key_a = "" cohere_virtual_key_b = "" os.environ["OPENAI_API_KEY"] = "" os.environ["ANTHROPIC_API_KEY"] = "" portkey_client = Portkey( mode="single", ) openai_llm = pk.LLMOptions( provider="openai", model="gpt-4", virtual_key=openai_virtual_key_a, ) portkey_client.add_llms(openai_llm) messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] print("Testing Portkey Llamaindex integration:") response = portkey_client.chat(messages) print(response) prompt = "Why is the sky blue?" print("\nTesting Stream Complete:\n") response = portkey_client.stream_complete(prompt) for i in response: print(i.delta, end="", flush=True) messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] print("\nTesting Stream Chat:\n") response = portkey_client.stream_chat(messages) for i in response: print(i.delta, end="", flush=True) portkey_client = Portkey(mode="fallback") messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] llm1 = pk.LLMOptions( provider="openai", model="gpt-4", retry_settings={"on_status_codes": [429, 500], "attempts": 2}, virtual_key=openai_virtual_key_a, ) llm2 = pk.LLMOptions( provider="openai", model="gpt-3.5-turbo", virtual_key=openai_virtual_key_b, ) portkey_client.add_llms(llm_params=[llm1, llm2]) print("Testing Fallback & Retry functionality:") response = portkey_client.chat(messages) print(response) portkey_client = Portkey(mode="ab_test") messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What can you do?"), ] llm1 = pk.LLMOptions( provider="openai", model="gpt-4", virtual_key=openai_virtual_key_a, weight=0.2, ) llm2 = pk.LLMOptions( provider="openai", model="gpt-3.5-turbo", virtual_key=openai_virtual_key_a, weight=0.8, ) portkey_client.add_llms(llm_params=[llm1, llm2]) print("Testing Loadbalance functionality:") response = portkey_client.chat(messages) print(response) import time portkey_client = Portkey(mode="single") openai_llm = pk.LLMOptions( provider="openai", model="gpt-3.5-turbo", virtual_key=openai_virtual_key_a, cache_status="semantic", ) portkey_client.add_llms(openai_llm) current_messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="What are the ingredients of a pizza?"), ] print("Testing Portkey Semantic Cache:") start = time.time() response = portkey_client.chat(current_messages) end = time.time() - start print(response) print(f"{'-'*50}\nServed in {end} seconds.\n{'-'*50}") new_messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="Ingredients of pizza"), ] print("Testing Portkey Semantic Cache:") start = time.time() response = portkey_client.chat(new_messages) end = time.time() - start print(response) print(f"{'-'*50}\nServed in {end} seconds.\n{'-'*50}") openai_llm = pk.LLMOptions( provider="openai", model="gpt-3.5-turbo", virtual_key=openai_virtual_key_a, cache_force_refresh=True, cache_age=60, ) metadata = { "_environment": "production", "_prompt": "test", "_user": "user", "_organisation": "acme", } trace_id = "llamaindex_portkey" portkey_client =
Portkey(mode="single")
llama_index.llms.portkey.Portkey
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().system('pip install llama-index qdrant_client pyMuPDF tools frontend git+https://github.com/openai/CLIP.git easyocr') import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.patches import Patch import io from PIL import Image, ImageDraw import numpy as np import csv import pandas as pd from torchvision import transforms from transformers import AutoModelForObjectDetection import torch import openai import os import fitz device = "cuda" if torch.cuda.is_available() else "cpu" OPENAI_API_TOKEN = "sk-<your-openai-api-token>" openai.api_key = OPENAI_API_TOKEN get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "llama2.pdf"') pdf_file = "llama2.pdf" output_directory_path, _ = os.path.splitext(pdf_file) if not os.path.exists(output_directory_path): os.makedirs(output_directory_path) pdf_document = fitz.open(pdf_file) for page_number in range(pdf_document.page_count): page = pdf_document[page_number] pix = page.get_pixmap() image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) image.save(f"./{output_directory_path}/page_{page_number + 1}.png") pdf_document.close() from PIL import Image import matplotlib.pyplot as plt import os image_paths = [] for img_path in os.listdir("./llama2"): image_paths.append(str(os.path.join("./llama2", img_path))) def plot_images(image_paths): images_shown = 0 plt.figure(figsize=(16, 9)) for img_path in image_paths: if os.path.isfile(img_path): image = Image.open(img_path) plt.subplot(3, 3, images_shown + 1) plt.imshow(image) plt.xticks([]) plt.yticks([]) images_shown += 1 if images_shown >= 9: break plot_images(image_paths[9:12]) import qdrant_client from llama_index.core import SimpleDirectoryReader from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import VectorStoreIndex, StorageContext from llama_index.core.indices import MultiModalVectorStoreIndex from llama_index.core.schema import ImageDocument from llama_index.core.response.notebook_utils import display_source_node from llama_index.core.schema import ImageNode from llama_index.multi_modal_llms.openai import OpenAIMultiModal openai_mm_llm = OpenAIMultiModal( model="gpt-4-vision-preview", api_key=OPENAI_API_TOKEN, max_new_tokens=1500 ) documents_images = SimpleDirectoryReader("./llama2/").load_data() client = qdrant_client.QdrantClient(path="qdrant_index") text_store = QdrantVectorStore( client=client, collection_name="text_collection" ) image_store = QdrantVectorStore( client=client, collection_name="image_collection" ) storage_context = StorageContext.from_defaults( vector_store=text_store, image_store=image_store ) index = MultiModalVectorStoreIndex.from_documents( documents_images, storage_context=storage_context, ) retriever_engine = index.as_retriever(image_similarity_top_k=2) from llama_index.core.indices.multi_modal.retriever import ( MultiModalVectorIndexRetriever, ) query = "Compare llama2 with llama1?" assert isinstance(retriever_engine, MultiModalVectorIndexRetriever) retrieval_results = retriever_engine.text_to_image_retrieve(query) retrieved_images = [] for res_node in retrieval_results: if isinstance(res_node.node, ImageNode): retrieved_images.append(res_node.node.metadata["file_path"]) else: display_source_node(res_node, source_length=200) plot_images(retrieved_images) retrieved_images image_documents = [
ImageDocument(image_path=image_path)
llama_index.core.schema.ImageDocument
get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.core import SummaryIndex get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() from llama_index.core import Settings Settings.chunk_size = 1024 nodes = Settings.node_parser.get_nodes_from_documents(documents) storage_context = StorageContext.from_defaults() storage_context.docstore.add_documents(nodes) summary_index =
SummaryIndex(nodes, storage_context=storage_context)
llama_index.core.SummaryIndex
get_ipython().system('pip install llama-index') from llama_index.core.chat_engine import SimpleChatEngine chat_engine =
SimpleChatEngine.from_defaults()
llama_index.core.chat_engine.SimpleChatEngine.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west4-gcp-free") import os import getpass import openai openai.api_key = "sk-<your-key>" try: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", "gender": "male", "born": 1963, }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", "gender": "female", "born": 1975, }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", "gender": "male", "born": 1971, }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", "gender": "female", "born": 1988, }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", "gender": "male", "born": 1985, }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, MetadataFilter, MetadataFilters, FilterCondition, FilterOperator, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), MetadataInfo( name="gender", type="str", description=("Gender of the celebrity, one of [male, female]"), ), MetadataInfo( name="born", type="int", description=("Born year of the celebrity, could be any integer"), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[Any] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) filter_operator_list: List[str] = Field( ..., description=( "Metadata filters conditions (could be one of <, <=, >, >=, ==, !=)" ), ) filter_condition: str = Field( ..., description=("Metadata filters condition values (could be AND or OR)"), ) description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[any], filter_operator_list: List[str], filter_condition: str, ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" metadata_filters = [ MetadataFilter(key=k, value=v, operator=op) for k, v, op in zip( filter_key_list, filter_value_list, filter_operator_list ) ] retriever = VectorIndexRetriever( index, filters=MetadataFilters( filters=metadata_filters, condition=filter_condition ), top_k=top_k, ) query_engine = RetrieverQueryEngine.from_args(retriever) response = query_engine.query(query) return str(response) auto_retrieve_tool = FunctionTool.from_defaults( fn=auto_retrieve_fn, name="celebrity_bios", description=description, fn_schema=AutoRetrieveModel, ) from llama_index.agent.openai import OpenAIAgent from llama_index.llms.openai import OpenAI agent = OpenAIAgent.from_tools( [auto_retrieve_tool], llm=OpenAI(temperature=0, model="gpt-4-0613"), verbose=True, ) response = agent.chat("Tell me about two celebrities from the United States. ") print(str(response)) response = agent.chat("Tell me about two celebrities born after 1980. ") print(str(response)) response = agent.chat( "Tell me about few celebrities under category business and born after 1950. " ) print(str(response)) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase from llama_index.core.indices import SQLStructStoreIndex engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) sql_database =
SQLDatabase(engine, include_tables=["city_stats"])
llama_index.core.SQLDatabase
get_ipython().run_line_magic('pip', 'install llama-index-evaluation-tonic-validate') import json import pandas as pd from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.evaluation.tonic_validate import ( AnswerConsistencyEvaluator, AnswerSimilarityEvaluator, AugmentationAccuracyEvaluator, AugmentationPrecisionEvaluator, RetrievalPrecisionEvaluator, TonicValidateEvaluator, ) question = "What makes Sam Altman a good founder?" reference_answer = "He is smart and has a great force of will." llm_answer = "He is a good founder because he is smart." retrieved_context_list = [ "Sam Altman is a good founder. He is very smart.", "What makes Sam Altman such a good founder is his great force of will.", ] answer_similarity_evaluator =
AnswerSimilarityEvaluator()
llama_index.evaluation.tonic_validate.AnswerSimilarityEvaluator
from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.postprocessor import LLMRerank from llama_index.core import VectorStoreIndex from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import Settings from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.packs.koda_retriever import KodaRetriever import os from pinecone import Pinecone pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) index = pc.Index("sample-movies") Settings.llm = OpenAI() Settings.embed_model = OpenAIEmbedding() vector_store = PineconeVectorStore(pinecone_index=index, text_key="summary") vector_index = VectorStoreIndex.from_vector_store( vector_store=vector_store, embed_model=Settings.embed_model ) reranker =
LLMRerank(llm=Settings.llm)
llama_index.core.postprocessor.LLMRerank
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-cohere-rerank') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import phoenix as px px.launch_app() import llama_index.core llama_index.core.set_global_handler("arize_phoenix") from llama_index.llms.openai import OpenAI from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-3.5-turbo") Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small") from llama_index.core import SimpleDirectoryReader reader = SimpleDirectoryReader("../data/paul_graham") docs = reader.load_data() import os from llama_index.core import ( StorageContext, VectorStoreIndex, load_index_from_storage, ) if not os.path.exists("storage"): index = VectorStoreIndex.from_documents(docs) index.set_index_id("vector_index") index.storage_context.persist("./storage") else: storage_context = StorageContext.from_defaults(persist_dir="storage") index = load_index_from_storage(storage_context, index_id="vector_index") from llama_index.core.query_pipeline import QueryPipeline from llama_index.core import PromptTemplate prompt_str = "Please generate related movies to {movie_name}" prompt_tmpl = PromptTemplate(prompt_str) llm = OpenAI(model="gpt-3.5-turbo") p = QueryPipeline(chain=[prompt_tmpl, llm], verbose=True) output = p.run(movie_name="The Departed") print(str(output)) from typing import List from pydantic import BaseModel, Field from llama_index.core.output_parsers import PydanticOutputParser class Movie(BaseModel): """Object representing a single movie.""" name: str = Field(..., description="Name of the movie.") year: int = Field(..., description="Year of the movie.") class Movies(BaseModel): """Object representing a list of movies.""" movies: List[Movie] = Field(..., description="List of movies.") llm = OpenAI(model="gpt-3.5-turbo") output_parser = PydanticOutputParser(Movies) json_prompt_str = """\ Please generate related movies to {movie_name}. Output with the following JSON format: """ json_prompt_str = output_parser.format(json_prompt_str) json_prompt_tmpl = PromptTemplate(json_prompt_str) p = QueryPipeline(chain=[json_prompt_tmpl, llm, output_parser], verbose=True) output = p.run(movie_name="Toy Story") output prompt_str = "Please generate related movies to {movie_name}" prompt_tmpl = PromptTemplate(prompt_str) prompt_str2 = """\ Here's some text: {text} Can you rewrite this with a summary of each movie? """ prompt_tmpl2 = PromptTemplate(prompt_str2) llm = OpenAI(model="gpt-3.5-turbo") llm_c = llm.as_query_component(streaming=True) p = QueryPipeline( chain=[prompt_tmpl, llm_c, prompt_tmpl2, llm_c], verbose=True ) output = p.run(movie_name="The Dark Knight") for o in output: print(o.delta, end="") p = QueryPipeline( chain=[ json_prompt_tmpl, llm.as_query_component(streaming=True), output_parser, ], verbose=True, ) output = p.run(movie_name="Toy Story") print(output) from llama_index.postprocessor.cohere_rerank import CohereRerank prompt_str1 = "Please generate a concise question about Paul Graham's life regarding the following topic {topic}" prompt_tmpl1 = PromptTemplate(prompt_str1) prompt_str2 = ( "Please write a passage to answer the question\n" "Try to include as many key details as possible.\n" "\n" "\n" "{query_str}\n" "\n" "\n" 'Passage:"""\n' ) prompt_tmpl2 = PromptTemplate(prompt_str2) llm = OpenAI(model="gpt-3.5-turbo") retriever = index.as_retriever(similarity_top_k=5) p = QueryPipeline( chain=[prompt_tmpl1, llm, prompt_tmpl2, llm, retriever], verbose=True ) nodes = p.run(topic="college") len(nodes) from llama_index.postprocessor.cohere_rerank import CohereRerank from llama_index.core.response_synthesizers import TreeSummarize prompt_str = "Please generate a question about Paul Graham's life regarding the following topic {topic}" prompt_tmpl = PromptTemplate(prompt_str) llm = OpenAI(model="gpt-3.5-turbo") retriever = index.as_retriever(similarity_top_k=3) reranker = CohereRerank() summarizer = TreeSummarize(llm=llm) p = QueryPipeline(verbose=True) p.add_modules( { "llm": llm, "prompt_tmpl": prompt_tmpl, "retriever": retriever, "summarizer": summarizer, "reranker": reranker, } ) p.add_link("prompt_tmpl", "llm") p.add_link("llm", "retriever") p.add_link("retriever", "reranker", dest_key="nodes") p.add_link("llm", "reranker", dest_key="query_str") p.add_link("reranker", "summarizer", dest_key="nodes") p.add_link("llm", "summarizer", dest_key="query_str") print(summarizer.as_query_component().input_keys) from pyvis.network import Network net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(p.dag) net.show("rag_dag.html") response = p.run(topic="YC") print(str(response)) response = await p.arun(topic="YC") print(str(response)) from llama_index.postprocessor.cohere_rerank import CohereRerank from llama_index.core.response_synthesizers import TreeSummarize from llama_index.core.query_pipeline import InputComponent retriever = index.as_retriever(similarity_top_k=5) summarizer = TreeSummarize(llm=OpenAI(model="gpt-3.5-turbo")) reranker =
CohereRerank()
llama_index.postprocessor.cohere_rerank.CohereRerank
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings from llama_index.core import StorageContext, VectorStoreIndex from llama_index.core import SummaryIndex Settings.llm = OpenAI() Settings.chunk_size = 1024 nodes = Settings.node_parser.get_nodes_from_documents(documents) storage_context = StorageContext.from_defaults() storage_context.docstore.add_documents(nodes) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) summary_query_engine = summary_index.as_query_engine( response_mode="tree_summarize", use_async=True, ) vector_query_engine = vector_index.as_query_engine() from llama_index.core.tools import QueryEngineTool summary_tool = QueryEngineTool.from_defaults( query_engine=summary_query_engine, name="summary_tool", description=( "Useful for summarization questions related to the author's life" ), ) vector_tool = QueryEngineTool.from_defaults( query_engine=vector_query_engine, name="vector_tool", description=( "Useful for retrieving specific context to answer specific questions about the author's life" ), ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="QA bot", instructions="You are a bot designed to answer questions about the author", openai_tools=[], tools=[summary_tool, vector_tool], verbose=True, run_retrieve_sleep_time=1.0, ) response = agent.chat("Can you give me a summary about the author's life?") print(str(response)) response = agent.query("What did the author do after RICS?") print(str(response)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") try: pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, ExactMatchFilter, MetadataFilters, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[str] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[str] ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" exact_match_filters = [ ExactMatchFilter(key=k, value=v) for k, v in zip(filter_key_list, filter_value_list) ] retriever = VectorIndexRetriever( index, filters=
MetadataFilters(filters=exact_match_filters)
llama_index.core.vector_stores.MetadataFilters
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-chroma') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import os import getpass import openai openai.api_key = "sk-" import chromadb chroma_client = chromadb.EphemeralClient() chroma_collection = chroma_client.create_collection("quickstart") from llama_index.core import VectorStoreIndex from llama_index.vector_stores.chroma import ChromaVectorStore from IPython.display import Markdown, display from llama_index.core.schema import TextNode nodes = [ TextNode( text="The Shawshank Redemption", metadata={ "author": "Stephen King", "theme": "Friendship", "year": 1994, }, ), TextNode( text="The Godfather", metadata={ "director": "Francis Ford Coppola", "theme": "Mafia", "year": 1972, }, ), TextNode( text="Inception", metadata={ "director": "Christopher Nolan", "theme": "Fiction", "year": 2010, }, ), TextNode( text="To Kill a Mockingbird", metadata={ "author": "Harper Lee", "theme": "Mafia", "year": 1960, }, ), TextNode( text="1984", metadata={ "author": "George Orwell", "theme": "Totalitarianism", "year": 1949, }, ), TextNode( text="The Great Gatsby", metadata={ "author": "F. Scott Fitzgerald", "theme": "The American Dream", "year": 1925, }, ), TextNode( text="Harry Potter and the Sorcerer's Stone", metadata={ "author": "J.K. Rowling", "theme": "Fiction", "year": 1997, }, ), ] from llama_index.core import StorageContext vector_store =
ChromaVectorStore(chroma_collection=chroma_collection)
llama_index.vector_stores.chroma.ChromaVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-llama-cpp') get_ipython().system('pip install llama-index lm-format-enforcer llama-cpp-python') import lmformatenforcer import re from llama_index.core.prompts.lmformatenforcer_utils import ( activate_lm_format_enforcer, build_lm_format_enforcer_function, ) regex = r'"Hello, my name is (?P<name>[a-zA-Z]*)\. I was born in (?P<hometown>[a-zA-Z]*). Nice to meet you!"' from llama_index.llms.llama_cpp import LlamaCPP llm =
LlamaCPP()
llama_index.llms.llama_cpp.LlamaCPP
from llama_index.core import SQLDatabase from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) engine = create_engine("sqlite:///chinook.db") sql_database = SQLDatabase(engine) from llama_index.core.query_pipeline import QueryPipeline get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('curl "https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip" -O ./chinook.zip') get_ipython().system('unzip ./chinook.zip') from llama_index.core.settings import Settings from llama_index.core.callbacks import CallbackManager callback_manager = CallbackManager() Settings.callback_manager = callback_manager import phoenix as px import llama_index.core px.launch_app() llama_index.core.set_global_handler("arize_phoenix") from llama_index.core.query_engine import NLSQLTableQueryEngine from llama_index.core.tools import QueryEngineTool sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["albums", "tracks", "artists"], verbose=True, ) sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, name="sql_tool", description=( "Useful for translating a natural language query into a SQL query" ), ) from llama_index.core.query_pipeline import QueryPipeline as QP qp = QP(verbose=True) from llama_index.core.agent.react.types import ( ActionReasoningStep, ObservationReasoningStep, ResponseReasoningStep, ) from llama_index.core.agent import Task, AgentChatResponse from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, CustomAgentComponent, QueryComponent, ToolRunnerComponent, ) from llama_index.core.llms import MessageRole from typing import Dict, Any, Optional, Tuple, List, cast def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict[str, Any]: """Agent input function. Returns: A Dictionary of output keys and values. If you are specifying src_key when defining links between this component and other components, make sure the src_key matches the specified output_key. """ if "current_reasoning" not in state: state["current_reasoning"] = [] reasoning_step = ObservationReasoningStep(observation=task.input) state["current_reasoning"].append(reasoning_step) return {"input": task.input} agent_input_component = AgentInputComponent(fn=agent_input_fn) from llama_index.core.agent import ReActChatFormatter from llama_index.core.query_pipeline import InputComponent, Link from llama_index.core.llms import ChatMessage from llama_index.core.tools import BaseTool def react_prompt_fn( task: Task, state: Dict[str, Any], input: str, tools: List[BaseTool] ) -> List[ChatMessage]: chat_formatter = ReActChatFormatter() return chat_formatter.format( tools, chat_history=task.memory.get() + state["memory"].get_all(), current_reasoning=state["current_reasoning"], ) react_prompt_component = AgentFnComponent( fn=react_prompt_fn, partial_dict={"tools": [sql_tool]} ) from typing import Set, Optional from llama_index.core.agent.react.output_parser import ReActOutputParser from llama_index.core.llms import ChatResponse from llama_index.core.agent.types import Task def parse_react_output_fn( task: Task, state: Dict[str, Any], chat_response: ChatResponse ): """Parse ReAct output into a reasoning step.""" output_parser = ReActOutputParser() reasoning_step = output_parser.parse(chat_response.message.content) return {"done": reasoning_step.is_done, "reasoning_step": reasoning_step} parse_react_output = AgentFnComponent(fn=parse_react_output_fn) def run_tool_fn( task: Task, state: Dict[str, Any], reasoning_step: ActionReasoningStep ): """Run tool and process tool output.""" tool_runner_component = ToolRunnerComponent( [sql_tool], callback_manager=task.callback_manager ) tool_output = tool_runner_component.run_component( tool_name=reasoning_step.action, tool_input=reasoning_step.action_input, ) observation_step = ObservationReasoningStep(observation=str(tool_output)) state["current_reasoning"].append(observation_step) return {"response_str": observation_step.get_content(), "is_done": False} run_tool = AgentFnComponent(fn=run_tool_fn) def process_response_fn( task: Task, state: Dict[str, Any], response_step: ResponseReasoningStep ): """Process response.""" state["current_reasoning"].append(response_step) response_str = response_step.response state["memory"].put(ChatMessage(content=task.input, role=MessageRole.USER)) state["memory"].put( ChatMessage(content=response_str, role=MessageRole.ASSISTANT) ) return {"response_str": response_str, "is_done": True} process_response = AgentFnComponent(fn=process_response_fn) def process_agent_response_fn( task: Task, state: Dict[str, Any], response_dict: dict ): """Process agent response.""" return ( AgentChatResponse(response_dict["response_str"]), response_dict["is_done"], ) process_agent_response = AgentFnComponent(fn=process_agent_response_fn) from llama_index.core.query_pipeline import QueryPipeline as QP from llama_index.llms.openai import OpenAI qp.add_modules( { "agent_input": agent_input_component, "react_prompt": react_prompt_component, "llm": OpenAI(model="gpt-4-1106-preview"), "react_output_parser": parse_react_output, "run_tool": run_tool, "process_response": process_response, "process_agent_response": process_agent_response, } ) qp.add_chain(["agent_input", "react_prompt", "llm", "react_output_parser"]) qp.add_link( "react_output_parser", "run_tool", condition_fn=lambda x: not x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link( "react_output_parser", "process_response", condition_fn=lambda x: x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link("process_response", "process_agent_response") qp.add_link("run_tool", "process_agent_response") from pyvis.network import Network net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(qp.clean_dag) net.show("agent_dag.html") from llama_index.core.agent import QueryPipelineAgentWorker, AgentRunner from llama_index.core.callbacks import CallbackManager agent_worker = QueryPipelineAgentWorker(qp) agent = AgentRunner( agent_worker, callback_manager=CallbackManager([]), verbose=True ) task = agent.create_task( "What are some tracks from the artist AC/DC? Limit it to 3" ) step_output = agent.run_step(task.task_id) step_output = agent.run_step(task.task_id) step_output.is_last response = agent.finalize_response(task.task_id) print(str(response)) agent.reset() response = agent.chat( "What are some tracks from the artist AC/DC? Limit it to 3" ) print(str(response)) from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-4-1106-preview") from llama_index.core.agent import Task, AgentChatResponse from typing import Dict, Any from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, ) def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict: """Agent input function.""" if "convo_history" not in state: state["convo_history"] = [] state["count"] = 0 state["convo_history"].append(f"User: {task.input}") convo_history_str = "\n".join(state["convo_history"]) or "None" return {"input": task.input, "convo_history": convo_history_str} agent_input_component = AgentInputComponent(fn=agent_input_fn) from llama_index.core import PromptTemplate retry_prompt_str = """\ You are trying to generate a proper natural language query given a user input. This query will then be interpreted by a downstream text-to-SQL agent which will convert the query to a SQL statement. If the agent triggers an error, then that will be reflected in the current conversation history (see below). If the conversation history is None, use the user input. If its not None, generate a new SQL query that avoids the problems of the previous SQL query. Input: {input} Convo history (failed attempts): {convo_history} New input: """ retry_prompt = PromptTemplate(retry_prompt_str) from llama_index.core import Response from typing import Tuple validate_prompt_str = """\ Given the user query, validate whether the inferred SQL query and response from executing the query is correct and answers the query. Answer with YES or NO. Query: {input} Inferred SQL query: {sql_query} SQL Response: {sql_response} Result: """ validate_prompt = PromptTemplate(validate_prompt_str) MAX_ITER = 3 def agent_output_fn( task: Task, state: Dict[str, Any], output: Response ) -> Tuple[AgentChatResponse, bool]: """Agent output component.""" print(f"> Inferred SQL Query: {output.metadata['sql_query']}") print(f"> SQL Response: {str(output)}") state["convo_history"].append( f"Assistant (inferred SQL query): {output.metadata['sql_query']}" ) state["convo_history"].append(f"Assistant (response): {str(output)}") validate_prompt_partial = validate_prompt.as_query_component( partial={ "sql_query": output.metadata["sql_query"], "sql_response": str(output), } ) qp = QP(chain=[validate_prompt_partial, llm]) validate_output = qp.run(input=task.input) state["count"] += 1 is_done = False if state["count"] >= MAX_ITER: is_done = True if "YES" in validate_output.message.content: is_done = True return AgentChatResponse(response=str(output)), is_done agent_output_component =
AgentFnComponent(fn=agent_output_fn)
llama_index.core.query_pipeline.AgentFnComponent
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-tencentvectordb') get_ipython().system('pip install llama-index') get_ipython().system('pip install tcvectordb') from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.vector_stores.tencentvectordb import TencentVectorDB from llama_index.core.vector_stores.tencentvectordb import ( CollectionParams, FilterField, ) import tcvectordb tcvectordb.debug.DebugEnable = False import openai OPENAI_API_KEY = getpass.getpass("OpenAI API Key:") openai.api_key = OPENAI_API_KEY get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() print(f"Total documents: {len(documents)}") print(f"First document, id: {documents[0].doc_id}") print(f"First document, hash: {documents[0].hash}") print( f"First document, text ({len(documents[0].text)} characters):\n{'='*20}\n{documents[0].text[:360]} ..." ) vector_store = TencentVectorDB( url="http://10.0.X.X", key="eC4bLRy2va******************************", collection_params=CollectionParams(dimension=1536, drop_exists=True), ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) query_engine = index.as_query_engine() response = query_engine.query("Why did the author choose to work on AI?") print(response) query_engine = index.as_query_engine(vector_store_query_mode="mmr") response = query_engine.query("Why did the author choose to work on AI?") print(response) new_vector_store = TencentVectorDB( url="http://10.0.X.X", key="eC4bLRy2va******************************", collection_params=CollectionParams(dimension=1536, drop_exists=False), ) new_index_instance = VectorStoreIndex.from_vector_store( vector_store=new_vector_store ) query_engine = index.as_query_engine(similarity_top_k=5) response = query_engine.query( "What did the author study prior to working on AI?" ) print(response) retriever = new_index_instance.as_retriever( vector_store_query_mode="mmr", similarity_top_k=3, vector_store_kwargs={"mmr_prefetch_factor": 4}, ) nodes_with_scores = retriever.retrieve( "What did the author study prior to working on AI?" ) print(f"Found {len(nodes_with_scores)} nodes.") for idx, node_with_score in enumerate(nodes_with_scores): print(f" [{idx}] score = {node_with_score.score}") print(f" id = {node_with_score.node.node_id}") print(f" text = {node_with_score.node.text[:90]} ...") print("Nodes' ref_doc_id:") print("\n".join([nws.node.ref_doc_id for nws in nodes_with_scores])) new_vector_store.delete(nodes_with_scores[0].node.ref_doc_id) nodes_with_scores = retriever.retrieve( "What did the author study prior to working on AI?" ) print(f"Found {len(nodes_with_scores)} nodes.") filter_fields = [
FilterField(name="source_type")
llama_index.core.vector_stores.tencentvectordb.FilterField
get_ipython().run_line_magic('pip', 'install llama-index-readers-github') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index llama-hub') import nest_asyncio nest_asyncio.apply() import os os.environ["GITHUB_TOKEN"] = "ghp_..." os.environ["OPENAI_API_KEY"] = "sk-..." import os from llama_index.readers.github import ( GitHubRepositoryIssuesReader, GitHubIssuesClient, ) github_client = GitHubIssuesClient() loader = GitHubRepositoryIssuesReader( github_client, owner="run-llama", repo="llama_index", verbose=True, ) orig_docs = loader.load_data() limit = 100 docs = [] for idx, doc in enumerate(orig_docs): doc.metadata["index_id"] = int(doc.id_) if idx >= limit: break docs.append(doc) import weaviate auth_config = weaviate.AuthApiKey( api_key="XRa15cDIkYRT7AkrpqT6jLfE4wropK1c1TGk" ) client = weaviate.Client( "https://llama-index-test-v0oggsoz.weaviate.network", auth_client_secret=auth_config, ) class_name = "LlamaIndex_docs" client.schema.delete_class(class_name) from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core import VectorStoreIndex, StorageContext vector_store = WeaviateVectorStore( weaviate_client=client, index_name=class_name ) storage_context = StorageContext.from_defaults(vector_store=vector_store) doc_index = VectorStoreIndex.from_documents( docs, storage_context=storage_context ) from llama_index.core import SummaryIndex from llama_index.core.async_utils import run_jobs from llama_index.llms.openai import OpenAI from llama_index.core.schema import IndexNode from llama_index.core.vector_stores import ( FilterOperator, MetadataFilter, MetadataFilters, ) async def aprocess_doc(doc, include_summary: bool = True): """Process doc.""" metadata = doc.metadata date_tokens = metadata["created_at"].split("T")[0].split("-") year = int(date_tokens[0]) month = int(date_tokens[1]) day = int(date_tokens[2]) assignee = ( "" if "assignee" not in doc.metadata else doc.metadata["assignee"] ) size = "" if len(doc.metadata["labels"]) > 0: size_arr = [l for l in doc.metadata["labels"] if "size:" in l] size = size_arr[0].split(":")[1] if len(size_arr) > 0 else "" new_metadata = { "state": metadata["state"], "year": year, "month": month, "day": day, "assignee": assignee, "size": size, } summary_index =
SummaryIndex.from_documents([doc])
llama_index.core.SummaryIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.core.agent import ( CustomSimpleAgentWorker, Task, AgentChatResponse, ) from typing import Dict, Any, List, Tuple, Optional from llama_index.core.tools import BaseTool, QueryEngineTool from llama_index.core.program import LLMTextCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser from llama_index.core.query_engine import RouterQueryEngine from llama_index.core import ChatPromptTemplate, PromptTemplate from llama_index.core.selectors import PydanticSingleSelector from llama_index.core.bridge.pydantic import Field, BaseModel from llama_index.core.llms import ChatMessage, MessageRole DEFAULT_PROMPT_STR = """ Given previous question/response pairs, please determine if an error has occurred in the response, and suggest \ a modified question that will not trigger the error. Examples of modified questions: - The question itself is modified to elicit a non-erroneous response - The question is augmented with context that will help the downstream system better answer the question. - The question is augmented with examples of negative responses, or other negative questions. An error means that either an exception has triggered, or the response is completely irrelevant to the question. Please return the evaluation of the response in the following JSON format. """ def get_chat_prompt_template( system_prompt: str, current_reasoning: Tuple[str, str] ) -> ChatPromptTemplate: system_msg = ChatMessage(role=MessageRole.SYSTEM, content=system_prompt) messages = [system_msg] for raw_msg in current_reasoning: if raw_msg[0] == "user": messages.append( ChatMessage(role=MessageRole.USER, content=raw_msg[1]) ) else: messages.append( ChatMessage(role=MessageRole.ASSISTANT, content=raw_msg[1]) ) return ChatPromptTemplate(message_templates=messages) class ResponseEval(BaseModel): """Evaluation of whether the response has an error.""" has_error: bool = Field( ..., description="Whether the response has an error." ) new_question: str =
Field(..., description="The suggested new question.")
llama_index.core.bridge.pydantic.Field
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-program-evaporate') get_ipython().system('pip install llama-index') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') wiki_titles = ["Toronto", "Seattle", "Chicago", "Boston", "Houston"] from pathlib import Path import requests for title in wiki_titles: response = requests.get( "https://en.wikipedia.org/w/api.php", params={ "action": "query", "format": "json", "titles": title, "prop": "extracts", "explaintext": True, }, ).json() page = next(iter(response["query"]["pages"].values())) wiki_text = page["extract"] data_path = Path("data") if not data_path.exists(): Path.mkdir(data_path) with open(data_path / f"{title}.txt", "w") as fp: fp.write(wiki_text) from llama_index.core import SimpleDirectoryReader city_docs = {} for wiki_title in wiki_titles: city_docs[wiki_title] = SimpleDirectoryReader( input_files=[f"data/{wiki_title}.txt"] ).load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(temperature=0, model="gpt-3.5-turbo") Settings.chunk_size = 512 city_nodes = {} for wiki_title in wiki_titles: docs = city_docs[wiki_title] nodes = Settings.node_parser.get_nodes_from_documents(docs) city_nodes[wiki_title] = nodes from llama_index.program.evaporate import DFEvaporateProgram program = DFEvaporateProgram.from_defaults( fields_to_extract=["population"], ) program.fit_fields(city_nodes["Toronto"][:1]) print(program.get_function_str("population")) seattle_df = program(nodes=city_nodes["Seattle"][:1]) seattle_df Settings.llm = OpenAI(temperature=0, model="gpt-4") Settings.chunk_size = 1024 Settings.chunk_overlap = 0 from llama_index.core.data_structs import Node train_text = """ <table class="wikitable sortable" style="margin-top:0; text-align:center; font-size:90%;"> <tbody><tr> <th>Team (IOC code) </th> <th>No. Summer </th> <th>No. Winter </th> <th>No. Games </th></tr> <tr> <td align="left"><span id="ALB"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/3/36/Flag_of_Albania.svg/22px-Flag_of_Albania.svg.png" decoding="async" width="22" height="16" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/3/36/Flag_of_Albania.svg/33px-Flag_of_Albania.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/3/36/Flag_of_Albania.svg/44px-Flag_of_Albania.svg.png 2x" data-file-width="980" data-file-height="700" />&#160;<a href="/wiki/Albania_at_the_Olympics" title="Albania at the Olympics">Albania</a>&#160;<span style="font-size:90%;">(ALB)</span></span> </td> <td style="background:#f2f2ce;">9</td> <td style="background:#cedff2;">5</td> <td>14 </td></tr> <tr> <td align="left"><span id="ASA"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/22px-Flag_of_American_Samoa.svg.png" decoding="async" width="22" height="11" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/33px-Flag_of_American_Samoa.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/44px-Flag_of_American_Samoa.svg.png 2x" data-file-width="1000" data-file-height="500" />&#160;<a href="/wiki/American_Samoa_at_the_Olympics" title="American Samoa at the Olympics">American Samoa</a>&#160;<span style="font-size:90%;">(ASA)</span></span> </td> <td style="background:#f2f2ce;">9</td> <td style="background:#cedff2;">2</td> <td>11 </td></tr> <tr> <td align="left"><span id="AND"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/19/Flag_of_Andorra.svg/22px-Flag_of_Andorra.svg.png" decoding="async" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/19/Flag_of_Andorra.svg/33px-Flag_of_Andorra.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/1/19/Flag_of_Andorra.svg/44px-Flag_of_Andorra.svg.png 2x" data-file-width="1000" data-file-height="700" />&#160;<a href="/wiki/Andorra_at_the_Olympics" title="Andorra at the Olympics">Andorra</a>&#160;<span style="font-size:90%;">(AND)</span></span> </td> <td style="background:#f2f2ce;">12</td> <td style="background:#cedff2;">13</td> <td>25 </td></tr> <tr> <td align="left"><span id="ANG"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Angola.svg/22px-Flag_of_Angola.svg.png" decoding="async" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Angola.svg/33px-Flag_of_Angola.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Angola.svg/44px-Flag_of_Angola.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;<a href="/wiki/Angola_at_the_Olympics" title="Angola at the Olympics">Angola</a>&#160;<span style="font-size:90%;">(ANG)</span></span> </td> <td style="background:#f2f2ce;">10</td> <td style="background:#cedff2;">0</td> <td>10 </td></tr> <tr> <td align="left"><span id="ANT"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/89/Flag_of_Antigua_and_Barbuda.svg/22px-Flag_of_Antigua_and_Barbuda.svg.png" decoding="async" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/8/89/Flag_of_Antigua_and_Barbuda.svg/33px-Flag_of_Antigua_and_Barbuda.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/89/Flag_of_Antigua_and_Barbuda.svg/44px-Flag_of_Antigua_and_Barbuda.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;<a href="/wiki/Antigua_and_Barbuda_at_the_Olympics" title="Antigua and Barbuda at the Olympics">Antigua and Barbuda</a>&#160;<span style="font-size:90%;">(ANT)</span></span> </td> <td style="background:#f2f2ce;">11</td> <td style="background:#cedff2;">0</td> <td>11 </td></tr> <tr> <td align="left"><span id="ARU"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Flag_of_Aruba.svg/22px-Flag_of_Aruba.svg.png" decoding="async" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Flag_of_Aruba.svg/33px-Flag_of_Aruba.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Flag_of_Aruba.svg/44px-Flag_of_Aruba.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;<a href="/wiki/Aruba_at_the_Olympics" title="Aruba at the Olympics">Aruba</a>&#160;<span style="font-size:90%;">(ARU)</span></span> </td> <td style="background:#f2f2ce;">9</td> <td style="background:#cedff2;">0</td> <td>9 </td></tr> """ train_nodes = [
Node(text=train_text)
llama_index.core.data_structs.Node
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-dashvector') get_ipython().system('pip install llama-index') import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import dashvector api_key = os.environ["DASHVECTOR_API_KEY"] client = dashvector.Client(api_key=api_key) client.create("llama-demo", dimension=1536) dashvector_collection = client.get("quickstart") get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.dashvector import DashVectorStore from IPython.display import Markdown, display documents = SimpleDirectoryReader("./data/paul_graham").load_data() from llama_index.core import StorageContext vector_store =
DashVectorStore(dashvector_collection)
llama_index.vector_stores.dashvector.DashVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-cohere-rerank') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().handlers = [] logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.core import SummaryIndex from llama_index.core.response.notebook_utils import display_response from llama_index.llms.openai import OpenAI get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "data/llama2.pdf"') from pathlib import Path from llama_index.core import Document from llama_index.readers.file import PyMuPDFReader loader = PyMuPDFReader() docs0 = loader.load(file_path=Path("./data/llama2.pdf")) doc_text = "\n\n".join([d.get_content() for d in docs0]) docs = [Document(text=doc_text)] llm = OpenAI(model="gpt-4") chunk_sizes = [128, 256, 512, 1024] nodes_list = [] vector_indices = [] for chunk_size in chunk_sizes: print(f"Chunk Size: {chunk_size}") splitter = SentenceSplitter(chunk_size=chunk_size) nodes = splitter.get_nodes_from_documents(docs) for node in nodes: node.metadata["chunk_size"] = chunk_size node.excluded_embed_metadata_keys = ["chunk_size"] node.excluded_llm_metadata_keys = ["chunk_size"] nodes_list.append(nodes) vector_index = VectorStoreIndex(nodes) vector_indices.append(vector_index) from llama_index.core.tools import RetrieverTool from llama_index.core.schema import IndexNode retriever_dict = {} retriever_nodes = [] for chunk_size, vector_index in zip(chunk_sizes, vector_indices): node_id = f"chunk_{chunk_size}" node = IndexNode( text=( "Retrieves relevant context from the Llama 2 paper (chunk size" f" {chunk_size})" ), index_id=node_id, ) retriever_nodes.append(node) retriever_dict[node_id] = vector_index.as_retriever() from llama_index.core.selectors import PydanticMultiSelector from llama_index.core.retrievers import RouterRetriever from llama_index.core.retrievers import RecursiveRetriever from llama_index.core import SummaryIndex summary_index = SummaryIndex(retriever_nodes) retriever = RecursiveRetriever( root_id="root", retriever_dict={"root": summary_index.as_retriever(), **retriever_dict}, ) nodes = await retriever.aretrieve( "Tell me about the main aspects of safety fine-tuning" ) print(f"Number of nodes: {len(nodes)}") for node in nodes: print(node.node.metadata["chunk_size"]) print(node.node.get_text()) from llama_index.core.postprocessor import LLMRerank, SentenceTransformerRerank from llama_index.postprocessor.cohere_rerank import CohereRerank reranker = CohereRerank(top_n=10) from llama_index.core.query_engine import RetrieverQueryEngine query_engine = RetrieverQueryEngine(retriever, node_postprocessors=[reranker]) response = query_engine.query( "Tell me about the main aspects of safety fine-tuning" ) display_response( response, show_source=True, source_length=500, show_source_metadata=True ) from collections import defaultdict import pandas as pd def mrr_all(metadata_values, metadata_key, source_nodes): value_to_mrr_dict = {} for metadata_value in metadata_values: mrr = 0 for idx, source_node in enumerate(source_nodes): if source_node.node.metadata[metadata_key] == metadata_value: mrr = 1 / (idx + 1) break else: continue value_to_mrr_dict[metadata_value] = mrr df = pd.DataFrame(value_to_mrr_dict, index=["MRR"]) df.style.set_caption("Mean Reciprocal Rank") return df print("Mean Reciprocal Rank for each Chunk Size") mrr_all(chunk_sizes, "chunk_size", response.source_nodes) from llama_index.core.evaluation import DatasetGenerator, QueryResponseDataset from llama_index.llms.openai import OpenAI import nest_asyncio nest_asyncio.apply() eval_llm = OpenAI(model="gpt-4") dataset_generator = DatasetGenerator( nodes_list[-1], llm=eval_llm, show_progress=True, num_questions_per_chunk=2, ) eval_dataset = await dataset_generator.agenerate_dataset_from_nodes(num=60) eval_dataset.save_json("data/llama2_eval_qr_dataset.json") eval_dataset = QueryResponseDataset.from_json( "data/llama2_eval_qr_dataset.json" ) import asyncio import nest_asyncio nest_asyncio.apply() from llama_index.core.evaluation import ( CorrectnessEvaluator, SemanticSimilarityEvaluator, RelevancyEvaluator, FaithfulnessEvaluator, PairwiseComparisonEvaluator, ) evaluator_c = CorrectnessEvaluator(llm=eval_llm) evaluator_s = SemanticSimilarityEvaluator(llm=eval_llm) evaluator_r = RelevancyEvaluator(llm=eval_llm) evaluator_f = FaithfulnessEvaluator(llm=eval_llm) pairwise_evaluator = PairwiseComparisonEvaluator(llm=eval_llm) from llama_index.core.evaluation.eval_utils import ( get_responses, get_results_df, ) from llama_index.core.evaluation import BatchEvalRunner max_samples = 60 eval_qs = eval_dataset.questions qr_pairs = eval_dataset.qr_pairs ref_response_strs = [r for (_, r) in qr_pairs] base_query_engine = vector_indices[-1].as_query_engine(similarity_top_k=2) reranker =
CohereRerank(top_n=4)
llama_index.postprocessor.cohere_rerank.CohereRerank
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import VectorStoreIndex, SQLDatabase from llama_index.readers.wikipedia import WikipediaReader from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) get_ipython().system('pip install wikipedia') cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from llama_index.core.query_engine import NLSQLTableQueryEngine sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], ) vector_indices = [] for wiki_doc in wiki_docs: vector_index = VectorStoreIndex.from_documents([wiki_doc]) vector_indices.append(vector_index) vector_query_engines = [index.as_query_engine() for index in vector_indices] from llama_index.core.tools import QueryEngineTool sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, description=( "Useful for translating a natural language query into a SQL query over" " a table containing: city_stats, containing the population/country of" " each city" ), ) vector_tools = [] for city, query_engine in zip(cities, vector_query_engines): vector_tool = QueryEngineTool.from_defaults( query_engine=query_engine, description=f"Useful for answering semantic questions about {city}", ) vector_tools.append(vector_tool) from llama_index.core.query_engine import RouterQueryEngine from llama_index.core.selectors import LLMSingleSelector query_engine = RouterQueryEngine( selector=
LLMSingleSelector.from_defaults()
llama_index.core.selectors.LLMSingleSelector.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().system('pip install llama-index') from llama_index.core import ( SimpleDirectoryReader, VectorStoreIndex, StorageContext, load_index_from_storage, ) from llama_index.core.tools import QueryEngineTool, ToolMetadata try: storage_context = StorageContext.from_defaults( persist_dir="./storage/lyft" ) lyft_index = load_index_from_storage(storage_context) storage_context = StorageContext.from_defaults( persist_dir="./storage/uber" ) uber_index = load_index_from_storage(storage_context) index_loaded = True except: index_loaded = False get_ipython().system("mkdir -p 'data/10k/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10k/uber_2021.pdf' -O 'data/10k/uber_2021.pdf'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10k/lyft_2021.pdf' -O 'data/10k/lyft_2021.pdf'") if not index_loaded: lyft_docs = SimpleDirectoryReader( input_files=["./data/10k/lyft_2021.pdf"] ).load_data() uber_docs = SimpleDirectoryReader( input_files=["./data/10k/uber_2021.pdf"] ).load_data() lyft_index = VectorStoreIndex.from_documents(lyft_docs) uber_index = VectorStoreIndex.from_documents(uber_docs) lyft_index.storage_context.persist(persist_dir="./storage/lyft") uber_index.storage_context.persist(persist_dir="./storage/uber") lyft_engine = lyft_index.as_query_engine(similarity_top_k=3) uber_engine = uber_index.as_query_engine(similarity_top_k=3) query_engine_tools = [ QueryEngineTool( query_engine=lyft_engine, metadata=ToolMetadata( name="lyft_10k", description=( "Provides information about Lyft financials for year 2021. " "Use a detailed plain text question as input to the tool." ), ), ), QueryEngineTool( query_engine=uber_engine, metadata=ToolMetadata( name="uber_10k", description=( "Provides information about Uber financials for year 2021. " "Use a detailed plain text question as input to the tool." ), ), ), ] from llama_index.agent.openai import OpenAIAgent agent =
OpenAIAgent.from_tools(query_engine_tools, verbose=True)
llama_index.agent.openai.OpenAIAgent.from_tools
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-redis') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import VectorStoreIndex, SimpleKeywordTableIndex from llama_index.core import SummaryIndex from llama_index.core import ComposableGraph from llama_index.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_response from llama_index.core import Settings get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") reader = SimpleDirectoryReader("./data/paul_graham/") documents = reader.load_data() from llama_index.core.node_parser import SentenceSplitter nodes = SentenceSplitter().get_nodes_from_documents(documents) REDIS_HOST = os.getenv("REDIS_HOST", "127.0.0.1") REDIS_PORT = os.getenv("REDIS_PORT", 6379) from llama_index.storage.docstore.redis import RedisDocumentStore from llama_index.storage.index_store.redis import RedisIndexStore storage_context = StorageContext.from_defaults( docstore=RedisDocumentStore.from_host_and_port( host=REDIS_HOST, port=REDIS_PORT, namespace="llama_index" ), index_store=RedisIndexStore.from_host_and_port( host=REDIS_HOST, port=REDIS_PORT, namespace="llama_index" ), ) storage_context.docstore.add_documents(nodes) len(storage_context.docstore.docs) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) keyword_table_index = SimpleKeywordTableIndex( nodes, storage_context=storage_context ) len(storage_context.docstore.docs) storage_context.persist(persist_dir="./storage") list_id = summary_index.index_id vector_id = vector_index.index_id keyword_id = keyword_table_index.index_id from llama_index.core import load_index_from_storage storage_context = StorageContext.from_defaults( docstore=RedisDocumentStore.from_host_and_port( host=REDIS_HOST, port=REDIS_PORT, namespace="llama_index" ), index_store=RedisIndexStore.from_host_and_port( host=REDIS_HOST, port=REDIS_PORT, namespace="llama_index" ), ) summary_index = load_index_from_storage( storage_context=storage_context, index_id=list_id ) vector_index = load_index_from_storage( storage_context=storage_context, index_id=vector_id ) keyword_table_index = load_index_from_storage( storage_context=storage_context, index_id=keyword_id ) chatgpt = OpenAI(temperature=0, model="gpt-3.5-turbo") Settings.llm = chatgpt Settings.chunk_size = 1024 query_engine = summary_index.as_query_engine() list_response = query_engine.query("What is a summary of this document?") display_response(list_response) query_engine = vector_index.as_query_engine() vector_response = query_engine.query("What did the author do growing up?") display_response(vector_response) query_engine = keyword_table_index.as_query_engine() keyword_response = query_engine.query( "What did the author do after his time at YC?" )
display_response(keyword_response)
llama_index.core.response.notebook_utils.display_response
get_ipython().run_line_magic('pip', 'install llama-index-readers-discord') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) get_ipython().system('pip install nest_asyncio') import nest_asyncio nest_asyncio.apply() from llama_index.core import SummaryIndex from llama_index.readers.discord import DiscordReader from IPython.display import Markdown, display import os discord_token = os.getenv("DISCORD_TOKEN") channel_ids = [1057178784895348746] # Replace with your channel_id documents = DiscordReader(discord_token=discord_token).load_data( channel_ids=channel_ids ) index =
SummaryIndex.from_documents(documents)
llama_index.core.SummaryIndex.from_documents
get_ipython().run_line_magic('pip', 'install -q llama-index-vector-stores-chroma llama-index-llms-fireworks llama-index-embeddings-fireworks==0.1.2') get_ipython().run_line_magic('pip', 'install -q llama-index') get_ipython().system('pip install llama-index chromadb --quiet') get_ipython().system('pip install -q chromadb') get_ipython().system('pip install -q pydantic==1.10.11') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.chroma import ChromaVectorStore from llama_index.core import StorageContext from llama_index.embeddings.fireworks import FireworksEmbedding from llama_index.llms.fireworks import Fireworks from IPython.display import Markdown, display import chromadb import getpass fw_api_key = getpass.getpass("Fireworks API Key:") get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.llms.fireworks import Fireworks from llama_index.embeddings.fireworks import FireworksEmbedding llm = Fireworks( temperature=0, model="accounts/fireworks/models/mixtral-8x7b-instruct" ) chroma_client = chromadb.EphemeralClient() chroma_collection = chroma_client.create_collection("quickstart") embed_model = FireworksEmbedding( model_name="nomic-ai/nomic-embed-text-v1.5", ) documents = SimpleDirectoryReader("./data/paul_graham/").load_data() vector_store =
ChromaVectorStore(chroma_collection=chroma_collection)
llama_index.vector_stores.chroma.ChromaVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import json from typing import Sequence, List from llama_index.llms.openai import OpenAI from llama_index.core.llms import ChatMessage from llama_index.core.tools import BaseTool, FunctionTool import nest_asyncio nest_asyncio.apply() def multiply(a: int, b: int) -> int: """Multiple two integers and returns the result integer""" return a * b multiply_tool =
FunctionTool.from_defaults(fn=multiply)
llama_index.core.tools.FunctionTool.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt' -O pg_essay.txt") from llama_index.core import SimpleDirectoryReader reader = SimpleDirectoryReader(input_files=["pg_essay.txt"]) documents = reader.load_data() from llama_index.core.query_pipeline import ( QueryPipeline, InputComponent, ArgPackComponent, ) from typing import Dict, Any, List, Optional from llama_index.core.llama_pack import BaseLlamaPack from llama_index.core.llms import LLM from llama_index.llms.openai import OpenAI from llama_index.core import Document, VectorStoreIndex from llama_index.core.response_synthesizers import TreeSummarize from llama_index.core.schema import NodeWithScore, TextNode from llama_index.core.node_parser import SentenceSplitter llm = OpenAI(model="gpt-3.5-turbo") chunk_sizes = [128, 256, 512, 1024] query_engines = {} for chunk_size in chunk_sizes: splitter = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=0) nodes = splitter.get_nodes_from_documents(documents) vector_index = VectorStoreIndex(nodes) query_engines[str(chunk_size)] = vector_index.as_query_engine(llm=llm) p = QueryPipeline(verbose=True) module_dict = { **query_engines, "input":
InputComponent()
llama_index.core.query_pipeline.InputComponent
import os import sys import logging from dotenv import load_dotenv logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger(__name__) load_dotenv() # take environment variables from .env. logger.debug(f"NewRelic application: {os.getenv('NEW_RELIC_APP_NAME')}") import os from time import time from nr_openai_observability import monitor from llama_index import VectorStoreIndex, download_loader if os.getenv("NEW_RELIC_APP_NAME") and os.getenv("NEW_RELIC_LICENSE_KEY"): monitor.initialization(application_name=os.getenv("NEW_RELIC_APP_NAME")) RayyanReader = download_loader("RayyanReader") loader = RayyanReader(credentials_path="rayyan-creds.json") documents = loader.load_data(review_id=746345) logger.info("Indexing articles...") t1 = time() review_index =
VectorStoreIndex.from_documents(documents)
llama_index.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-readers-faiss') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.readers.faiss import FaissReader import faiss id_to_text_map = { "id1": "text blob 1", "id2": "text blob 2", } index = ... reader =
FaissReader(index)
llama_index.readers.faiss.FaissReader
get_ipython().run_line_magic('pip', 'install llama-index-readers-make-com') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.readers.make_com import MakeWrapper get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-gradient') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-finetuning') get_ipython().system('pip install llama-index gradientai -q') import os from llama_index.llms.gradient import GradientBaseModelLLM from llama_index.finetuning import GradientFinetuneEngine os.environ["GRADIENT_ACCESS_TOKEN"] = os.getenv("GRADIENT_API_KEY") os.environ["GRADIENT_WORKSPACE_ID"] = "<insert_workspace_id>" from pydantic import BaseModel class Album(BaseModel): """Data model for an album.""" name: str artist: str from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler from llama_index.llms.openai import OpenAI from llama_index.llms.gradient import GradientBaseModelLLM from llama_index.core.program import LLMTextCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser openai_handler = LlamaDebugHandler() openai_callback = CallbackManager([openai_handler]) openai_llm = OpenAI(model="gpt-4", callback_manager=openai_callback) gradient_handler = LlamaDebugHandler() gradient_callback = CallbackManager([gradient_handler]) base_model_slug = "llama2-7b-chat" gradient_llm = GradientBaseModelLLM( base_model_slug=base_model_slug, max_tokens=300, callback_manager=gradient_callback, is_chat_model=True, ) from llama_index.core.llms import LLMMetadata prompt_template_str = """\ Generate an example album, with an artist and a list of songs. \ Using the movie {movie_name} as inspiration.\ """ openai_program = LLMTextCompletionProgram.from_defaults( output_parser=PydanticOutputParser(Album), prompt_template_str=prompt_template_str, llm=openai_llm, verbose=True, ) gradient_program = LLMTextCompletionProgram.from_defaults( output_parser=PydanticOutputParser(Album), prompt_template_str=prompt_template_str, llm=gradient_llm, verbose=True, ) response = openai_program(movie_name="The Shining") print(str(response)) tmp = openai_handler.get_llm_inputs_outputs() print(tmp[0][0].payload["messages"][0]) response = gradient_program(movie_name="The Shining") print(str(response)) tmp = gradient_handler.get_llm_inputs_outputs() print(tmp[0][0].payload["messages"][0]) from llama_index.core.program import LLMTextCompletionProgram from pydantic import BaseModel from llama_index.llms.openai import OpenAI from llama_index.core.callbacks import GradientAIFineTuningHandler from llama_index.core.callbacks import CallbackManager from llama_index.core.output_parsers import PydanticOutputParser from typing import List class Song(BaseModel): """Data model for a song.""" title: str length_seconds: int class Album(BaseModel): """Data model for an album.""" name: str artist: str songs: List[Song] finetuning_handler =
GradientAIFineTuningHandler()
llama_index.core.callbacks.GradientAIFineTuningHandler
get_ipython().run_line_magic('pip', 'install llama-index-evaluation-tonic-validate') import json import pandas as pd from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.evaluation.tonic_validate import ( AnswerConsistencyEvaluator, AnswerSimilarityEvaluator, AugmentationAccuracyEvaluator, AugmentationPrecisionEvaluator, RetrievalPrecisionEvaluator, TonicValidateEvaluator, ) question = "What makes Sam Altman a good founder?" reference_answer = "He is smart and has a great force of will." llm_answer = "He is a good founder because he is smart." retrieved_context_list = [ "Sam Altman is a good founder. He is very smart.", "What makes Sam Altman such a good founder is his great force of will.", ] answer_similarity_evaluator = AnswerSimilarityEvaluator() score = await answer_similarity_evaluator.aevaluate( question, llm_answer, retrieved_context_list, reference_response=reference_answer, ) score answer_consistency_evaluator = AnswerConsistencyEvaluator() score = await answer_consistency_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score augmentation_accuracy_evaluator = AugmentationAccuracyEvaluator() score = await augmentation_accuracy_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score augmentation_precision_evaluator = AugmentationPrecisionEvaluator() score = await augmentation_precision_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score retrieval_precision_evaluator = RetrievalPrecisionEvaluator() score = await retrieval_precision_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score tonic_validate_evaluator = TonicValidateEvaluator() scores = await tonic_validate_evaluator.aevaluate( question, llm_answer, retrieved_context_list, reference_response=reference_answer, ) scores.score_dict tonic_validate_evaluator = TonicValidateEvaluator() scores = await tonic_validate_evaluator.aevaluate_run( [question], [llm_answer], [retrieved_context_list], [reference_answer] ) scores.run_data[0].scores get_ipython().system('llamaindex-cli download-llamadataset EvaluatingLlmSurveyPaperDataset --download-dir ./data') from llama_index.core import SimpleDirectoryReader from llama_index.core.llama_dataset import LabelledRagDataset from llama_index.core import VectorStoreIndex rag_dataset =
LabelledRagDataset.from_json("./data/rag_dataset.json")
llama_index.core.llama_dataset.LabelledRagDataset.from_json
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-replicate') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('', 'autoreload 2') get_ipython().system('pip install unstructured') from unstructured.partition.html import partition_html import pandas as pd pd.set_option("display.max_rows", None) pd.set_option("display.max_columns", None) pd.set_option("display.width", None) pd.set_option("display.max_colwidth", None) get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1THe1qqM61lretr9N3BmINc_NWDvuthYf" -O shanghai.jpg') get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1PDVCf_CzLWXNnNoRV8CFgoJxv6U0sHAO" -O tesla_supercharger.jpg') from llama_index.readers.file import FlatReader from pathlib import Path reader = FlatReader() docs_2021 = reader.load_data(Path("tesla_2021_10k.htm")) from llama_index.core.node_parser import UnstructuredElementNodeParser node_parser = UnstructuredElementNodeParser() import os REPLICATE_API_TOKEN = "..." # Your Relicate API token here os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN import openai OPENAI_API_TOKEN = "sk-..." openai.api_key = OPENAI_API_TOKEN # add your openai api key here os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN import os import pickle if not os.path.exists("2021_nodes.pkl"): raw_nodes_2021 = node_parser.get_nodes_from_documents(docs_2021) pickle.dump(raw_nodes_2021, open("2021_nodes.pkl", "wb")) else: raw_nodes_2021 = pickle.load(open("2021_nodes.pkl", "rb")) nodes_2021, objects_2021 = node_parser.get_nodes_and_objects(raw_nodes_2021) from llama_index.core import VectorStoreIndex vector_index = VectorStoreIndex(nodes=nodes_2021, objects=objects_2021) query_engine = vector_index.as_query_engine(similarity_top_k=2, verbose=True) from PIL import Image import matplotlib.pyplot as plt imageUrl = "./tesla_supercharger.jpg" image = Image.open(imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index.core.schema import ImageDocument from llama_index.multi_modal_llms.replicate.base import ( REPLICATE_MULTI_MODAL_LLM_MODELS, ) multi_modal_llm = ReplicateMultiModal( model=REPLICATE_MULTI_MODAL_LLM_MODELS["llava-13b"], max_new_tokens=200, temperature=0.1, ) prompt = "what is the main object for tesla in the image?" llava_response = multi_modal_llm.complete( prompt=prompt, image_documents=[
ImageDocument(image_path=imageUrl)
llama_index.core.schema.ImageDocument
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-replicate') get_ipython().run_line_magic('pip', 'install unstructured replicate') get_ipython().run_line_magic('pip', 'install llama_index ftfy regex tqdm') get_ipython().run_line_magic('pip', 'install git+https://github.com/openai/CLIP.git') get_ipython().run_line_magic('pip', 'install torch torchvision') get_ipython().run_line_magic('pip', 'install matplotlib scikit-image') get_ipython().run_line_magic('pip', 'install -U qdrant_client') import os REPLICATE_API_TOKEN = "..." # Your Relicate API token here os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1UU0xc3uLXs-WG0aDQSXjGacUkp142rLS" -O texas.jpg') from llama_index.readers.file import FlatReader from pathlib import Path from llama_index.core.node_parser import UnstructuredElementNodeParser reader = FlatReader() docs_2021 = reader.load_data(Path("tesla_2021_10k.htm")) node_parser = UnstructuredElementNodeParser() import openai OPENAI_API_TOKEN = "..." openai.api_key = OPENAI_API_TOKEN # add your openai api key here os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN import os import pickle if not os.path.exists("2021_nodes.pkl"): raw_nodes_2021 = node_parser.get_nodes_from_documents(docs_2021) pickle.dump(raw_nodes_2021, open("2021_nodes.pkl", "wb")) else: raw_nodes_2021 = pickle.load(open("2021_nodes.pkl", "rb")) nodes_2021, objects_2021 = node_parser.get_nodes_and_objects(raw_nodes_2021) from llama_index.core import VectorStoreIndex vector_index = VectorStoreIndex(nodes=nodes_2021, objects=objects_2021) query_engine = vector_index.as_query_engine(similarity_top_k=5, verbose=True) from PIL import Image import matplotlib.pyplot as plt imageUrl = "./texas.jpg" image = Image.open(imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index.core.schema import ImageDocument from llama_index.multi_modal_llms.replicate.base import ( REPLICATE_MULTI_MODAL_LLM_MODELS, ) print(imageUrl) llava_multi_modal_llm = ReplicateMultiModal( model=REPLICATE_MULTI_MODAL_LLM_MODELS["llava-13b"], max_new_tokens=200, temperature=0.1, ) prompt = "which Tesla factory is shown in the image? Please answer just the name of the factory." llava_response = llava_multi_modal_llm.complete( prompt=prompt, image_documents=[
ImageDocument(image_path=imageUrl)
llama_index.core.schema.ImageDocument
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') import nest_asyncio nest_asyncio.apply() import cProfile, pstats from pstats import SortKey get_ipython().system('llamaindex-cli download-llamadataset PatronusAIFinanceBenchDataset --download-dir ./data') from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader(input_dir="./data/source_files").load_data() from llama_index.core import Document from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.core.extractors import TitleExtractor from llama_index.core.ingestion import IngestionPipeline pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_size=1024, chunk_overlap=20),
TitleExtractor()
llama_index.core.extractors.TitleExtractor
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai pandas[jinja2] spacy') import nest_asyncio nest_asyncio.apply() import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, Response, ) from llama_index.llms.openai import OpenAI from llama_index.core.evaluation import FaithfulnessEvaluator from llama_index.core.node_parser import SentenceSplitter import pandas as pd pd.set_option("display.max_colwidth", 0) gpt4 = OpenAI(temperature=0, model="gpt-4") evaluator_gpt4 =
FaithfulnessEvaluator(llm=gpt4)
llama_index.core.evaluation.FaithfulnessEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-llms-anthropic') get_ipython().system('pip install llama-index') from llama_index.llms.anthropic import Anthropic from llama_index.core import Settings tokenizer = Anthropic().tokenizer Settings.tokenizer = tokenizer import os os.environ["ANTHROPIC_API_KEY"] = "YOUR ANTHROPIC API KEY" from llama_index.llms.anthropic import Anthropic llm = Anthropic(model="claude-3-opus-20240229") resp = llm.complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.anthropic import Anthropic messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="Tell me a story"), ] resp = Anthropic(model="claude-3-opus-20240229").chat(messages) print(resp) from llama_index.llms.anthropic import Anthropic llm = Anthropic(model="claude-3-opus-20240229", max_tokens=100) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.anthropic import Anthropic llm =
Anthropic(model="claude-3-opus-20240229")
llama_index.llms.anthropic.Anthropic
import sys from llama_index import download_loader BoardDocsReader = download_loader( "BoardDocsReader", loader_hub_url=( "https://raw.githubusercontent.com/dweekly/llama-hub/boarddocs/llama_hub" ), refresh_cache=True, ) loader = BoardDocsReader(site="ca/redwood", committee_id="A4EP6J588C05") from llama_index import GPTSimpleVectorIndex documents = loader.load_data(meeting_ids=["CPSNV9612DF1"]) index =
GPTSimpleVectorIndex.from_documents(documents)
llama_index.GPTSimpleVectorIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-finetuning-cross-encoders') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') get_ipython().system('pip install datasets --quiet') get_ipython().system('pip install sentence-transformers --quiet') get_ipython().system('pip install openai --quiet') from datasets import load_dataset import random dataset = load_dataset("allenai/qasper") train_dataset = dataset["train"] validation_dataset = dataset["validation"] test_dataset = dataset["test"] random.seed(42) # Set a random seed for reproducibility train_sampled_indices = random.sample(range(len(train_dataset)), 800) train_samples = [train_dataset[i] for i in train_sampled_indices] test_sampled_indices = random.sample(range(len(test_dataset)), 80) test_samples = [test_dataset[i] for i in test_sampled_indices] from typing import List def get_full_text(sample: dict) -> str: """ :param dict sample: the row sample from QASPER """ title = sample["title"] abstract = sample["abstract"] sections_list = sample["full_text"]["section_name"] paragraph_list = sample["full_text"]["paragraphs"] combined_sections_with_paras = "" if len(sections_list) == len(paragraph_list): combined_sections_with_paras += title + "\t" combined_sections_with_paras += abstract + "\t" for index in range(0, len(sections_list)): combined_sections_with_paras += str(sections_list[index]) + "\t" combined_sections_with_paras += "".join(paragraph_list[index]) return combined_sections_with_paras else: print("Not the same number of sections as paragraphs list") def get_questions(sample: dict) -> List[str]: """ :param dict sample: the row sample from QASPER """ questions_list = sample["qas"]["question"] return questions_list doc_qa_dict_list = [] for train_sample in train_samples: full_text = get_full_text(train_sample) questions_list = get_questions(train_sample) local_dict = {"paper": full_text, "questions": questions_list} doc_qa_dict_list.append(local_dict) len(doc_qa_dict_list) import pandas as pd df_train = pd.DataFrame(doc_qa_dict_list) df_train.to_csv("train.csv") """ The Answers field in the dataset follow the below format:- Unanswerable answers have "unanswerable" set to true. The remaining answers have exactly one of the following fields being non-empty. "extractive_spans" are spans in the paper which serve as the answer. "free_form_answer" is a written out answer. "yes_no" is true iff the answer is Yes, and false iff the answer is No. We accept only free-form answers and for all the other kind of answers we set their value to 'Unacceptable', to better evaluate the performance of the query engine using pairwise comparision evaluator as it uses GPT-4 which is biased towards preferring long answers more. https://www.anyscale.com/blog/a-comprehensive-guide-for-building-rag-based-llm-applications-part-1 So in the case of 'yes_no' answers it can favour Query Engine answers more than reference answers. Also in the case of extracted spans it can favour reference answers more than Query engine generated answers. """ eval_doc_qa_answer_list = [] def get_answers(sample: dict) -> List[str]: """ :param dict sample: the row sample from the train split of QASPER """ final_answers_list = [] answers = sample["qas"]["answers"] for answer in answers: local_answer = "" types_of_answers = answer["answer"][0] if types_of_answers["unanswerable"] == False: if types_of_answers["free_form_answer"] != "": local_answer = types_of_answers["free_form_answer"] else: local_answer = "Unacceptable" else: local_answer = "Unacceptable" final_answers_list.append(local_answer) return final_answers_list for test_sample in test_samples: full_text = get_full_text(test_sample) questions_list = get_questions(test_sample) answers_list = get_answers(test_sample) local_dict = { "paper": full_text, "questions": questions_list, "answers": answers_list, } eval_doc_qa_answer_list.append(local_dict) len(eval_doc_qa_answer_list) import pandas as pd df_test = pd.DataFrame(eval_doc_qa_answer_list) df_test.to_csv("test.csv") get_ipython().system('pip install llama-index --quiet') import os from llama_index.core import SimpleDirectoryReader import openai from llama_index.finetuning.cross_encoders.dataset_gen import ( generate_ce_fine_tuning_dataset, generate_synthetic_queries_over_documents, ) from llama_index.finetuning.cross_encoders import CrossEncoderFinetuneEngine os.environ["OPENAI_API_KEY"] = "sk-" openai.api_key = os.environ["OPENAI_API_KEY"] from llama_index.core import Document final_finetuning_data_list = [] for paper in doc_qa_dict_list: questions_list = paper["questions"] documents = [Document(text=paper["paper"])] local_finetuning_dataset = generate_ce_fine_tuning_dataset( documents=documents, questions_list=questions_list, max_chunk_length=256, top_k=5, ) final_finetuning_data_list.extend(local_finetuning_dataset) len(final_finetuning_data_list) import pandas as pd df_finetuning_dataset = pd.DataFrame(final_finetuning_data_list) df_finetuning_dataset.to_csv("fine_tuning.csv") finetuning_dataset = final_finetuning_data_list finetuning_dataset[0] get_ipython().system('wget -O test.csv https://www.dropbox.com/scl/fi/3lmzn6714oy358mq0vawm/test.csv?rlkey=yz16080te4van7fvnksi9kaed&dl=0') import pandas as pd import ast # Used to safely evaluate the string as a list df_test = pd.read_csv("/content/test.csv", index_col=0) df_test["questions"] = df_test["questions"].apply(ast.literal_eval) df_test["answers"] = df_test["answers"].apply(ast.literal_eval) print(f"Number of papers in the test sample:- {len(df_test)}") from llama_index.core import Document final_eval_data_list = [] for index, row in df_test.iterrows(): documents = [Document(text=row["paper"])] query_list = row["questions"] local_eval_dataset = generate_ce_fine_tuning_dataset( documents=documents, questions_list=query_list, max_chunk_length=256, top_k=5, ) relevant_query_list = [] relevant_context_list = [] for item in local_eval_dataset: if item.score == 1: relevant_query_list.append(item.query) relevant_context_list.append(item.context) if len(relevant_query_list) > 0: final_eval_data_list.append( { "paper": row["paper"], "questions": relevant_query_list, "context": relevant_context_list, } ) len(final_eval_data_list) import pandas as pd df_finetuning_dataset = pd.DataFrame(final_eval_data_list) df_finetuning_dataset.to_csv("reranking_test.csv") get_ipython().system('pip install huggingface_hub --quiet') from huggingface_hub import notebook_login notebook_login() from sentence_transformers import SentenceTransformer finetuning_engine = CrossEncoderFinetuneEngine( dataset=finetuning_dataset, epochs=2, batch_size=8 ) finetuning_engine.finetune() finetuning_engine.push_to_hub( repo_id="bpHigh/Cross-Encoder-LLamaIndex-Demo-v2" ) get_ipython().system('pip install nest-asyncio --quiet') import nest_asyncio nest_asyncio.apply() get_ipython().system('wget -O reranking_test.csv https://www.dropbox.com/scl/fi/mruo5rm46k1acm1xnecev/reranking_test.csv?rlkey=hkniwowq0xrc3m0ywjhb2gf26&dl=0') import pandas as pd import ast df_reranking = pd.read_csv("/content/reranking_test.csv", index_col=0) df_reranking["questions"] = df_reranking["questions"].apply(ast.literal_eval) df_reranking["context"] = df_reranking["context"].apply(ast.literal_eval) print(f"Number of papers in the reranking eval dataset:- {len(df_reranking)}") df_reranking.head(1) from llama_index.core.postprocessor import SentenceTransformerRerank from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Response from llama_index.core.retrievers import VectorIndexRetriever from llama_index.llms.openai import OpenAI from llama_index.core import Document from llama_index.core import Settings import os import openai import pandas as pd os.environ["OPENAI_API_KEY"] = "sk-" openai.api_key = os.environ["OPENAI_API_KEY"] Settings.chunk_size = 256 rerank_base = SentenceTransformerRerank( model="cross-encoder/ms-marco-MiniLM-L-12-v2", top_n=3 ) rerank_finetuned = SentenceTransformerRerank( model="bpHigh/Cross-Encoder-LLamaIndex-Demo-v2", top_n=3 ) without_reranker_hits = 0 base_reranker_hits = 0 finetuned_reranker_hits = 0 total_number_of_context = 0 for index, row in df_reranking.iterrows(): documents = [Document(text=row["paper"])] query_list = row["questions"] context_list = row["context"] assert len(query_list) == len(context_list) vector_index = VectorStoreIndex.from_documents(documents) retriever_without_reranker = vector_index.as_query_engine( similarity_top_k=3, response_mode="no_text" ) retriever_with_base_reranker = vector_index.as_query_engine( similarity_top_k=8, response_mode="no_text", node_postprocessors=[rerank_base], ) retriever_with_finetuned_reranker = vector_index.as_query_engine( similarity_top_k=8, response_mode="no_text", node_postprocessors=[rerank_finetuned], ) for index in range(0, len(query_list)): query = query_list[index] context = context_list[index] total_number_of_context += 1 response_without_reranker = retriever_without_reranker.query(query) without_reranker_nodes = response_without_reranker.source_nodes for node in without_reranker_nodes: if context in node.node.text or node.node.text in context: without_reranker_hits += 1 response_with_base_reranker = retriever_with_base_reranker.query(query) with_base_reranker_nodes = response_with_base_reranker.source_nodes for node in with_base_reranker_nodes: if context in node.node.text or node.node.text in context: base_reranker_hits += 1 response_with_finetuned_reranker = ( retriever_with_finetuned_reranker.query(query) ) with_finetuned_reranker_nodes = ( response_with_finetuned_reranker.source_nodes ) for node in with_finetuned_reranker_nodes: if context in node.node.text or node.node.text in context: finetuned_reranker_hits += 1 assert ( len(with_finetuned_reranker_nodes) == len(with_base_reranker_nodes) == len(without_reranker_nodes) == 3 ) without_reranker_scores = [without_reranker_hits] base_reranker_scores = [base_reranker_hits] finetuned_reranker_scores = [finetuned_reranker_hits] reranker_eval_dict = { "Metric": "Hits", "OpenAI_Embeddings": without_reranker_scores, "Base_cross_encoder": base_reranker_scores, "Finetuned_cross_encoder": finetuned_reranker_hits, "Total Relevant Context": total_number_of_context, } df_reranker_eval_results = pd.DataFrame(reranker_eval_dict) display(df_reranker_eval_results) get_ipython().system('wget -O test.csv https://www.dropbox.com/scl/fi/3lmzn6714oy358mq0vawm/test.csv?rlkey=yz16080te4van7fvnksi9kaed&dl=0') import pandas as pd import ast # Used to safely evaluate the string as a list df_test = pd.read_csv("/content/test.csv", index_col=0) df_test["questions"] = df_test["questions"].apply(ast.literal_eval) df_test["answers"] = df_test["answers"].apply(ast.literal_eval) print(f"Number of papers in the test sample:- {len(df_test)}") df_test.head(1) from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Response from llama_index.llms.openai import OpenAI from llama_index.core import Document from llama_index.core.evaluation import PairwiseComparisonEvaluator from llama_index.core.evaluation.eval_utils import ( get_responses, get_results_df, ) import os import openai import pandas as pd os.environ["OPENAI_API_KEY"] = "sk-" openai.api_key = os.environ["OPENAI_API_KEY"] gpt4 = OpenAI(temperature=0, model="gpt-4") evaluator_gpt4_pairwise =
PairwiseComparisonEvaluator(llm=gpt4)
llama_index.core.evaluation.PairwiseComparisonEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-zilliz') from getpass import getpass import os os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API Key:") ZILLIZ_PROJECT_ID = getpass("Enter your Zilliz Project ID:") ZILLIZ_CLUSTER_ID = getpass("Enter your Zilliz Cluster ID:") ZILLIZ_TOKEN = getpass("Enter your Zilliz API Key:") from llama_index.indices.managed.zilliz import ZillizCloudPipelineIndex zcp_index = ZillizCloudPipelineIndex.from_document_url( url="https://publicdataset.zillizcloud.com/milvus_doc.md", project_id=ZILLIZ_PROJECT_ID, cluster_id=ZILLIZ_CLUSTER_ID, token=ZILLIZ_TOKEN, metadata={"version": "2.3"}, # used for filtering collection_name="zcp_llamalection", # change this value will specify customized collection name ) zcp_index.insert_doc_url( url="https://publicdataset.zillizcloud.com/milvus_doc_22.md", metadata={"version": "2.2"}, ) from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters query_engine_milvus23 = zcp_index.as_query_engine( search_top_k=3, filters=MetadataFilters( filters=[
ExactMatchFilter(key="version", value="2.3")
llama_index.core.vector_stores.ExactMatchFilter
get_ipython().system('pip install llama-index') import os import openai os.environ["OPENAI_API_KEY"] = "sk-..." openai.api_key = os.environ["OPENAI_API_KEY"] import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, load_index_from_storage, StorageContext, ) from IPython.display import Markdown, display get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine(response_mode="tree_summarize") def display_prompt_dict(prompts_dict): for k, p in prompts_dict.items(): text_md = f"**Prompt Key**: {k}<br>" f"**Text:** <br>" display(Markdown(text_md)) print(p.get_template()) display(Markdown("<br><br>")) prompts_dict = query_engine.get_prompts() display_prompt_dict(prompts_dict) prompts_dict = query_engine.response_synthesizer.get_prompts() display_prompt_dict(prompts_dict) query_engine = index.as_query_engine(response_mode="compact") prompts_dict = query_engine.get_prompts() display_prompt_dict(prompts_dict) response = query_engine.query("What did the author do growing up?") print(str(response)) from llama_index.core import PromptTemplate query_engine = index.as_query_engine(response_mode="tree_summarize") new_summary_tmpl_str = ( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information and not prior knowledge, " "answer the query in the style of a Shakespeare play.\n" "Query: {query_str}\n" "Answer: " ) new_summary_tmpl = PromptTemplate(new_summary_tmpl_str) query_engine.update_prompts( {"response_synthesizer:summary_template": new_summary_tmpl} ) prompts_dict = query_engine.get_prompts() display_prompt_dict(prompts_dict) response = query_engine.query("What did the author do growing up?") print(str(response)) from llama_index.core.query_engine import ( RouterQueryEngine, FLAREInstructQueryEngine, ) from llama_index.core.selectors import LLMMultiSelector from llama_index.core.evaluation import FaithfulnessEvaluator, DatasetGenerator from llama_index.core.postprocessor import LLMRerank from llama_index.core.tools import QueryEngineTool query_tool = QueryEngineTool.from_defaults( query_engine=query_engine, description="test description" ) router_query_engine = RouterQueryEngine.from_defaults([query_tool]) prompts_dict = router_query_engine.get_prompts() display_prompt_dict(prompts_dict) flare_query_engine =
FLAREInstructQueryEngine(query_engine)
llama_index.core.query_engine.FLAREInstructQueryEngine
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import os import pinecone api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="eu-west1-gcp") indexes = pinecone.list_indexes() print(indexes) if "quickstart-index" not in indexes: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll="true") books = [ { "title": "To Kill a Mockingbird", "author": "Harper Lee", "content": ( "To Kill a Mockingbird is a novel by Harper Lee published in" " 1960..." ), "year": 1960, }, { "title": "1984", "author": "George Orwell", "content": ( "1984 is a dystopian novel by George Orwell published in 1949..." ), "year": 1949, }, { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "content": ( "The Great Gatsby is a novel by F. Scott Fitzgerald published in" " 1925..." ), "year": 1925, }, { "title": "Pride and Prejudice", "author": "Jane Austen", "content": ( "Pride and Prejudice is a novel by Jane Austen published in" " 1813..." ), "year": 1813, }, ] import uuid from llama_index.embeddings.openai import OpenAIEmbedding embed_model =
OpenAIEmbedding()
llama_index.embeddings.openai.OpenAIEmbedding
get_ipython().system('pip install llama-index-multi-modal-llms-anthropic') get_ipython().system('pip install llama-index-vector-stores-qdrant') get_ipython().system('pip install matplotlib') import os os.environ["ANTHROPIC_API_KEY"] = "" # Your ANTHROPIC API key here from PIL import Image import matplotlib.pyplot as plt img = Image.open("../data/images/prometheus_paper_card.png") plt.imshow(img) from llama_index.core import SimpleDirectoryReader from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal image_documents = SimpleDirectoryReader( input_files=["../data/images/prometheus_paper_card.png"] ).load_data() anthropic_mm_llm =
AnthropicMultiModal(max_tokens=300)
llama_index.multi_modal_llms.anthropic.AnthropicMultiModal
from llama_index import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader( "../../examples/data/paul_graham" ).load_data() index = VectorStoreIndex.from_documents(documents) import pinecone from llama_index import VectorStoreIndex, SimpleDirectoryReader, StorageContext from llama_index.vector_stores import PineconeVectorStore pinecone.init(api_key="<api_key>", environment="<environment>") pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) storage_context = StorageContext.from_defaults( vector_store=PineconeVectorStore(pinecone.Index("quickstart")) ) documents = SimpleDirectoryReader( "../../examples/data/paul_graham" ).load_data() index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) vector_store = PineconeVectorStore(pinecone.Index("quickstart")) index =
VectorStoreIndex.from_vector_store(vector_store=vector_store)
llama_index.VectorStoreIndex.from_vector_store
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-supabase') get_ipython().system('pip install llama-index') import logging import sys from llama_index.core import SimpleDirectoryReader, Document, StorageContext from llama_index.core import VectorStoreIndex from llama_index.vector_stores.supabase import SupabaseVectorStore import textwrap import os os.environ["OPENAI_API_KEY"] = "[your_openai_api_key]" get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() print( "Document ID:", documents[0].doc_id, "Document Hash:", documents[0].doc_hash, ) vector_store = SupabaseVectorStore( postgres_connection_string=( "postgresql://<user>:<password>@<host>:<port>/<db_name>" ), collection_name="base_demo", ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) query_engine = index.as_query_engine() response = query_engine.query("Who is the author?") print(textwrap.fill(str(response), 100)) response = query_engine.query("What did the author do growing up?") print(textwrap.fill(str(response), 100)) from llama_index.core.schema import TextNode nodes = [ TextNode( **{ "text": "The Shawshank Redemption", "metadata": { "author": "Stephen King", "theme": "Friendship", }, } ), TextNode( **{ "text": "The Godfather", "metadata": { "director": "Francis Ford Coppola", "theme": "Mafia", }, } ), TextNode( **{ "text": "Inception", "metadata": { "director": "Christopher Nolan", }, } ), ] vector_store = SupabaseVectorStore( postgres_connection_string=( "postgresql://<user>:<password>@<host>:<port>/<db_name>" ), collection_name="metadata_filters_demo", ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters filters = MetadataFilters( filters=[
ExactMatchFilter(key="theme", value="Mafia")
llama_index.core.vector_stores.ExactMatchFilter
import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import VectorStoreIndex, SimpleDirectoryReader get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() index =
VectorStoreIndex.from_documents(documents)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-google') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-google') get_ipython().run_line_magic('pip', 'install llama-index-response-synthesizers-google') get_ipython().run_line_magic('pip', 'install llama-index') get_ipython().run_line_magic('pip', 'install "google-ai-generativelanguage>=0.4,<=1.0"') get_ipython().run_line_magic('pip', 'install google-auth-oauthlib') from google.oauth2 import service_account from llama_index.vector_stores.google import set_google_config credentials = service_account.Credentials.from_service_account_file( "service_account_key.json", scopes=[ "https://www.googleapis.com/auth/generative-language.retriever", ], ) set_google_config(auth_credentials=credentials) get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") import llama_index.core.vector_stores.google.generativeai.genai_extension as genaix from typing import Iterable from random import randrange LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX = f"llama-index-colab" SESSION_CORPUS_ID_PREFIX = ( f"{LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX}-{randrange(1000000)}" ) def corpus_id(num_id: int) -> str: return f"{SESSION_CORPUS_ID_PREFIX}-{num_id}" SESSION_CORPUS_ID = corpus_id(1) def list_corpora() -> Iterable[genaix.Corpus]: client = genaix.build_semantic_retriever() yield from genaix.list_corpora(client=client) def delete_corpus(*, corpus_id: str) -> None: client = genaix.build_semantic_retriever() genaix.delete_corpus(corpus_id=corpus_id, client=client) def cleanup_colab_corpora(): for corpus in list_corpora(): if corpus.corpus_id.startswith(LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX): try: delete_corpus(corpus_id=corpus.corpus_id) print(f"Deleted corpus {corpus.corpus_id}.") except Exception: pass cleanup_colab_corpora() from llama_index.core import SimpleDirectoryReader from llama_index.indices.managed.google import GoogleIndex from llama_index.core import Response import time index = GoogleIndex.create_corpus( corpus_id=SESSION_CORPUS_ID, display_name="My first corpus!" ) print(f"Newly created corpus ID is {index.corpus_id}.") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() index.insert_documents(documents) for corpus in list_corpora(): print(corpus) query_engine = index.as_query_engine() response = query_engine.query("What did Paul Graham do growing up?") assert isinstance(response, Response) print(f"Response is {response.response}") for cited_text in [node.text for node in response.source_nodes]: print(f"Cited text: {cited_text}") if response.metadata: print( f"Answerability: {response.metadata.get('answerable_probability', 0)}" ) index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) query_engine = index.as_query_engine() response = query_engine.query("Which company did Paul Graham build?") assert isinstance(response, Response) print(f"Response is {response.response}") from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) index.insert_nodes( [ TextNode( text="It was the best of times.", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="123", metadata={"file_name": "Tale of Two Cities"}, ) }, ), TextNode( text="It was the worst of times.", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="123", metadata={"file_name": "Tale of Two Cities"}, ) }, ), TextNode( text="Bugs Bunny: Wassup doc?", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="456", metadata={"file_name": "Bugs Bunny Adventure"}, ) }, ), ] ) from google.ai.generativelanguage import ( GenerateAnswerRequest, HarmCategory, SafetySetting, ) index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) query_engine = index.as_query_engine( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, safety_setting=[ SafetySetting( category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold=SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), SafetySetting( category=HarmCategory.HARM_CATEGORY_VIOLENCE, threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH, ), ], ) response = query_engine.query("What was Bugs Bunny's favorite saying?") print(response) from llama_index.core import Response response = query_engine.query("What were Paul Graham's achievements?") assert isinstance(response, Response) print(f"Response is {response.response}") for cited_text in [node.text for node in response.source_nodes]: print(f"Cited text: {cited_text}") if response.metadata: print( f"Answerability: {response.metadata.get('answerable_probability', 0)}" ) from llama_index.llms.gemini import Gemini GEMINI_API_KEY = "" # @param {type:"string"} gemini = Gemini(api_key=GEMINI_API_KEY) from llama_index.response_synthesizers.google import GoogleTextSynthesizer from llama_index.vector_stores.google import GoogleVectorStore from llama_index.core import VectorStoreIndex from llama_index.core.postprocessor import LLMRerank from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.retrievers import VectorIndexRetriever store = GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID) index = VectorStoreIndex.from_vector_store( vector_store=store, ) response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, ) reranker = LLMRerank( top_n=10, llm=gemini, ) query_engine = RetrieverQueryEngine.from_args( retriever=VectorIndexRetriever( index=index, similarity_top_k=20, ), node_postprocessors=[reranker], response_synthesizer=response_synthesizer, ) response = query_engine.query("What were Paul Graham's achievements?") print(response) from llama_index.core.indices.query.query_transform.base import ( StepDecomposeQueryTransform, ) from llama_index.core.query_engine import MultiStepQueryEngine store =
GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID)
llama_index.vector_stores.google.GoogleVectorStore.from_corpus
get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-vectara') get_ipython().system('pip install llama-index') from llama_index.indices.managed.vectara import VectaraIndex from llama_index.core import SimpleDirectoryReader import os documents = SimpleDirectoryReader(os.path.abspath("../data/10q/")).load_data() print(f"documents loaded into {len(documents)} document objects") print(f"Document ID of first doc is {documents[0].doc_id}") index =
VectaraIndex.from_documents(documents)
llama_index.indices.managed.vectara.VectaraIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-evaluation-tonic-validate') import json import pandas as pd from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.evaluation.tonic_validate import ( AnswerConsistencyEvaluator, AnswerSimilarityEvaluator, AugmentationAccuracyEvaluator, AugmentationPrecisionEvaluator, RetrievalPrecisionEvaluator, TonicValidateEvaluator, ) question = "What makes Sam Altman a good founder?" reference_answer = "He is smart and has a great force of will." llm_answer = "He is a good founder because he is smart." retrieved_context_list = [ "Sam Altman is a good founder. He is very smart.", "What makes Sam Altman such a good founder is his great force of will.", ] answer_similarity_evaluator = AnswerSimilarityEvaluator() score = await answer_similarity_evaluator.aevaluate( question, llm_answer, retrieved_context_list, reference_response=reference_answer, ) score answer_consistency_evaluator = AnswerConsistencyEvaluator() score = await answer_consistency_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score augmentation_accuracy_evaluator = AugmentationAccuracyEvaluator() score = await augmentation_accuracy_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score augmentation_precision_evaluator =
AugmentationPrecisionEvaluator()
llama_index.evaluation.tonic_validate.AugmentationPrecisionEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-google') get_ipython().system('pip install llama-index') from llama_index.embeddings.google import GooglePaLMEmbedding model_name = "models/embedding-gecko-001" api_key = "YOUR API KEY" embed_model =
GooglePaLMEmbedding(model_name=model_name, api_key=api_key)
llama_index.embeddings.google.GooglePaLMEmbedding
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west4-gcp-free") import os import getpass import openai openai.api_key = "sk-<your-key>" try: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", "gender": "male", "born": 1963, }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", "gender": "female", "born": 1975, }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", "gender": "male", "born": 1971, }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", "gender": "female", "born": 1988, }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", "gender": "male", "born": 1985, }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index =
VectorStoreIndex(nodes, storage_context=storage_context)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-finetuning') get_ipython().run_line_magic('pip', 'install llama-index-finetuning-callbacks') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.core import ( SimpleDirectoryReader, VectorStoreIndex, StorageContext, load_index_from_storage, ) from llama_index.llms.openai import OpenAI from llama_index.core.tools import QueryEngineTool, ToolMetadata llm_35 = OpenAI(model="gpt-3.5-turbo-0613", temperature=0.3) llm_4 = OpenAI(model="gpt-4-0613", temperature=0.3) try: storage_context = StorageContext.from_defaults( persist_dir="./storage/march" ) march_index = load_index_from_storage(storage_context) storage_context = StorageContext.from_defaults( persist_dir="./storage/june" ) june_index = load_index_from_storage(storage_context) storage_context = StorageContext.from_defaults( persist_dir="./storage/sept" ) sept_index = load_index_from_storage(storage_context) index_loaded = True except: index_loaded = False if not index_loaded: march_docs = SimpleDirectoryReader( input_files=["../../data/10q/uber_10q_march_2022.pdf"] ).load_data() june_docs = SimpleDirectoryReader( input_files=["../../data/10q/uber_10q_june_2022.pdf"] ).load_data() sept_docs = SimpleDirectoryReader( input_files=["../../data/10q/uber_10q_sept_2022.pdf"] ).load_data() march_index = VectorStoreIndex.from_documents( march_docs, ) june_index = VectorStoreIndex.from_documents( june_docs, ) sept_index = VectorStoreIndex.from_documents( sept_docs, ) march_index.storage_context.persist(persist_dir="./storage/march") june_index.storage_context.persist(persist_dir="./storage/june") sept_index.storage_context.persist(persist_dir="./storage/sept") march_engine = march_index.as_query_engine(similarity_top_k=3, llm=llm_35) june_engine = june_index.as_query_engine(similarity_top_k=3, llm=llm_35) sept_engine = sept_index.as_query_engine(similarity_top_k=3, llm=llm_35) from llama_index.core.tools import QueryEngineTool query_tool_sept = QueryEngineTool.from_defaults( query_engine=sept_engine, name="sept_2022", description=( f"Provides information about Uber quarterly financials ending" f" September 2022" ), ) query_tool_june = QueryEngineTool.from_defaults( query_engine=june_engine, name="june_2022", description=( f"Provides information about Uber quarterly financials ending June" f" 2022" ), ) query_tool_march = QueryEngineTool.from_defaults( query_engine=march_engine, name="march_2022", description=( f"Provides information about Uber quarterly financials ending March" f" 2022" ), ) query_engine_tools = [query_tool_march, query_tool_june, query_tool_sept] from llama_index.core.agent import ReActAgent from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo-0613") base_agent = ReActAgent.from_tools(query_engine_tools, llm=llm, verbose=True) response = base_agent.chat( "Analyze Uber revenue growth over the last few quarters" ) print(str(response)) print(str(response)) response = base_agent.chat( "Can you tell me about the risk factors in the quarter with the highest" " revenue growth?" ) print(str(response)) from llama_index.core.evaluation import DatasetGenerator base_question_gen_query = ( "You are a Teacher/ Professor. Your task is to setup a quiz/examination." " Using the provided context from the Uber March 10Q filing, formulate a" " single question that captures an important fact from the context." " context. Restrict the question to the context information provided." ) dataset_generator = DatasetGenerator.from_documents( march_docs, question_gen_query=base_question_gen_query, llm=llm_35, ) questions = dataset_generator.generate_questions_from_nodes(num=20) questions from llama_index.llms.openai import OpenAI from llama_index.core import PromptTemplate vary_question_tmpl = """\ You are a financial assistant. Given a question over a 2023 Uber 10Q filing, your goal is to generate up to {num_vary} variations of that question that might span multiple 10Q's. This can include compare/contrasting different 10Qs, replacing the current quarter with another quarter, or generating questions that can only be answered over multiple quarters (be creative!) You are given a valid set of 10Q filings. Please only generate question variations that can be answered in that set. For example: Base Question: What was the free cash flow of Uber in March 2023? Valid 10Qs: [March 2023, June 2023, September 2023] Question Variations: What was the free cash flow of Uber in June 2023? Can you compare/contrast the free cash flow of Uber in June/September 2023 and offer explanations for the change? Did the free cash flow of Uber increase of decrease in 2023? Now let's give it a shot! Base Question: {base_question} Valid 10Qs: {valid_10qs} Question Variations: """ def gen_question_variations(base_questions, num_vary=3): """Generate question variations.""" VALID_10Q_STR = "[March 2022, June 2022, September 2022]" llm = OpenAI(model="gpt-4") prompt_tmpl = PromptTemplate(vary_question_tmpl) new_questions = [] for idx, question in enumerate(base_questions): new_questions.append(question) response = llm.complete( prompt_tmpl.format( num_vary=num_vary, base_question=question, valid_10qs=VALID_10Q_STR, ) ) raw_lines = str(response).split("\n") cur_new_questions = [l for l in raw_lines if l != ""] print(f"[{idx}] Original Question: {question}") print(f"[{idx}] Generated Question Variations: {cur_new_questions}") new_questions.extend(cur_new_questions) return new_questions def save_questions(questions, path): with open(path, "w") as f: for question in questions: f.write(question + "\n") def load_questions(path): questions = [] with open(path, "r") as f: for line in f: questions.append(line.strip()) return questions new_questions = gen_question_variations(questions) len(new_questions) train_questions, eval_questions = new_questions[:60], new_questions[60:] save_questions(train_questions, "train_questions_10q.txt") save_questions(eval_questions, "eval_questions_10q.txt") train_questions = load_questions("train_questions_10q.txt") eval_questions = load_questions("eval_questions_10q.txt") from llama_index.llms.openai import OpenAI from llama_index.finetuning.callbacks import OpenAIFineTuningHandler from llama_index.core.callbacks import CallbackManager from llama_index.core.agent import ReActAgent finetuning_handler =
OpenAIFineTuningHandler()
llama_index.finetuning.callbacks.OpenAIFineTuningHandler
from llama_index.tools.waii import WaiiToolSpec waii_tool = WaiiToolSpec( url="https://tweakit.waii.ai/api/", api_key="3........", database_key="snowflake://....", verbose=True, ) from llama_index import VectorStoreIndex documents = waii_tool.load_data("Get all tables with their number of columns") index =
VectorStoreIndex.from_documents(documents)
llama_index.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-anyscale') get_ipython().system('pip install llama-index') from llama_index.llms.anyscale import Anyscale from llama_index.core.llms import ChatMessage llm =
Anyscale(api_key="<your-api-key>")
llama_index.llms.anyscale.Anyscale
get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-google') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-google') get_ipython().run_line_magic('pip', 'install llama-index-response-synthesizers-google') get_ipython().run_line_magic('pip', 'install llama-index') get_ipython().run_line_magic('pip', 'install "google-ai-generativelanguage>=0.4,<=1.0"') get_ipython().run_line_magic('pip', 'install google-auth-oauthlib') from google.oauth2 import service_account from llama_index.vector_stores.google import set_google_config credentials = service_account.Credentials.from_service_account_file( "service_account_key.json", scopes=[ "https://www.googleapis.com/auth/generative-language.retriever", ], ) set_google_config(auth_credentials=credentials) get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") import llama_index.core.vector_stores.google.generativeai.genai_extension as genaix from typing import Iterable from random import randrange LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX = f"llama-index-colab" SESSION_CORPUS_ID_PREFIX = ( f"{LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX}-{randrange(1000000)}" ) def corpus_id(num_id: int) -> str: return f"{SESSION_CORPUS_ID_PREFIX}-{num_id}" SESSION_CORPUS_ID = corpus_id(1) def list_corpora() -> Iterable[genaix.Corpus]: client = genaix.build_semantic_retriever() yield from genaix.list_corpora(client=client) def delete_corpus(*, corpus_id: str) -> None: client = genaix.build_semantic_retriever() genaix.delete_corpus(corpus_id=corpus_id, client=client) def cleanup_colab_corpora(): for corpus in list_corpora(): if corpus.corpus_id.startswith(LLAMA_INDEX_COLAB_CORPUS_ID_PREFIX): try: delete_corpus(corpus_id=corpus.corpus_id) print(f"Deleted corpus {corpus.corpus_id}.") except Exception: pass cleanup_colab_corpora() from llama_index.core import SimpleDirectoryReader from llama_index.indices.managed.google import GoogleIndex from llama_index.core import Response import time index = GoogleIndex.create_corpus( corpus_id=SESSION_CORPUS_ID, display_name="My first corpus!" ) print(f"Newly created corpus ID is {index.corpus_id}.") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() index.insert_documents(documents) for corpus in list_corpora(): print(corpus) query_engine = index.as_query_engine() response = query_engine.query("What did Paul Graham do growing up?") assert isinstance(response, Response) print(f"Response is {response.response}") for cited_text in [node.text for node in response.source_nodes]: print(f"Cited text: {cited_text}") if response.metadata: print( f"Answerability: {response.metadata.get('answerable_probability', 0)}" ) index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) query_engine = index.as_query_engine() response = query_engine.query("Which company did Paul Graham build?") assert isinstance(response, Response) print(f"Response is {response.response}") from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) index.insert_nodes( [ TextNode( text="It was the best of times.", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="123", metadata={"file_name": "Tale of Two Cities"}, ) }, ), TextNode( text="It was the worst of times.", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="123", metadata={"file_name": "Tale of Two Cities"}, ) }, ), TextNode( text="Bugs Bunny: Wassup doc?", relationships={ NodeRelationship.SOURCE: RelatedNodeInfo( node_id="456", metadata={"file_name": "Bugs Bunny Adventure"}, ) }, ), ] ) from google.ai.generativelanguage import ( GenerateAnswerRequest, HarmCategory, SafetySetting, ) index = GoogleIndex.from_corpus(corpus_id=SESSION_CORPUS_ID) query_engine = index.as_query_engine( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, safety_setting=[ SafetySetting( category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold=SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, ), SafetySetting( category=HarmCategory.HARM_CATEGORY_VIOLENCE, threshold=SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH, ), ], ) response = query_engine.query("What was Bugs Bunny's favorite saying?") print(response) from llama_index.core import Response response = query_engine.query("What were Paul Graham's achievements?") assert isinstance(response, Response) print(f"Response is {response.response}") for cited_text in [node.text for node in response.source_nodes]: print(f"Cited text: {cited_text}") if response.metadata: print( f"Answerability: {response.metadata.get('answerable_probability', 0)}" ) from llama_index.llms.gemini import Gemini GEMINI_API_KEY = "" # @param {type:"string"} gemini = Gemini(api_key=GEMINI_API_KEY) from llama_index.response_synthesizers.google import GoogleTextSynthesizer from llama_index.vector_stores.google import GoogleVectorStore from llama_index.core import VectorStoreIndex from llama_index.core.postprocessor import LLMRerank from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.retrievers import VectorIndexRetriever store = GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID) index = VectorStoreIndex.from_vector_store( vector_store=store, ) response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, ) reranker = LLMRerank( top_n=10, llm=gemini, ) query_engine = RetrieverQueryEngine.from_args( retriever=VectorIndexRetriever( index=index, similarity_top_k=20, ), node_postprocessors=[reranker], response_synthesizer=response_synthesizer, ) response = query_engine.query("What were Paul Graham's achievements?") print(response) from llama_index.core.indices.query.query_transform.base import ( StepDecomposeQueryTransform, ) from llama_index.core.query_engine import MultiStepQueryEngine store = GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID) index = VectorStoreIndex.from_vector_store( vector_store=store, ) response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, ) single_step_query_engine = index.as_query_engine( similarity_top_k=10, response_synthesizer=response_synthesizer, ) step_decompose_transform = StepDecomposeQueryTransform( llm=gemini, verbose=True, ) query_engine = MultiStepQueryEngine( query_engine=single_step_query_engine, query_transform=step_decompose_transform, response_synthesizer=response_synthesizer, index_summary="Ask me anything.", num_steps=6, ) response = query_engine.query("What were Paul Graham's achievements?") print(response) from llama_index.core.indices.query.query_transform import HyDEQueryTransform from llama_index.core.query_engine import TransformQueryEngine store = GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID) index = VectorStoreIndex.from_vector_store( vector_store=store, ) response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.2, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, ) base_query_engine = index.as_query_engine( similarity_top_k=10, response_synthesizer=response_synthesizer, ) hyde = HyDEQueryTransform( llm=gemini, include_original=False, ) hyde_query_engine = TransformQueryEngine(base_query_engine, hyde) response = query_engine.query("What were Paul Graham's achievements?") print(response) store =
GoogleVectorStore.from_corpus(corpus_id=SESSION_CORPUS_ID)
llama_index.vector_stores.google.GoogleVectorStore.from_corpus