prompt
stringlengths
70
19.8k
completion
stringlengths
8
1.03k
api
stringlengths
23
93
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-colbert') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-gemini') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-vectara') 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 torch sentence-transformers') get_ipython().run_line_magic('pip', 'install google-auth-oauthlib') from google.oauth2 import service_account from llama_index.indices.managed.google import GoogleIndex 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/cloud-platform", "https://www.googleapis.com/auth/generative-language.retriever", ], ) set_google_config(auth_credentials=credentials) project_name = "TODO-your-project-name" # @param {type:"string"} email = "ht@runllama.ai" # @param {type:"string"} client_file_name = "client_secret.json" get_ipython().system('gcloud config set project $project_name') get_ipython().system('gcloud config set account $email') get_ipython().system('gcloud auth application-default login --no-browser --client-id-file=$client_file_name --scopes="https://www.googleapis.com/auth/generative-language.retriever,https://www.googleapis.com/auth/cloud-platform"') 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 GOOGLE_API_KEY = "" # add your GOOGLE API key here os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY from llama_index.core import SimpleDirectoryReader from llama_index.indices.managed.google import GoogleIndex google_index = GoogleIndex.create_corpus(display_name="My first corpus!") print(f"Newly created corpus ID is {google_index.corpus_id}.") documents =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-output-parsers-guardrails') get_ipython().system('pip install guardrails-ai') 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 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 IPython.display import Markdown, display import os os.environ["OPENAI_API_KEY"] = "sk-..." documents = SimpleDirectoryReader("./data/paul_graham/").load_data() index =
VectorStoreIndex.from_documents(documents, chunk_size=512)
llama_index.core.VectorStoreIndex.from_documents
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") import pandas as pd def display_eval_df(question, source, answer_a, answer_b, result) -> None: """Pretty print question/answer + gpt-4 judgement dataset.""" eval_df = pd.DataFrame( { "Question": question, "Source": source, "Model A": answer_a["model"], "Answer A": answer_a["text"], "Model B": answer_b["model"], "Answer B": answer_b["text"], "Score": result.score, "Judgement": result.feedback, }, index=[0], ) eval_df = eval_df.style.set_properties( **{ "inline-size": "300px", "overflow-wrap": "break-word", }, subset=["Answer A", "Answer B"] ) display(eval_df) get_ipython().system('pip install wikipedia -q') from llama_index.readers.wikipedia import WikipediaReader train_cities = [ "San Francisco", "Toronto", "New York", "Vancouver", "Montreal", "Boston", ] test_cities = [ "Tokyo", "Singapore", "Paris", ] train_documents = WikipediaReader().load_data( pages=[f"History of {x}" for x in train_cities] ) test_documents = WikipediaReader().load_data( pages=[f"History of {x}" for x in test_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 llm = OpenAI(model="gpt-3.5-turbo", temperature=0.3) train_dataset_generator = DatasetGenerator.from_documents( train_documents, question_gen_query=QUESTION_GEN_PROMPT, llm=llm, show_progress=True, num_questions_per_chunk=25, ) test_dataset_generator = DatasetGenerator.from_documents( test_documents, question_gen_query=QUESTION_GEN_PROMPT, llm=llm, show_progress=True, num_questions_per_chunk=25, ) train_questions = train_dataset_generator.generate_questions_from_nodes( num=200 ) test_questions = test_dataset_generator.generate_questions_from_nodes(num=150) len(train_questions), len(test_questions) train_questions[:3] test_questions[:3] from llama_index.core import VectorStoreIndex from llama_index.core.retrievers import VectorIndexRetriever train_index =
VectorStoreIndex.from_documents(documents=train_documents)
llama_index.core.VectorStoreIndex.from_documents
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-llms-anthropic') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') 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.llms.openai import OpenAI from llama_index.llms.anthropic import Anthropic llm = OpenAI() data = SimpleDirectoryReader(input_dir="./data/paul_graham/").load_data() index = VectorStoreIndex.from_documents(data) chat_engine = index.as_chat_engine(chat_mode="react", llm=llm, verbose=True) response = chat_engine.chat( "Use the tool to answer what did Paul Graham do in the summer of 1995?" ) print(response) llm =
Anthropic()
llama_index.llms.anthropic.Anthropic
get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-cohere-rerank') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-finetuning') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-cohere') get_ipython().system('pip install llama-index cohere pypdf') openai_api_key = "YOUR OPENAI API KEY" cohere_api_key = "YOUR COHEREAI API KEY" import os os.environ["OPENAI_API_KEY"] = openai_api_key os.environ["COHERE_API_KEY"] = cohere_api_key from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.node_parser import SimpleNodeParser from llama_index.llms.openai import OpenAI from llama_index.embeddings.cohere import CohereEmbedding from llama_index.core.retrievers import BaseRetriever, VectorIndexRetriever from llama_index.core import QueryBundle from llama_index.core.indices.query.schema import QueryType from llama_index.core.schema import NodeWithScore from llama_index.postprocessor.cohere_rerank import CohereRerank from llama_index.core.evaluation import EmbeddingQAFinetuneDataset from llama_index.finetuning import generate_cohere_reranker_finetuning_dataset from llama_index.core.evaluation import generate_question_context_pairs from llama_index.core.evaluation import RetrieverEvaluator from llama_index.finetuning import CohereRerankerFinetuneEngine from typing import List import pandas as pd import nest_asyncio nest_asyncio.apply() 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'") lyft_docs = SimpleDirectoryReader( input_files=["./data/10k/lyft_2021.pdf"] ).load_data() uber_docs = SimpleDirectoryReader( input_files=["./data/10k/uber_2021.pdf"] ).load_data() node_parser =
SimpleNodeParser.from_defaults(chunk_size=400)
llama_index.core.node_parser.SimpleNodeParser.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-llms-openllm') get_ipython().system('pip install "openllm" # use \'openllm[vllm]\' if you have access to GPU') get_ipython().system('pip install llama-index') import os from typing import List, Optional from llama_index.llms.openllm import OpenLLM, OpenLLMAPI from llama_index.core.llms import ChatMessage os.environ[ "OPENLLM_ENDPOINT" ] = "na" # Change this to a remote server that you might run OpenLLM at. local_llm = OpenLLM("HuggingFaceH4/zephyr-7b-alpha") remote_llm = OpenLLMAPI(address="http://localhost:3000") remote_llm = OpenLLMAPI() completion_response = remote_llm.complete("To infinity, and") print(completion_response) for it in remote_llm.stream_complete( "The meaning of time is", max_new_tokens=128 ): print(it, end="", flush=True) async for it in remote_llm.astream_chat( [ ChatMessage( role="system", content="You are acting as Ernest Hemmingway." ), ChatMessage(role="user", content="Hi there!"),
ChatMessage(role="assistant", content="Yes?")
llama_index.core.llms.ChatMessage
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)
llama_index.core.output_parsers.PydanticOutputParser
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-hub-llama-packs-tables-chain-of-table-base') get_ipython().system('wget "https://github.com/ppasupat/WikiTableQuestions/releases/download/v1.0.2/WikiTableQuestions-1.0.2-compact.zip" -O data.zip') get_ipython().system('unzip data.zip') import pandas as pd df = pd.read_csv("./WikiTableQuestions/csv/200-csv/3.csv") df from llama_index.packs.tables.chain_of_table.base import ( ChainOfTableQueryEngine, serialize_table, ) from llama_index.core.llama_pack import download_llama_pack download_llama_pack( "ChainOfTablePack", "./chain_of_table_pack", skip_load=True, ) from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-4-1106-preview") import phoenix as px import llama_index.core px.launch_app() llama_index.core.set_global_handler("arize_phoenix") import pandas as pd df = pd.read_csv("~/Downloads/WikiTableQuestions/csv/200-csv/11.csv") df query_engine = ChainOfTableQueryEngine(df, llm=llm, verbose=True) response = query_engine.query("Who won best Director in the 1972 Academy Awards?") str(response.response) import pandas as pd df = pd.read_csv("./WikiTableQuestions/csv/200-csv/42.csv") df query_engine = ChainOfTableQueryEngine(df, llm=llm, verbose=True) response = query_engine.query("What was the precipitation in inches during June?") str(response) from llama_index.core import PromptTemplate from llama_index.core.query_pipeline import QueryPipeline prompt_str = """\ Here's a serialized table. {serialized_table} Given this table please answer the question: {question} Answer: """ prompt = PromptTemplate(prompt_str) prompt_c = prompt.as_query_component(partial={"serialized_table": serialize_table(df)}) qp = QueryPipeline(chain=[prompt_c, llm]) response = qp.run("What was the precipitation in inches during June?") print(str(response)) import pandas as pd df = pd.read_csv("./WikiTableQuestions/csv/203-csv/114.csv") df query_engine = ChainOfTableQueryEngine(df, llm=llm, verbose=True) response = query_engine.query("Which televised ABC game had the greatest attendance?") print(str(response)) from llama_index.core import PromptTemplate from llama_index.core.query_pipeline import QueryPipeline prompt_str = """\ Here's a serialized table. {serialized_table} Given this table please answer the question: {question} Answer: """ prompt =
PromptTemplate(prompt_str)
llama_index.core.PromptTemplate
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")) ] # add a SQLTableSchema for each table obj_index = ObjectIndex.from_objects( table_schema_objs, table_node_mapping, VectorStoreIndex, ) query_engine = SQLTableRetrieverQueryEngine( sql_database, obj_index.as_retriever(similarity_top_k=1) ) response = query_engine.query("Which city has the highest population?") display(Markdown(f"<b>{response}</b>")) response.metadata["result"] city_stats_text = ( "This table gives information regarding the population and country of a" " given city.\nThe user will query with codewords, where 'foo' corresponds" " to population and 'bar'corresponds to city." ) table_node_mapping = SQLTableNodeMapping(sql_database) table_schema_objs = [ (SQLTableSchema(table_name="city_stats", context_str=city_stats_text)) ] from llama_index.core.retrievers import NLSQLRetriever nl_sql_retriever = NLSQLRetriever( sql_database, tables=["city_stats"], return_raw=True ) results = nl_sql_retriever.retrieve( "Return the top 5 cities (along with their populations) with the highest population." ) from llama_index.core.response.notebook_utils import display_source_node for n in results: display_source_node(n) nl_sql_retriever = NLSQLRetriever( sql_database, tables=["city_stats"], return_raw=False ) results = nl_sql_retriever.retrieve( "Return the top 5 cities (along with their populations) with the highest population." ) for n in results: display_source_node(n, show_source_metadata=True) from llama_index.core.query_engine import RetrieverQueryEngine query_engine =
RetrieverQueryEngine.from_args(nl_sql_retriever)
llama_index.core.query_engine.RetrieverQueryEngine.from_args
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/").load_data() index = VectorStoreIndex.from_documents(documents=documents) query_str = "What did the author do growing up?" query_engine = index.as_query_engine() response = query_engine.query(query_str) wrapper =
MakeWrapper()
llama_index.readers.make_com.MakeWrapper
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import camelot from llama_index.core import VectorStoreIndex from llama_index.core.query_engine import PandasQueryEngine from llama_index.core.schema import IndexNode from llama_index.llms.openai import OpenAI from llama_index.readers.file import PyMuPDFReader from typing import List import os os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY" from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-3.5-turbo") Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small") file_path = "billionaires_page.pdf" reader = PyMuPDFReader() docs = reader.load(file_path) def get_tables(path: str, pages: List[int]): table_dfs = [] for page in pages: table_list = camelot.read_pdf(path, pages=str(page)) table_df = table_list[0].df table_df = ( table_df.rename(columns=table_df.iloc[0]) .drop(table_df.index[0]) .reset_index(drop=True) ) table_dfs.append(table_df) return table_dfs table_dfs = get_tables(file_path, pages=[3, 25]) table_dfs[0] table_dfs[1] llm = OpenAI(model="gpt-4") df_query_engines = [ PandasQueryEngine(table_df, llm=llm) for table_df in table_dfs ] response = df_query_engines[0].query( "What's the net worth of the second richest billionaire in 2023?" ) print(str(response)) response = df_query_engines[1].query( "How many billionaires were there in 2009?" ) print(str(response)) from llama_index.core import Settings doc_nodes =
Settings.node_parser.get_nodes_from_documents(docs)
llama_index.core.Settings.node_parser.get_nodes_from_documents
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') 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 =
OpenAI(model="gpt-4-1106-preview")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().system('mkdir -p data') get_ipython().system('echo "This is a test file: one!" > data/test1.txt') get_ipython().system('echo "This is a test file: two!" > data/test2.txt') from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data", filename_as_id=True).load_data() from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core.ingestion import IngestionPipeline 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.core.node_parser import SentenceSplitter pipeline = IngestionPipeline( transformations=[ SentenceSplitter(),
HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
llama_index.embeddings.huggingface.HuggingFaceEmbedding
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai-legacy') get_ipython().system('pip install llama-index') import json from typing import Sequence from llama_index.core.tools import BaseTool, FunctionTool def multiply(a: int, b: int) -> int: """Multiply two integers and returns the result integer""" return a * b def add(a: int, b: int) -> int: """Add two integers and returns the result integer""" return a + b def useless(a: int, b: int) -> int: """Toy useless function.""" pass multiply_tool = FunctionTool.from_defaults(fn=multiply, name="multiply") useless_tools = [ FunctionTool.from_defaults(fn=useless, name=f"useless_{str(idx)}") for idx in range(28) ] add_tool =
FunctionTool.from_defaults(fn=add, name="add")
llama_index.core.tools.FunctionTool.from_defaults
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)
llama_index.core.query_engine.TransformQueryEngine
get_ipython().system('pip install llama-index llama-index-packs-raptor llama-index-vector-stores-qdrant') from llama_index.packs.raptor import RaptorPack get_ipython().system('wget https://arxiv.org/pdf/2401.18059.pdf -O ./raptor_paper.pdf') import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() from llama_index.core import SimpleDirectoryReader documents =
SimpleDirectoryReader(input_files=["./raptor_paper.pdf"])
llama_index.core.SimpleDirectoryReader
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) vector_index = VectorStoreIndex.from_documents(documents) vector_query_engine = vector_index.as_query_engine(similarity_top_k=2) summary_index =
SummaryIndex.from_documents(documents)
llama_index.core.SummaryIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-dynamodb') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-dynamodb') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-dynamodb') 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.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) TABLE_NAME = os.environ["DYNAMODB_TABLE_NAME"] from llama_index.storage.docstore.dynamodb import DynamoDBDocumentStore from llama_index.storage.index_store.dynamodb import DynamoDBIndexStore from llama_index.vector_stores.dynamodb import DynamoDBVectorStore storage_context = StorageContext.from_defaults( docstore=DynamoDBDocumentStore.from_table_name(table_name=TABLE_NAME), index_store=DynamoDBIndexStore.from_table_name(table_name=TABLE_NAME), vector_store=DynamoDBVectorStore.from_table_name(table_name=TABLE_NAME), ) storage_context.docstore.add_documents(nodes) 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() 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=
DynamoDBDocumentStore.from_table_name(table_name=TABLE_NAME)
llama_index.storage.docstore.dynamodb.DynamoDBDocumentStore.from_table_name
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai-legacy') get_ipython().system('pip install llama-index') import json from typing import Sequence 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/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 get_ipython().system("mkdir -p 'data/10q/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_march_2022.pdf' -O 'data/10q/uber_10q_march_2022.pdf'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_june_2022.pdf' -O 'data/10q/uber_10q_june_2022.pdf'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/10q/uber_10q_sept_2022.pdf' -O 'data/10q/uber_10q_sept_2022.pdf'") 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)
llama_index.core.VectorStoreIndex.from_documents
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') import openai import os os.environ["OPENAI_API_KEY"] = "[You API key]" 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)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp-free") pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True) from llama_index.core import StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import VectorStoreIndex 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)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-llms-rungpt') get_ipython().system('pip install llama-index') get_ipython().system('pip install rungpt') get_ipython().system('rungpt serve decapoda-research/llama-7b-hf --precision fp16 --device_map balanced') from llama_index.llms.rungpt import RunGptLLM llm = RunGptLLM() promot = "What public transportation might be available in a city?" response = llm.complete(promot) print(response) from llama_index.core.llms import ChatMessage, MessageRole from llama_index.llms.rungpt import RunGptLLM messages = [ ChatMessage( role=MessageRole.USER, content="Now, I want you to do some math for me.", ), ChatMessage( role=MessageRole.ASSISTANT, content="Sure, I would like to help you." ), ChatMessage( role=MessageRole.USER, content="How many points determine a straight line?", ), ] llm =
RunGptLLM()
llama_index.llms.rungpt.RunGptLLM
get_ipython().run_line_magic('', 'pip install llama-index-llms-groq') get_ipython().system('pip install llama-index') from llama_index.llms.groq import Groq llm = Groq(model="mixtral-8x7b-32768", api_key="your_api_key") response = llm.complete("Explain the importance of low latency LLMs") print(response) 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")
llama_index.core.llms.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().system('pip install llama-index') import os import openai os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE" 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)) import weaviate resource_owner_config = weaviate.AuthClientPassword( username="<username>", password="<password>", ) client = weaviate.Client( "https://llama-test-ezjahb4m.weaviate.network", auth_client_secret=resource_owner_config, ) from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.weaviate import WeaviateVectorStore 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() from llama_index.core import StorageContext vector_store = WeaviateVectorStore( weaviate_client=client, index_name="LlamaIndex" ) 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("What did the author do growing up?") display(Markdown(f"<b>{response}</b>")) resource_owner_config = weaviate.AuthClientPassword( username="<username>", password="<password>", ) client = weaviate.Client( "https://llama-test-ezjahb4m.weaviate.network", auth_client_secret=resource_owner_config, ) vector_store = WeaviateVectorStore( weaviate_client=client, index_name="LlamaIndex" ) loaded_index =
VectorStoreIndex.from_vector_store(vector_store)
llama_index.core.VectorStoreIndex.from_vector_store
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') import openai import os os.environ["OPENAI_API_KEY"] = "[You API key]" 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)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp-free") pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True) from llama_index.core import StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import VectorStoreIndex 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) 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') from llama_index.readers.wikipedia import WikipediaReader cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) from llama_index.core import SQLDatabase 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"], ) from llama_index.core import Settings 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-llms-openai') get_ipython().system('pip install llama-index') from llama_index.llms.openai import OpenAI resp = OpenAI().complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.openai import OpenAI messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="What is your name"), ] resp = OpenAI().chat(messages) print(resp) from llama_index.llms.openai import OpenAI llm = OpenAI() resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI from llama_index.core.llms import ChatMessage llm =
OpenAI()
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') 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.llms.openai import OpenAI llm = OpenAI(model="gpt-4") node_parser = SentenceSplitter(chunk_size=1024) nodes = node_parser.get_nodes_from_documents(documents) index = VectorStoreIndex(nodes) query_engine = index.as_query_engine(llm=llm) from llama_index.core.schema import BaseNode from llama_index.llms.openai import OpenAI from llama_index.core.llms import ChatMessage, MessageRole from llama_index.core import ChatPromptTemplate, PromptTemplate from typing import Tuple, List import re llm = OpenAI(model="gpt-4") QA_PROMPT = PromptTemplate( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information and not prior knowledge, " "answer the query.\n" "Query: {query_str}\n" "Answer: " ) def generate_answers_for_questions( questions: List[str], context: str, llm: OpenAI ) -> str: """Generate answers for questions given context.""" answers = [] for question in questions: fmt_qa_prompt = QA_PROMPT.format( context_str=context, query_str=question ) response_obj = llm.complete(fmt_qa_prompt) answers.append(str(response_obj)) return answers QUESTION_GEN_USER_TMPL = ( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information and not prior knowledge, " "generate the relevant questions. " ) QUESTION_GEN_SYS_TMPL = """\ You are a Teacher/ Professor. Your task is to setup \ {num_questions_per_chunk} questions for an upcoming \ quiz/examination. The questions should be diverse in nature \ across the document. Restrict the questions to the \ context information provided.\ """ question_gen_template = ChatPromptTemplate( message_templates=[ ChatMessage(role=MessageRole.SYSTEM, content=QUESTION_GEN_SYS_TMPL), ChatMessage(role=MessageRole.USER, content=QUESTION_GEN_USER_TMPL), ] ) def generate_qa_pairs( nodes: List[BaseNode], llm: OpenAI, num_questions_per_chunk: int = 10 ) -> List[Tuple[str, str]]: """Generate questions.""" qa_pairs = [] for idx, node in enumerate(nodes): print(f"Node {idx}/{len(nodes)}") context_str = node.get_content(metadata_mode="all") fmt_messages = question_gen_template.format_messages( num_questions_per_chunk=10, context_str=context_str, ) chat_response = llm.chat(fmt_messages) raw_output = chat_response.message.content result_list = str(raw_output).strip().split("\n") cleaned_questions = [ re.sub(r"^\d+[\).\s]", "", question).strip() for question in result_list ] answers = generate_answers_for_questions( cleaned_questions, context_str, llm ) cur_qa_pairs = list(zip(cleaned_questions, answers)) qa_pairs.extend(cur_qa_pairs) return qa_pairs qa_pairs qa_pairs = generate_qa_pairs( nodes, llm, num_questions_per_chunk=10, ) import pickle pickle.dump(qa_pairs, open("eval_dataset.pkl", "wb")) import pickle qa_pairs = pickle.load(open("eval_dataset.pkl", "rb")) from llama_index.core.llms import ChatMessage, MessageRole from llama_index.core import ChatPromptTemplate, PromptTemplate from typing import Dict CORRECTNESS_SYS_TMPL = """ You are an expert evaluation system for a question answering chatbot. You are given the following information: - a user query, - a reference answer, and - a generated answer. Your job is to judge the relevance and correctness of the generated answer. Output a single score that represents a holistic evaluation. You must return your response in a line with only the score. Do not return answers in any other format. On a separate line provide your reasoning for the score as well. Follow these guidelines for scoring: - Your score has to be between 1 and 5, where 1 is the worst and 5 is the best. - If the generated answer is not relevant to the user query, \ you should give a score of 1. - If the generated answer is relevant but contains mistakes, \ you should give a score between 2 and 3. - If the generated answer is relevant and fully correct, \ you should give a score between 4 and 5. """ CORRECTNESS_USER_TMPL = """ {query} {reference_answer} {generated_answer} """ eval_chat_template = ChatPromptTemplate( message_templates=[
ChatMessage(role=MessageRole.SYSTEM, content=CORRECTNESS_SYS_TMPL)
llama_index.core.llms.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') import os os.environ["OPENAI_API_KEY"] = "sk-..." get_ipython().system("mkdir -p 'data/'") get_ipython().system("curl 'https://arxiv.org/pdf/2307.09288.pdf' -o 'data/llama2.pdf'") get_ipython().system('pip install unstructured[pdf]') from llama_index.core import VectorStoreIndex from llama_index.readers.file import UnstructuredReader documents = UnstructuredReader().load_data("data/llama2.pdf") index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() from llama_index.core.llama_pack import download_llama_pack FuzzyCitationEnginePack =
download_llama_pack("FuzzyCitationEnginePack", "./fuzzy_pack")
llama_index.core.llama_pack.download_llama_pack
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') 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-..." from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.llms.openai import OpenAI from IPython.display import Markdown, display gpt35 = OpenAI(temperature=0, model="gpt-3.5-turbo") gpt4 =
OpenAI(temperature=0, model="gpt-4")
llama_index.llms.openai.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"] 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)
llama_index.core.PromptTemplate
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)
llama_index.core.VectorStoreIndex
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) from llama_index.core import ChatPromptTemplate chat_text_qa_msgs = [ ( "system", "Always answer the question, even if the context isn't helpful.", ), ("user", qa_prompt_str), ] text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs) chat_refine_msgs = [ ( "system", "Always answer the question, even if the context isn't helpful.", ), ("user", refine_prompt_str), ] refine_template = ChatPromptTemplate.from_messages(chat_refine_msgs) import openai import os os.environ["OPENAI_API_KEY"] = "sk-..." openai.api_key = os.environ["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'") from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.llms.openai import OpenAI documents =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
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?")
llama_index.core.llms.ChatMessage
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
get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-rankgpt-rerank') get_ipython().run_line_magic('pip', 'install llama-index-llms-huggingface') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-ollama') 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 from llama_index.core.postprocessor import LLMRerank from llama_index.llms.openai import OpenAI from IPython.display import Markdown, display import os OPENAI_API_TOKEN = "sk-" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN from llama_index.core import Settings Settings.llm =
OpenAI(temperature=0, model="gpt-3.5-turbo")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-jinaai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') get_ipython().system('pip install Pillow') import os jinaai_api_key = "YOUR_JINAAI_API_KEY" os.environ["JINAAI_API_KEY"] = jinaai_api_key from llama_index.embeddings.jinaai import JinaEmbedding embed_model = JinaEmbedding( api_key=jinaai_api_key, model="jina-embeddings-v2-base-en", ) embeddings = embed_model.get_text_embedding("This is the text to embed") print(len(embeddings)) print(embeddings[:5]) embeddings = embed_model.get_query_embedding("This is the query to embed") print(len(embeddings)) print(embeddings[:5]) embed_model = JinaEmbedding( api_key=jinaai_api_key, model="jina-embeddings-v2-base-en", embed_batch_size=16, ) embeddings = embed_model.get_text_embedding_batch( ["This is the text to embed", "More text can be provided in a batch"] ) print(len(embeddings)) print(embeddings[0][:5]) 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 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.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_source_node from IPython.display import Markdown, display documents = SimpleDirectoryReader("./data/paul_graham/").load_data() your_openai_key = "YOUR_OPENAI_KEY" llm =
OpenAI(api_key=your_openai_key)
llama_index.llms.openai.OpenAI
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)
llama_index.core.load_index_from_storage
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') import openai import os os.environ["OPENAI_API_KEY"] = "[You API key]" 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)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp-free") pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True) from llama_index.core import StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import VectorStoreIndex 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) 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') from llama_index.readers.wikipedia import WikipediaReader cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs =
WikipediaReader()
llama_index.readers.wikipedia.WikipediaReader
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) pairwise_scores_list = [] no_reranker_dict_list = [] for index, row in df_test.iterrows(): documents = [Document(text=row["paper"])] query_list = row["questions"] reference_answers_list = row["answers"] number_of_accepted_queries = 0 vector_index =
VectorStoreIndex.from_documents(documents)
llama_index.core.VectorStoreIndex.from_documents
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('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().run_line_magic('env', 'OPENAI_API_KEY=') get_ipython().run_line_magic('env', 'BRAINTRUST_API_KEY=') get_ipython().run_line_magic('env', 'TOKENIZERS_PARALLELISM=true # This is needed to avoid a warning message from Chroma') get_ipython().run_line_magic('pip', 'install -U llama_hub llama_index braintrust autoevals pypdf pillow transformers torch torchvision') 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 PDFReader from llama_index.core.response.notebook_utils import display_source_node from llama_index.core.retrievers import RecursiveRetriever from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI import json loader = PDFReader() docs0 = loader.load_data(file=Path("./data/llama2.pdf")) from llama_index.core import Document doc_text = "\n\n".join([d.get_content() for d in docs0]) docs = [
Document(text=doc_text)
llama_index.core.Document
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() callback_manager = CallbackManager([finetuning_handler]) llm_gpt4 =
OpenAI(model="gpt-4", callback_manager=callback_manager)
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-deeplake') get_ipython().system('pip install llama-index') get_ipython().system('pip install deeplake') import os import textwrap from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Document from llama_index.vector_stores.deeplake import DeepLakeVectorStore os.environ["OPENAI_API_KEY"] = "sk-********************************" os.environ["ACTIVELOOP_TOKEN"] = "********************************" import urllib.request urllib.request.urlretrieve( "https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt", "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].hash, ) from llama_index.core import StorageContext dataset_path = "./dataset/paul_graham" vector_store =
DeepLakeVectorStore(dataset_path=dataset_path, overwrite=True)
llama_index.vector_stores.deeplake.DeepLakeVectorStore
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-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-4") Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small") from llama_index.core import SimpleDirectoryReader 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) 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.core import VectorStoreIndex from llama_index.agent.openai import OpenAIAgent from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core import VectorStoreIndex tool_dict = {} for wiki_title in wiki_titles: vector_index = VectorStoreIndex.from_documents( city_docs[wiki_title], ) vector_query_engine = vector_index.as_query_engine(llm=llm) vector_tool = QueryEngineTool( query_engine=vector_query_engine, metadata=ToolMetadata( name=wiki_title, description=("Useful for questions related to" f" {wiki_title}"), ), ) tool_dict[wiki_title] = vector_tool from llama_index.core import VectorStoreIndex from llama_index.core.objects import ObjectIndex, SimpleToolNodeMapping tool_mapping = SimpleToolNodeMapping.from_objects(list(tool_dict.values())) tool_index = ObjectIndex.from_objects( list(tool_dict.values()), tool_mapping, VectorStoreIndex, ) tool_retriever = tool_index.as_retriever(similarity_top_k=1) from llama_index.core.llms import ChatMessage from llama_index.core import ChatPromptTemplate from typing import List GEN_SYS_PROMPT_STR = """\ Task information is given below. Given the task, please generate a system prompt for an OpenAI-powered bot to solve this task: {task} \ """ gen_sys_prompt_messages = [ ChatMessage( role="system", content="You are helping to build a system prompt for another bot.", ), ChatMessage(role="user", content=GEN_SYS_PROMPT_STR), ] GEN_SYS_PROMPT_TMPL =
ChatPromptTemplate(gen_sys_prompt_messages)
llama_index.core.ChatPromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-longllmlingua') get_ipython().system('pip install llmlingua llama-index') import openai openai.api_key = "<insert_openai_key>" get_ipython().system('wget "https://www.dropbox.com/s/f6bmb19xdg0xedm/paul_graham_essay.txt?dl=1" -O paul_graham_essay.txt') from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, load_index_from_storage, StorageContext, ) documents = SimpleDirectoryReader( input_files=["paul_graham_essay.txt"] ).load_data() index =
VectorStoreIndex.from_documents(documents)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().system('pip install llama-index') import time import nest_asyncio nest_asyncio.apply() import os os.environ["OPENAI_API_KEY"] = "[YOUR_API_KEY]" from llama_index.core import VectorStoreIndex, download_loader from llama_index.readers.wikipedia import WikipediaReader loader = WikipediaReader() documents = loader.load_data( pages=[ "Berlin", "Santiago", "Moscow", "Tokyo", "Jakarta", "Cairo", "Bogota", "Shanghai", "Damascus", ] ) len(documents) start_time = time.perf_counter() index =
VectorStoreIndex.from_documents(documents)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-monsterapi') get_ipython().system('python3 -m pip install llama-index --quiet -y') get_ipython().system('python3 -m pip install monsterapi --quiet') get_ipython().system('python3 -m pip install sentence_transformers --quiet') import os from llama_index.llms.monsterapi import MonsterLLM from llama_index.core.embeddings import resolve_embed_model from llama_index.core.node_parser import SentenceSplitter from llama_index.core import VectorStoreIndex, SimpleDirectoryReader os.environ["MONSTER_API_KEY"] = "" model = "llama2-7b-chat" llm = MonsterLLM(model=model, temperature=0.75) result = llm.complete("Who are you?") print(result) from llama_index.core.llms import ChatMessage history_message = ChatMessage( **{ "role": "user", "content": ( "When asked 'who are you?' respond as 'I am qblocks llm model'" " everytime." ), } ) current_message = ChatMessage(**{"role": "user", "content": "Who are you?"}) response = llm.chat([history_message, current_message]) print(response) get_ipython().system('python3 -m pip install pypdf --quiet') get_ipython().system('rm -r ./data') get_ipython().system('mkdir -p data&&cd data&&curl \'https://arxiv.org/pdf/2005.11401.pdf\' -o "RAG.pdf"') documents =
SimpleDirectoryReader("./data")
llama_index.core.SimpleDirectoryReader
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 nltk nltk.download("stopwords") import llama_index.core 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) index.set_index_id("vector_index") index.storage_context.persist("./storage") storage_context = StorageContext.from_defaults(persist_dir="storage") index = load_index_from_storage(storage_context, index_id="vector_index") query_engine = index.as_query_engine(response_mode="tree_summarize") response = query_engine.query("What did the author do growing up?") display(Markdown(f"<b>{response}</b>")) query_modes = [ "svm", "linear_regression", "logistic_regression", ] for query_mode in query_modes: query_engine = index.as_query_engine(vector_store_query_mode=query_mode) response = query_engine.query("What did the author do growing up?") print(f"Query mode: {query_mode}") display(Markdown(f"<b>{response}</b>")) display(Markdown(f"<b>{response}</b>")) print(response.source_nodes[0].text) from llama_index.core import QueryBundle query_bundle = QueryBundle( query_str="What did the author do growing up?", custom_embedding_strs=["The author grew up painting."], ) query_engine = index.as_query_engine() response = query_engine.query(query_bundle) display(Markdown(f"<b>{response}</b>")) query_engine = index.as_query_engine( vector_store_query_mode="mmr", vector_store_kwargs={"mmr_threshold": 0.2} ) response = query_engine.query("What did the author do growing up?") print(response.get_formatted_sources()) from llama_index.core import Document doc =
Document(text="target", metadata={"tag": "target"})
llama_index.core.Document
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")
llama_index.llms.openai.OpenAI
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") import pandas as pd def display_eval_df(question, source, answer_a, answer_b, result) -> None: """Pretty print question/answer + gpt-4 judgement dataset.""" eval_df = pd.DataFrame( { "Question": question, "Source": source, "Model A": answer_a["model"], "Answer A": answer_a["text"], "Model B": answer_b["model"], "Answer B": answer_b["text"], "Score": result.score, "Judgement": result.feedback, }, index=[0], ) eval_df = eval_df.style.set_properties( **{ "inline-size": "300px", "overflow-wrap": "break-word", }, subset=["Answer A", "Answer B"] ) display(eval_df) get_ipython().system('pip install wikipedia -q') from llama_index.readers.wikipedia import WikipediaReader train_cities = [ "San Francisco", "Toronto", "New York", "Vancouver", "Montreal", "Boston", ] test_cities = [ "Tokyo", "Singapore", "Paris", ] train_documents = WikipediaReader().load_data( pages=[f"History of {x}" for x in train_cities] ) test_documents = WikipediaReader().load_data( pages=[f"History of {x}" for x in test_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 llm = OpenAI(model="gpt-3.5-turbo", temperature=0.3) train_dataset_generator = DatasetGenerator.from_documents( train_documents, question_gen_query=QUESTION_GEN_PROMPT, llm=llm, show_progress=True, num_questions_per_chunk=25, ) test_dataset_generator = DatasetGenerator.from_documents( test_documents, question_gen_query=QUESTION_GEN_PROMPT, llm=llm, show_progress=True, num_questions_per_chunk=25, ) train_questions = train_dataset_generator.generate_questions_from_nodes( num=200 ) test_questions = test_dataset_generator.generate_questions_from_nodes(num=150) len(train_questions), len(test_questions) train_questions[:3] test_questions[:3] from llama_index.core import VectorStoreIndex from llama_index.core.retrievers import VectorIndexRetriever train_index = VectorStoreIndex.from_documents(documents=train_documents) train_retriever = VectorIndexRetriever( index=train_index, similarity_top_k=2, ) test_index = VectorStoreIndex.from_documents(documents=test_documents) test_retriever = VectorIndexRetriever( index=test_index, similarity_top_k=2, ) from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.llms.huggingface import HuggingFaceInferenceAPI def create_query_engine( hf_name: str, retriever: VectorIndexRetriever, hf_llm_generators: dict ) -> RetrieverQueryEngine: """Create a RetrieverQueryEngine using the HuggingFaceInferenceAPI LLM""" if hf_name not in hf_llm_generators: raise KeyError("model not listed in hf_llm_generators") llm = HuggingFaceInferenceAPI( model_name=hf_llm_generators[hf_name], context_window=2048, # to use refine token=HUGGING_FACE_TOKEN, ) return RetrieverQueryEngine.from_args(retriever=retriever, llm=llm) hf_llm_generators = { "mistral-7b-instruct": "mistralai/Mistral-7B-Instruct-v0.1", "llama2-7b-chat": "meta-llama/Llama-2-7b-chat-hf", } train_query_engines = { mdl: create_query_engine(mdl, train_retriever, hf_llm_generators) for mdl in hf_llm_generators.keys() } test_query_engines = { mdl: create_query_engine(mdl, test_retriever, hf_llm_generators) for mdl in hf_llm_generators.keys() } import tqdm import random train_dataset = [] for q in tqdm.tqdm(train_questions): model_versus = random.sample(list(train_query_engines.items()), 2) data_entry = {"question": q} responses = [] source = None for name, engine in model_versus: response = engine.query(q) response_struct = {} response_struct["model"] = name response_struct["text"] = str(response) if source is not None: assert source == response.source_nodes[0].node.text[:1000] + "..." else: source = response.source_nodes[0].node.text[:1000] + "..." responses.append(response_struct) data_entry["answers"] = responses data_entry["source"] = source 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 PairwiseComparisonEvaluator from llama_index.core import Settings main_finetuning_handler =
OpenAIFineTuningHandler()
llama_index.finetuning.callbacks.OpenAIFineTuningHandler
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-4", temperature=0) Settings.chunk_size = 512 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, VectorStoreIndex documents =
SimpleDirectoryReader("./data/paul_graham")
llama_index.core.SimpleDirectoryReader
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)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index') get_ipython().run_line_magic('pip', 'install sqlite-utils') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import os import openai os.environ["OPENAI_API_KEY"] = "YOUR_KEY_HERE" openai.api_key = os.environ["OPENAI_API_KEY"] from IPython.display import Markdown, display json_list = [ { "name": "John Doe", "age": 25, "major": "Computer Science", "email": "john.doe@example.com", "address": "123 Main St", "city": "New York", "state": "NY", "country": "USA", "phone": "+1 123-456-7890", "occupation": "Software Engineer", }, { "name": "Jane Smith", "age": 30, "major": "Business Administration", "email": "jane.smith@example.com", "address": "456 Elm St", "city": "San Francisco", "state": "CA", "country": "USA", "phone": "+1 234-567-8901", "occupation": "Marketing Manager", }, { "name": "Michael Johnson", "age": 35, "major": "Finance", "email": "michael.johnson@example.com", "address": "789 Oak Ave", "city": "Chicago", "state": "IL", "country": "USA", "phone": "+1 345-678-9012", "occupation": "Financial Analyst", }, { "name": "Emily Davis", "age": 28, "major": "Psychology", "email": "emily.davis@example.com", "address": "234 Pine St", "city": "Los Angeles", "state": "CA", "country": "USA", "phone": "+1 456-789-0123", "occupation": "Psychologist", }, { "name": "Alex Johnson", "age": 27, "major": "Engineering", "email": "alex.johnson@example.com", "address": "567 Cedar Ln", "city": "Seattle", "state": "WA", "country": "USA", "phone": "+1 567-890-1234", "occupation": "Civil Engineer", }, { "name": "Jessica Williams", "age": 32, "major": "Biology", "email": "jessica.williams@example.com", "address": "890 Walnut Ave", "city": "Boston", "state": "MA", "country": "USA", "phone": "+1 678-901-2345", "occupation": "Biologist", }, { "name": "Matthew Brown", "age": 26, "major": "English Literature", "email": "matthew.brown@example.com", "address": "123 Peach St", "city": "Atlanta", "state": "GA", "country": "USA", "phone": "+1 789-012-3456", "occupation": "Writer", }, { "name": "Olivia Wilson", "age": 29, "major": "Art", "email": "olivia.wilson@example.com", "address": "456 Plum Ave", "city": "Miami", "state": "FL", "country": "USA", "phone": "+1 890-123-4567", "occupation": "Artist", }, { "name": "Daniel Thompson", "age": 31, "major": "Physics", "email": "daniel.thompson@example.com", "address": "789 Apple St", "city": "Denver", "state": "CO", "country": "USA", "phone": "+1 901-234-5678", "occupation": "Physicist", }, { "name": "Sophia Clark", "age": 27, "major": "Sociology", "email": "sophia.clark@example.com", "address": "234 Orange Ln", "city": "Austin", "state": "TX", "country": "USA", "phone": "+1 012-345-6789", "occupation": "Social Worker", }, { "name": "Christopher Lee", "age": 33, "major": "Chemistry", "email": "christopher.lee@example.com", "address": "567 Mango St", "city": "San Diego", "state": "CA", "country": "USA", "phone": "+1 123-456-7890", "occupation": "Chemist", }, { "name": "Ava Green", "age": 28, "major": "History", "email": "ava.green@example.com", "address": "890 Cherry Ave", "city": "Philadelphia", "state": "PA", "country": "USA", "phone": "+1 234-567-8901", "occupation": "Historian", }, { "name": "Ethan Anderson", "age": 30, "major": "Business", "email": "ethan.anderson@example.com", "address": "123 Lemon Ln", "city": "Houston", "state": "TX", "country": "USA", "phone": "+1 345-678-9012", "occupation": "Entrepreneur", }, { "name": "Isabella Carter", "age": 28, "major": "Mathematics", "email": "isabella.carter@example.com", "address": "456 Grape St", "city": "Phoenix", "state": "AZ", "country": "USA", "phone": "+1 456-789-0123", "occupation": "Mathematician", }, { "name": "Andrew Walker", "age": 32, "major": "Economics", "email": "andrew.walker@example.com", "address": "789 Berry Ave", "city": "Portland", "state": "OR", "country": "USA", "phone": "+1 567-890-1234", "occupation": "Economist", }, { "name": "Mia Evans", "age": 29, "major": "Political Science", "email": "mia.evans@example.com", "address": "234 Lime St", "city": "Washington", "state": "DC", "country": "USA", "phone": "+1 678-901-2345", "occupation": "Political Analyst", }, ] from llama_index.llms.openai import OpenAI from llama_index.core.query_engine import JSONalyzeQueryEngine llm =
OpenAI(model="gpt-3.5-turbo")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-readers-psychic') 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)) from llama_index.core import SummaryIndex from llama_index.readers.psychic import PsychicReader from IPython.display import Markdown, display psychic_key = "PSYCHIC_API_KEY" account_id = "ACCOUNT_ID" connector_id = "notion" documents =
PsychicReader(psychic_key=psychic_key)
llama_index.readers.psychic.PsychicReader
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().system('mkdir -p data') get_ipython().system('echo "This is a test file: one!" > data/test1.txt') get_ipython().system('echo "This is a test file: two!" > data/test2.txt') from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data", filename_as_id=True).load_data() from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core.ingestion import IngestionPipeline 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.core.node_parser import SentenceSplitter pipeline = IngestionPipeline( transformations=[ SentenceSplitter(), HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), ], docstore=SimpleDocumentStore(), ) nodes = pipeline.run(documents=documents) print(f"Ingested {len(nodes)} Nodes") pipeline.persist("./pipeline_storage") pipeline = IngestionPipeline( transformations=[ SentenceSplitter(), HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), ] ) pipeline.load("./pipeline_storage") get_ipython().system('echo "This is a test file: three!" > data/test3.txt') get_ipython().system('echo "This is a NEW test file: one!" > data/test1.txt') documents =
SimpleDirectoryReader("./data", filename_as_id=True)
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-rungpt') get_ipython().system('pip install llama-index') get_ipython().system('pip install rungpt') get_ipython().system('rungpt serve decapoda-research/llama-7b-hf --precision fp16 --device_map balanced') from llama_index.llms.rungpt import RunGptLLM llm =
RunGptLLM()
llama_index.llms.rungpt.RunGptLLM
get_ipython().run_line_magic('pip', 'install llama-index-llms-openllm') get_ipython().system('pip install "openllm" # use \'openllm[vllm]\' if you have access to GPU') get_ipython().system('pip install llama-index') import os from typing import List, Optional from llama_index.llms.openllm import OpenLLM, OpenLLMAPI from llama_index.core.llms import ChatMessage os.environ[ "OPENLLM_ENDPOINT" ] = "na" # Change this to a remote server that you might run OpenLLM at. local_llm = OpenLLM("HuggingFaceH4/zephyr-7b-alpha") remote_llm = OpenLLMAPI(address="http://localhost:3000") remote_llm =
OpenLLMAPI()
llama_index.llms.openllm.OpenLLMAPI
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 logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SimpleDirectoryReader 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 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) from llama_index.core.storage.docstore import SimpleDocumentStore docstore =
SimpleDocumentStore()
llama_index.core.storage.docstore.SimpleDocumentStore
get_ipython().run_line_magic('pip', 'install llama-index-finetuning') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import nest_asyncio nest_asyncio.apply() get_ipython().system('pip install llama-index') get_ipython().system('pip install spacy') wiki_titles = [ "Toronto", "Seattle", "Chicago", "Boston", "Houston", "Tokyo", "Berlin", "Lisbon", ] 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 llm = OpenAI(model="gpt-3.5-turbo", temperature=0.3) city_descs_dict = {} choices = [] choice_to_id_dict = {} for idx, wiki_title in enumerate(wiki_titles): vector_desc = ( "Useful for questions related to specific aspects of" f" {wiki_title} (e.g. the history, arts and culture," " sports, demographics, or more)." ) summary_desc = ( "Useful for any requests that require a holistic summary" f" of EVERYTHING about {wiki_title}. For questions about" " more specific sections, please use the vector_tool." ) doc_id_vector = f"{wiki_title}_vector" doc_id_summary = f"{wiki_title}_summary" city_descs_dict[doc_id_vector] = vector_desc city_descs_dict[doc_id_summary] = summary_desc choices.extend([vector_desc, summary_desc]) choice_to_id_dict[idx * 2] = f"{wiki_title}_vector" choice_to_id_dict[idx * 2 + 1] = f"{wiki_title}_summary" from llama_index.llms.openai import OpenAI from llama_index.core import PromptTemplate llm = OpenAI(model_name="gpt-3.5-turbo") summary_q_tmpl = """\ You are a summary question generator. Given an existing question which asks for a summary of a given topic, \ generate {num_vary} related queries that also ask for a summary of the topic. For example, assuming we're generating 3 related questions: Base Question: Can you tell me more about Boston? Question Variations: Give me an overview of Boston as a city. Can you describe different aspects of Boston, from the history to the sports scene to the food? Write a concise summary of Boston; I've never been. Now let's give it a shot! Base Question: {base_question} Question Variations: """ summary_q_prompt = PromptTemplate(summary_q_tmpl) from collections import defaultdict from llama_index.core.evaluation import DatasetGenerator from llama_index.core.evaluation import EmbeddingQAFinetuneDataset from llama_index.core.node_parser import SimpleNodeParser from tqdm.notebook import tqdm def generate_dataset( wiki_titles, city_descs_dict, llm, summary_q_prompt, num_vector_qs_per_node=2, num_summary_qs=4, ): queries = {} corpus = {} relevant_docs = defaultdict(list) for idx, wiki_title in enumerate(tqdm(wiki_titles)): doc_id_vector = f"{wiki_title}_vector" doc_id_summary = f"{wiki_title}_summary" corpus[doc_id_vector] = city_descs_dict[doc_id_vector] corpus[doc_id_summary] = city_descs_dict[doc_id_summary] node_parser = SimpleNodeParser.from_defaults() nodes = node_parser.get_nodes_from_documents(city_docs[wiki_title]) dataset_generator = DatasetGenerator( nodes, llm=llm, num_questions_per_chunk=num_vector_qs_per_node, ) doc_questions = dataset_generator.generate_questions_from_nodes( num=len(nodes) * num_vector_qs_per_node ) for query_idx, doc_question in enumerate(doc_questions): query_id = f"{wiki_title}_{query_idx}" relevant_docs[query_id] = [doc_id_vector] queries[query_id] = doc_question base_q = f"Give me a summary of {wiki_title}" fmt_prompt = summary_q_prompt.format( num_vary=num_summary_qs, base_question=base_q, ) raw_response = llm.complete(fmt_prompt) raw_lines = str(raw_response).split("\n") doc_summary_questions = [l for l in raw_lines if l != ""] print(f"[{idx}] Original Question: {base_q}") print( f"[{idx}] Generated Question Variations: {doc_summary_questions}" ) for query_idx, doc_summary_question in enumerate( doc_summary_questions ): query_id = f"{wiki_title}_{query_idx}" relevant_docs[query_id] = [doc_id_summary] queries[query_id] = doc_summary_question return EmbeddingQAFinetuneDataset( queries=queries, corpus=corpus, relevant_docs=relevant_docs ) dataset = generate_dataset( wiki_titles, city_descs_dict, llm, summary_q_prompt, num_vector_qs_per_node=4, num_summary_qs=5, ) dataset.save_json("dataset.json") dataset =
EmbeddingQAFinetuneDataset.from_json("dataset.json")
llama_index.core.evaluation.EmbeddingQAFinetuneDataset.from_json
from llama_hub.semanticscholar.base import SemanticScholarReader import os import openai from llama_index.llms import OpenAI from llama_index.query_engine import CitationQueryEngine from llama_index import ( VectorStoreIndex, StorageContext, load_index_from_storage, ServiceContext, ) from llama_index.response.notebook_utils import display_response s2reader = SemanticScholarReader() openai.api_key = os.environ["OPENAI_API_KEY"] service_context = ServiceContext.from_defaults( llm=OpenAI(model="gpt-3.5-turbo", temperature=0) ) query_space = "large language models" full_text = True total_papers = 50 persist_dir = ( "./citation_" + query_space + "_" + str(total_papers) + "_" + str(full_text) ) if not os.path.exists(persist_dir): documents = s2reader.load_data(query_space, total_papers, full_text=full_text) index = VectorStoreIndex.from_documents(documents, service_context=service_context) index.storage_context.persist(persist_dir=persist_dir) else: index = load_index_from_storage( StorageContext.from_defaults(persist_dir=persist_dir), service_context=service_context, ) query_engine = CitationQueryEngine.from_args( index, similarity_top_k=3, citation_chunk_size=512, ) query_string = "limitations of using large language models" response = query_engine.query(query_string) display_response( response, show_source=True, source_length=100, show_source_metadata=True ) query_space = "covid 19 vaccine" query_string = "List the efficacy numbers of the covid 19 vaccines" full_text = True total_papers = 50 persist_dir = ( "./citation_" + query_space + "_" + str(total_papers) + "_" + str(full_text) ) if not os.path.exists(persist_dir): documents = s2reader.load_data(query_space, total_papers, full_text=full_text) index = VectorStoreIndex.from_documents(documents, service_context=service_context) index.storage_context.persist(persist_dir=persist_dir) else: index = load_index_from_storage(
StorageContext.from_defaults(persist_dir=persist_dir)
llama_index.StorageContext.from_defaults
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) from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data/paul_graham").load_data() import time times = [] for _ in range(3): time.sleep(30) # help prevent rate-limits/timeouts, keeps each run fair pipline = build_pipeline() start = time.time() nodes = await pipline.arun(documents=documents) end = time.time() times.append(end - start) print(f"Average time: {sum(times) / len(times)}") get_ipython().system('pip install "llama_index<0.9.6"') import os os.environ["OPENAI_API_KEY"] = "sk-..." 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), SummaryExtractor(llm=llm, metadata_mode=MetadataMode.EMBED), OpenAIEmbedding(), ] return IngestionPipeline(transformations=transformations) from llama_index.core import SimpleDirectoryReader 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-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"] = "" dialect = "sqlite" from datasets import load_dataset from pathlib import Path import json def load_jsonl(data_dir): data_path = Path(data_dir).as_posix() data = load_dataset("json", data_files=data_path) return data def save_jsonl(data_dicts, out_path): with open(out_path, "w") as fp: for data_dict in data_dicts: fp.write(json.dumps(data_dict) + "\n") def load_data_sql(data_dir: str = "data_sql"): dataset = load_dataset("b-mc2/sql-create-context") dataset_splits = {"train": dataset["train"]} out_path = Path(data_dir) out_path.parent.mkdir(parents=True, exist_ok=True) for key, ds in dataset_splits.items(): with open(out_path, "w") as f: for item in ds: newitem = { "input": item["question"], "context": item["context"], "output": item["answer"], } f.write(json.dumps(newitem) + "\n") load_data_sql(data_dir="data_sql") from math import ceil def get_train_val_splits( data_dir: str = "data_sql", val_ratio: float = 0.1, seed: int = 42, shuffle: bool = True, ): data = load_jsonl(data_dir) num_samples = len(data["train"]) val_set_size = ceil(val_ratio * num_samples) train_val = data["train"].train_test_split( test_size=val_set_size, shuffle=shuffle, seed=seed ) return train_val["train"].shuffle(), train_val["test"].shuffle() raw_train_data, raw_val_data = get_train_val_splits(data_dir="data_sql") save_jsonl(raw_train_data, "train_data_raw.jsonl") save_jsonl(raw_val_data, "val_data_raw.jsonl") raw_train_data[0] text_to_sql_tmpl_str = """\ <s>### Instruction:\n{system_message}{user_message}\n\n### Response:\n{response}</s>""" text_to_sql_inference_tmpl_str = """\ <s>### Instruction:\n{system_message}{user_message}\n\n### Response:\n""" def _generate_prompt_sql(input, context, dialect="sqlite", output=""): system_message = f"""You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. You must output the SQL query that answers the question. """ user_message = f"""### Dialect: {dialect} {input} {context} """ if output: return text_to_sql_tmpl_str.format( system_message=system_message, user_message=user_message, response=output, ) else: return text_to_sql_inference_tmpl_str.format( system_message=system_message, user_message=user_message ) def generate_prompt(data_point): full_prompt = _generate_prompt_sql( data_point["input"], data_point["context"], dialect="sqlite", output=data_point["output"], ) return {"inputs": full_prompt} train_data = [ {"inputs": d["inputs"] for d in raw_train_data.map(generate_prompt)} ] save_jsonl(train_data, "train_data.jsonl") val_data = [{"inputs": d["inputs"] for d in raw_val_data.map(generate_prompt)}] save_jsonl(val_data, "val_data.jsonl") print(train_data[0]["inputs"]) base_model_slug = "llama2-7b-chat" base_llm = GradientBaseModelLLM( base_model_slug=base_model_slug, max_tokens=300 ) finetune_engine = GradientFinetuneEngine( base_model_slug=base_model_slug, name="text_to_sql", data_path="train_data.jsonl", verbose=True, max_steps=200, batch_size=4, ) finetune_engine.model_adapter_id epochs = 1 for i in range(epochs): print(f"** EPOCH {i} **") finetune_engine.finetune() ft_llm = finetune_engine.get_finetuned_model(max_tokens=300) def get_text2sql_completion(llm, raw_datapoint): text2sql_tmpl_str = _generate_prompt_sql( raw_datapoint["input"], raw_datapoint["context"], dialect="sqlite", output=None, ) response = llm.complete(text2sql_tmpl_str) return str(response) test_datapoint = raw_val_data[2] display(test_datapoint) get_text2sql_completion(base_llm, test_datapoint) get_text2sql_completion(ft_llm, test_datapoint) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase 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 sqlalchemy.schema import CreateTable table_create_stmt = str(CreateTable(city_stats_table)) print(table_create_stmt) 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.connect() as connection: cursor = connection.execute(stmt) connection.commit() from llama_index.core.query_engine import NLSQLTableQueryEngine from llama_index.core import PromptTemplate def get_text2sql_query_engine(llm, table_context, sql_database): text2sql_tmpl_str = _generate_prompt_sql( "{query_str}", "{schema}", dialect="{dialect}", output="" ) sql_prompt =
PromptTemplate(text2sql_tmpl_str)
llama_index.core.PromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-callbacks-aim') get_ipython().system('pip install llama-index') from llama_index.core.callbacks import CallbackManager from llama_index.callbacks.aim import AimCallback from llama_index.core import SummaryIndex from llama_index.core import 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'") docs = SimpleDirectoryReader("./data/paul_graham").load_data() aim_callback = AimCallback(repo="./") callback_manager = CallbackManager([aim_callback]) index =
SummaryIndex.from_documents(docs, callback_manager=callback_manager)
llama_index.core.SummaryIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.llms.openai import OpenAI resp = OpenAI().complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.openai import OpenAI messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="What is your name"), ] resp = OpenAI().chat(messages) print(resp) from llama_index.llms.openai import OpenAI llm = OpenAI() resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI from llama_index.core.llms import ChatMessage llm = OpenAI() messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="What is your name"), ] resp = llm.stream_chat(messages) for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI llm =
OpenAI(model="text-davinci-003")
llama_index.llms.openai.OpenAI
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/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') 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 weaviate resource_owner_config = weaviate.AuthClientPassword( username="<username>", password="<password>", ) client = weaviate.Client("http://localhost:8080") from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core.response.notebook_utils import display_response 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 = WeaviateVectorStore(weaviate_client=client) storage_context =
StorageContext.from_defaults(vector_store=vector_store)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().system('pip install llama-index') import weaviate client = weaviate.Client("https://test-cluster-bbn8vqsn.weaviate.network") try: client.schema.delete_class("Book") except: pass schema = { "classes": [ { "class": "Book", "properties": [ {"name": "title", "dataType": ["text"]}, {"name": "author", "dataType": ["text"]}, {"name": "content", "dataType": ["text"]}, {"name": "year", "dataType": ["int"]}, ], }, ] } if not client.schema.contains(schema): client.schema.create(schema) 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, }, ] from llama_index.embeddings.openai import OpenAIEmbedding embed_model = OpenAIEmbedding() with client.batch as batch: for book in books: vector = embed_model.get_text_embedding(book["content"]) batch.add_data_object( data_object=book, class_name="Book", vector=vector ) from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core import VectorStoreIndex from llama_index.core.response.pprint_utils import pprint_source_node vector_store = WeaviateVectorStore( weaviate_client=client, index_name="Book", text_key="content" ) retriever = VectorStoreIndex.from_vector_store(vector_store).as_retriever( similarity_top_k=1 ) nodes = retriever.retrieve("What is that book about a bird again?")
pprint_source_node(nodes[0])
llama_index.core.response.pprint_utils.pprint_source_node
get_ipython().system('pip install llama-index') 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 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.core.indices.query.query_transform import HyDEQueryTransform from llama_index.core.query_engine import TransformQueryEngine from IPython.display import Markdown, display documents =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-together') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') domain = "docs.llamaindex.ai" docs_url = "https://docs.llamaindex.ai/en/latest/" get_ipython().system('wget -e robots=off --recursive --no-clobber --page-requisites --html-extension --convert-links --restrict-file-names=windows --domains {domain} --no-parent {docs_url}') from llama_index.readers.file import UnstructuredReader from pathlib import Path from llama_index.llms.openai import OpenAI from llama_index.core import Document reader = UnstructuredReader() all_html_files = [ "docs.llamaindex.ai/en/latest/index.html", "docs.llamaindex.ai/en/latest/contributing/contributing.html", "docs.llamaindex.ai/en/latest/understanding/understanding.html", "docs.llamaindex.ai/en/latest/understanding/using_llms/using_llms.html", "docs.llamaindex.ai/en/latest/understanding/using_llms/privacy.html", "docs.llamaindex.ai/en/latest/understanding/loading/llamahub.html", "docs.llamaindex.ai/en/latest/optimizing/production_rag.html", "docs.llamaindex.ai/en/latest/module_guides/models/llms.html", ] doc_limit = 10 docs = [] for idx, f in enumerate(all_html_files): if idx > doc_limit: break print(f"Idx {idx}/{len(all_html_files)}") loaded_docs = reader.load_data(file=f, split_documents=True) start_idx = 64 loaded_doc = Document( id_=str(f), text="\n\n".join([d.get_content() for d in loaded_docs[start_idx:]]), metadata={"path": str(f)}, ) print(str(f)) docs.append(loaded_doc) from llama_index.embeddings.together import TogetherEmbedding from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI api_key = "<api_key>" embed_model = TogetherEmbedding( model_name="togethercomputer/m2-bert-80M-32k-retrieval", api_key=api_key ) llm = OpenAI(temperature=0, model="gpt-3.5-turbo") from llama_index.core.storage.docstore import SimpleDocumentStore for doc in docs: embedding = embed_model.get_text_embedding(doc.get_content()) doc.embedding = embedding docstore = SimpleDocumentStore() docstore.add_documents(docs) from llama_index.core.schema import IndexNode from llama_index.core import ( load_index_from_storage, StorageContext, VectorStoreIndex, ) from llama_index.core.node_parser import SentenceSplitter from llama_index.core import SummaryIndex from llama_index.core.retrievers import RecursiveRetriever import os from tqdm.notebook import tqdm import pickle def build_index(docs, out_path: str = "storage/chunk_index"): nodes = [] splitter = SentenceSplitter(chunk_size=512, chunk_overlap=70) for idx, doc in enumerate(tqdm(docs)): cur_nodes = splitter.get_nodes_from_documents([doc]) for cur_node in cur_nodes: file_path = doc.metadata["path"] new_node = IndexNode( text=cur_node.text or "None", index_id=str(file_path), metadata=doc.metadata ) nodes.append(new_node) print("num nodes: " + str(len(nodes))) if not os.path.exists(out_path): index =
VectorStoreIndex(nodes, embed_model=embed_model)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-lantern') get_ipython().system('pip install llama-index psycopg2-binary asyncpg') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import os os.environ["OPENAI_API_KEY"] = "<your-api-key>" import openai openai.api_key = os.environ["OPENAI_API_KEY"] import psycopg2 from sqlalchemy import make_url connection_string = "postgresql://postgres:postgres@localhost:5432" url = make_url(connection_string) db_name = "postgres" conn = psycopg2.connect(connection_string) conn.autocommit = True from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.lantern import LanternVectorStore 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 = LanternVectorStore.from_params( database=db_name, host=url.host, password=url.password, port=url.port, user=url.username, table_name="famous_people", embed_dim=1536, # openai embedding dimension m=16, # HNSW M parameter ef_construction=128, # HNSW ef construction parameter ef=64, # HNSW ef search parameter ) storage_context =
StorageContext.from_defaults(vector_store=vector_store)
llama_index.core.StorageContext.from_defaults