prompt
stringlengths
70
19.8k
completion
stringlengths
8
1.03k
api
stringlengths
23
93
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)
llama_index.core.agent.react.types.ObservationReasoningStep
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west4-gcp-free") import os import getpass import openai openai.api_key = "sk-<your-key>" try: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", "gender": "male", "born": 1963, }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", "gender": "female", "born": 1975, }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", "gender": "male", "born": 1971, }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", "gender": "female", "born": 1988, }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", "gender": "male", "born": 1985, }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, MetadataFilter, MetadataFilters, FilterCondition, FilterOperator, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), MetadataInfo( name="gender", type="str", description=("Gender of the celebrity, one of [male, female]"), ), MetadataInfo( name="born", type="int", description=("Born year of the celebrity, could be any integer"), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[Any] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) filter_operator_list: List[str] = Field( ..., description=( "Metadata filters conditions (could be one of <, <=, >, >=, ==, !=)" ), ) filter_condition: str = Field( ..., description=("Metadata filters condition values (could be AND or OR)"), ) description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[any], filter_operator_list: List[str], filter_condition: str, ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" metadata_filters = [ MetadataFilter(key=k, value=v, operator=op) for k, v, op in zip( filter_key_list, filter_value_list, filter_operator_list ) ] retriever = VectorIndexRetriever( index, filters=MetadataFilters( filters=metadata_filters, condition=filter_condition ), top_k=top_k, ) query_engine = RetrieverQueryEngine.from_args(retriever) response = query_engine.query(query) return str(response) auto_retrieve_tool = FunctionTool.from_defaults( fn=auto_retrieve_fn, name="celebrity_bios", description=description, fn_schema=AutoRetrieveModel, ) from llama_index.agent.openai import OpenAIAgent from llama_index.llms.openai import OpenAI agent = OpenAIAgent.from_tools( [auto_retrieve_tool], llm=OpenAI(temperature=0, model="gpt-4-0613"), verbose=True, ) response = agent.chat("Tell me about two celebrities from the United States. ") print(str(response)) response = agent.chat("Tell me about two celebrities born after 1980. ") print(str(response)) response = agent.chat( "Tell me about few celebrities under category business and born after 1950. " ) print(str(response)) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase from llama_index.core.indices import SQLStructStoreIndex engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) sql_database =
SQLDatabase(engine, include_tables=["city_stats"])
llama_index.core.SQLDatabase
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') 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 from llama_index.core import PromptTemplate from IPython.display import Markdown, display 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.llms.openai import OpenAI gpt35_llm = OpenAI(model="gpt-3.5-turbo") gpt4_llm = OpenAI(model="gpt-4") index = VectorStoreIndex.from_documents(documents) query_str = "What are the potential risks associated with the use of Llama 2 as mentioned in the context?" query_engine = index.as_query_engine(similarity_top_k=2, llm=gpt35_llm) vector_retriever = index.as_retriever(similarity_top_k=2) response = query_engine.query(query_str) print(str(response)) 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) from langchain import hub langchain_prompt = hub.pull("rlm/rag-prompt") from llama_index.core.prompts import LangchainPromptTemplate lc_prompt_tmpl = LangchainPromptTemplate( template=langchain_prompt, template_var_mappings={"query_str": "question", "context_str": "context"}, ) query_engine.update_prompts( {"response_synthesizer:text_qa_template": lc_prompt_tmpl} ) prompts_dict = query_engine.get_prompts() display_prompt_dict(prompts_dict) response = query_engine.query(query_str) print(str(response)) from llama_index.core.schema import TextNode few_shot_nodes = [] for line in open("../llama2_qa_citation_events.jsonl", "r"): few_shot_nodes.append(
TextNode(text=line)
llama_index.core.schema.TextNode
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-retrievers-bm25') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() 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().handlers = [] logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( SimpleDirectoryReader, StorageContext, VectorStoreIndex, ) from llama_index.retrievers.bm25 import BM25Retriever from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.node_parser import SentenceSplitter from llama_index.llms.openai import 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'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() llm =
OpenAI(model="gpt-4")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings from llama_index.core import StorageContext, VectorStoreIndex from llama_index.core import SummaryIndex Settings.llm = OpenAI() Settings.chunk_size = 1024 nodes = Settings.node_parser.get_nodes_from_documents(documents) storage_context = StorageContext.from_defaults() storage_context.docstore.add_documents(nodes) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) summary_query_engine = summary_index.as_query_engine( response_mode="tree_summarize", use_async=True, ) vector_query_engine = vector_index.as_query_engine() from llama_index.core.tools import QueryEngineTool summary_tool = QueryEngineTool.from_defaults( query_engine=summary_query_engine, name="summary_tool", description=( "Useful for summarization questions related to the author's life" ), ) vector_tool = QueryEngineTool.from_defaults( query_engine=vector_query_engine, name="vector_tool", description=( "Useful for retrieving specific context to answer specific questions about the author's life" ), ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="QA bot", instructions="You are a bot designed to answer questions about the author", openai_tools=[], tools=[summary_tool, vector_tool], verbose=True, run_retrieve_sleep_time=1.0, ) response = agent.chat("Can you give me a summary about the author's life?") print(str(response)) response = agent.query("What did the author do after RICS?") print(str(response)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") try: pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [ TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." ), metadata={ "category": "Sports", "country": "United States", }, ), TextNode( text=( "Angelina Jolie is an American actress, filmmaker, and" " humanitarian. She has received numerous awards for her acting" " and is known for her philanthropic work." ), metadata={ "category": "Entertainment", "country": "United States", }, ), TextNode( text=( "Elon Musk is a business magnate, industrial designer, and" " engineer. He is the founder, CEO, and lead designer of SpaceX," " Tesla, Inc., Neuralink, and The Boring Company." ), metadata={ "category": "Business", "country": "United States", }, ), TextNode( text=( "Rihanna is a Barbadian singer, actress, and businesswoman. She" " has achieved significant success in the music industry and is" " known for her versatile musical style." ), metadata={ "category": "Music", "country": "Barbados", }, ), TextNode( text=( "Cristiano Ronaldo is a Portuguese professional footballer who is" " considered one of the greatest football players of all time. He" " has won numerous awards and set multiple records during his" " career." ), metadata={ "category": "Sports", "country": "Portugal", }, ), ] vector_store = PineconeVectorStore( pinecone_index=pinecone_index, namespace="test" ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes, storage_context=storage_context) from llama_index.core.tools import FunctionTool from llama_index.core.vector_stores import ( VectorStoreInfo, MetadataInfo, ExactMatchFilter, MetadataFilters, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from typing import List, Tuple, Any from pydantic import BaseModel, Field top_k = 3 vector_store_info = VectorStoreInfo( content_info="brief biography of celebrities", metadata_info=[ MetadataInfo( name="category", type="str", description=( "Category of the celebrity, one of [Sports, Entertainment," " Business, Music]" ), ), MetadataInfo( name="country", type="str", description=( "Country of the celebrity, one of [United States, Barbados," " Portugal]" ), ), ], ) class AutoRetrieveModel(BaseModel): query: str = Field(..., description="natural language query string") filter_key_list: List[str] = Field( ..., description="List of metadata filter field names" ) filter_value_list: List[str] = Field( ..., description=( "List of metadata filter field values (corresponding to names" " specified in filter_key_list)" ), ) def auto_retrieve_fn( query: str, filter_key_list: List[str], filter_value_list: List[str] ): """Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. """ query = query or "Query" exact_match_filters = [ ExactMatchFilter(key=k, value=v) for k, v in zip(filter_key_list, filter_value_list) ] retriever = VectorIndexRetriever( index, filters=MetadataFilters(filters=exact_match_filters), top_k=top_k, ) results = retriever.retrieve(query) return [r.get_content() for r in results] description = f"""\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} """ auto_retrieve_tool = FunctionTool.from_defaults( fn=auto_retrieve_fn, name="celebrity_bios", description=description, fn_schema=AutoRetrieveModel, ) auto_retrieve_fn( "celebrity from the United States", filter_key_list=["country"], filter_value_list=["United States"], ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="Celebrity bot", instructions="You are a bot designed to answer questions about celebrities.", tools=[auto_retrieve_tool], verbose=True, ) response = agent.chat("Tell me about two celebrities from the United States. ") print(str(response)) from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase from llama_index.core.indices import SQLStructStoreIndex engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from llama_index.core.query_engine import NLSQLTableQueryEngine query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], ) get_ipython().system('pip install wikipedia') from llama_index.readers.wikipedia import WikipediaReader from llama_index.core import SimpleDirectoryReader, VectorStoreIndex cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) from llama_index.core import Settings from llama_index.core import StorageContext from llama_index.core.node_parser import TokenTextSplitter from llama_index.llms.openai import OpenAI Settings.chunk_size = 1024 Settings.llm = OpenAI(temperature=0, model="gpt-4") text_splitter =
TokenTextSplitter(chunk_size=1024)
llama_index.core.node_parser.TokenTextSplitter
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)] from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode node_parser = SentenceSplitter(chunk_size=1024) base_nodes = node_parser.get_nodes_from_documents(docs) for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}" from llama_index.core.embeddings import resolve_embed_model embed_model = resolve_embed_model("local:BAAI/bge-small-en") llm = OpenAI(model="gpt-3.5-turbo") base_index = VectorStoreIndex(base_nodes, embed_model=embed_model) base_retriever = base_index.as_retriever(similarity_top_k=2) retrievals = base_retriever.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for n in retrievals: display_source_node(n, source_length=1500) query_engine_base = RetrieverQueryEngine.from_args(base_retriever, llm=llm) response = query_engine_base.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [SentenceSplitter(chunk_size=c) for c in sub_chunk_sizes] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) original_node =
IndexNode.from_text_node(base_node, base_node.node_id)
llama_index.core.schema.IndexNode.from_text_node
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import os os.environ["OPENAI_API_KEY"] = "sk-..." import tiktoken from llama_index.core.callbacks import CallbackManager, TokenCountingHandler from llama_index.llms.openai import OpenAI from llama_index.core import Settings token_counter = TokenCountingHandler( tokenizer=tiktoken.encoding_for_model("gpt-3.5-turbo").encode ) Settings.llm =
OpenAI(model="gpt-3.5-turbo", temperature=0.2)
llama_index.llms.openai.OpenAI
get_ipython().system('pip install llama-index') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.postprocessor import ( PrevNextNodePostprocessor, AutoPrevNextNodePostprocessor, ) from llama_index.core.node_parser import SentenceSplitter from llama_index.core.storage.docstore import SimpleDocumentStore 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 StorageContext documents = SimpleDirectoryReader("./data/paul_graham").load_data() from llama_index.core import Settings Settings.chunk_size = 512 nodes = Settings.node_parser.get_nodes_from_documents(documents) docstore =
SimpleDocumentStore()
llama_index.core.storage.docstore.SimpleDocumentStore
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)
llama_index.core.ChatPromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().system('pip install llama-index') import os import pinecone api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="eu-west1-gcp") indexes = pinecone.list_indexes() print(indexes) if "quickstart-index" not in indexes: pinecone.create_index( "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1" ) pinecone_index = pinecone.Index("quickstart-index") pinecone_index.delete(deleteAll="true") books = [ { "title": "To Kill a Mockingbird", "author": "Harper Lee", "content": ( "To Kill a Mockingbird is a novel by Harper Lee published in" " 1960..." ), "year": 1960, }, { "title": "1984", "author": "George Orwell", "content": ( "1984 is a dystopian novel by George Orwell published in 1949..." ), "year": 1949, }, { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "content": ( "The Great Gatsby is a novel by F. Scott Fitzgerald published in" " 1925..." ), "year": 1925, }, { "title": "Pride and Prejudice", "author": "Jane Austen", "content": ( "Pride and Prejudice is a novel by Jane Austen published in" " 1813..." ), "year": 1813, }, ] import uuid from llama_index.embeddings.openai import OpenAIEmbedding embed_model =
OpenAIEmbedding()
llama_index.embeddings.openai.OpenAIEmbedding
get_ipython().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)] from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode node_parser = SentenceSplitter(chunk_size=1024) base_nodes = node_parser.get_nodes_from_documents(docs) for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}" from llama_index.core.embeddings import resolve_embed_model embed_model = resolve_embed_model("local:BAAI/bge-small-en") llm = OpenAI(model="gpt-3.5-turbo") base_index = VectorStoreIndex(base_nodes, embed_model=embed_model) base_retriever = base_index.as_retriever(similarity_top_k=2) retrievals = base_retriever.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for n in retrievals: display_source_node(n, source_length=1500) query_engine_base = RetrieverQueryEngine.from_args(base_retriever, llm=llm) response = query_engine_base.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [SentenceSplitter(chunk_size=c) for c in sub_chunk_sizes] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) original_node = IndexNode.from_text_node(base_node, base_node.node_id) all_nodes.append(original_node) all_nodes_dict = {n.node_id: n for n in all_nodes} vector_index_chunk = VectorStoreIndex(all_nodes, embed_model=embed_model) vector_retriever_chunk = vector_index_chunk.as_retriever(similarity_top_k=2) retriever_chunk = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever_chunk}, node_dict=all_nodes_dict, verbose=True, ) nodes = retriever_chunk.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for node in nodes:
display_source_node(node, source_length=2000)
llama_index.core.response.notebook_utils.display_source_node
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()
llama_index.core.callbacks.CallbackManager
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.core.agent import ( CustomSimpleAgentWorker, Task, AgentChatResponse, ) from typing import Dict, Any, List, Tuple, Optional from llama_index.core.tools import BaseTool, QueryEngineTool from llama_index.core.program import LLMTextCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser from llama_index.core.query_engine import RouterQueryEngine from llama_index.core import ChatPromptTemplate, PromptTemplate from llama_index.core.selectors import PydanticSingleSelector from llama_index.core.bridge.pydantic import Field, BaseModel from llama_index.core.llms import ChatMessage, MessageRole DEFAULT_PROMPT_STR = """ Given previous question/response pairs, please determine if an error has occurred in the response, and suggest \ a modified question that will not trigger the error. Examples of modified questions: - The question itself is modified to elicit a non-erroneous response - The question is augmented with context that will help the downstream system better answer the question. - The question is augmented with examples of negative responses, or other negative questions. An error means that either an exception has triggered, or the response is completely irrelevant to the question. Please return the evaluation of the response in the following JSON format. """ def get_chat_prompt_template( system_prompt: str, current_reasoning: Tuple[str, str] ) -> ChatPromptTemplate: system_msg = ChatMessage(role=MessageRole.SYSTEM, content=system_prompt) messages = [system_msg] for raw_msg in current_reasoning: if raw_msg[0] == "user": messages.append( ChatMessage(role=MessageRole.USER, content=raw_msg[1]) ) else: messages.append( ChatMessage(role=MessageRole.ASSISTANT, content=raw_msg[1]) ) return ChatPromptTemplate(message_templates=messages) class ResponseEval(BaseModel): """Evaluation of whether the response has an error.""" has_error: bool = Field( ..., description="Whether the response has an error." ) new_question: str = Field(..., description="The suggested new question.") explanation: str = Field( ..., description=( "The explanation for the error as well as for the new question." "Can include the direct stack trace as well." ), ) from llama_index.core.bridge.pydantic import PrivateAttr class RetryAgentWorker(CustomSimpleAgentWorker): """Agent worker that adds a retry layer on top of a router. Continues iterating until there's no errors / task is done. """ prompt_str: str = Field(default=DEFAULT_PROMPT_STR) max_iterations: int = Field(default=10) _router_query_engine: RouterQueryEngine = PrivateAttr() def __init__(self, tools: List[BaseTool], **kwargs: Any) -> None: """Init params.""" for tool in tools: if not isinstance(tool, QueryEngineTool): raise ValueError( f"Tool {tool.metadata.name} is not a query engine tool." ) self._router_query_engine = RouterQueryEngine( selector=PydanticSingleSelector.from_defaults(), query_engine_tools=tools, verbose=kwargs.get("verbose", False), ) super().__init__( tools=tools, **kwargs, ) def _initialize_state(self, task: Task, **kwargs: Any) -> Dict[str, Any]: """Initialize state.""" return {"count": 0, "current_reasoning": []} def _run_step( self, state: Dict[str, Any], task: Task, input: Optional[str] = None ) -> Tuple[AgentChatResponse, bool]: """Run step. Returns: Tuple of (agent_response, is_done) """ if "new_input" not in state: new_input = task.input else: new_input = state["new_input"] response = self._router_query_engine.query(new_input) state["current_reasoning"].extend( [("user", new_input), ("assistant", str(response))] ) chat_prompt_tmpl = get_chat_prompt_template( self.prompt_str, state["current_reasoning"] ) llm_program = LLMTextCompletionProgram.from_defaults( output_parser=PydanticOutputParser(output_cls=ResponseEval), prompt=chat_prompt_tmpl, llm=self.llm, ) response_eval = llm_program( query_str=new_input, response_str=str(response) ) if not response_eval.has_error: is_done = True else: is_done = False state["new_input"] = response_eval.new_question if self.verbose: print(f"> Question: {new_input}") print(f"> Response: {response}") print(f"> Response eval: {response_eval.dict()}") return AgentChatResponse(response=str(response)), is_done def _finalize_task(self, state: Dict[str, Any], **kwargs) -> None: """Finalize task.""" pass from llama_index.core.tools import QueryEngineTool from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) from llama_index.core import SQLDatabase 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) 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) from llama_index.core.query_engine import NLSQLTableQueryEngine sql_database = SQLDatabase(engine, include_tables=["city_stats"]) sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], verbose=True ) sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, description=( "Useful for translating a natural language query into a SQL query over" " a table containing: city_stats, containing the population/country of" " each city" ), ) from llama_index.readers.wikipedia import WikipediaReader from llama_index.core import VectorStoreIndex cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) vector_tools = [] for city, wiki_doc in zip(cities, wiki_docs): vector_index =
VectorStoreIndex.from_documents([wiki_doc])
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-postprocessor-flag-embedding-reranker') get_ipython().system('pip install llama-index') get_ipython().system('pip install git+https://github.com/FlagOpen/FlagEmbedding.git') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") import os OPENAI_API_TOKEN = "sk-" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN documents =
SimpleDirectoryReader("./data/paul_graham")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.core.evaluation.benchmarks import HotpotQAEvaluator from llama_index.core import VectorStoreIndex from llama_index.core import Document from llama_index.llms.openai import OpenAI from llama_index.core.embeddings import resolve_embed_model llm = OpenAI(model="gpt-3.5-turbo") embed_model = resolve_embed_model( "local:sentence-transformers/all-MiniLM-L6-v2" ) index = VectorStoreIndex.from_documents( [Document.example()], embed_model=embed_model, show_progress=True ) engine = index.as_query_engine(llm=llm) HotpotQAEvaluator().run(engine, queries=5, show_result=True) from llama_index.core.postprocessor import SentenceTransformerRerank rerank =
SentenceTransformerRerank(top_n=3)
llama_index.core.postprocessor.SentenceTransformerRerank
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') from pydantic import BaseModel from unstructured.partition.html import partition_html import pandas as pd pd.set_option("display.max_rows", None) pd.set_option("display.max_columns", None) pd.set_option("display.width", None) pd.set_option("display.max_colwidth", None) get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://www.dropbox.com/scl/fi/rkw0u959yb4w8vlzz76sa/tesla_2020_10k.htm?rlkey=tfkdshswpoupav5tqigwz1mp7&dl=1" -O tesla_2020_10k.htm') from llama_index.readers.file import FlatReader from pathlib import Path reader = FlatReader() docs_2021 = reader.load_data(Path("tesla_2021_10k.htm")) docs_2020 = reader.load_data(Path("tesla_2020_10k.htm")) from llama_index.core.node_parser import UnstructuredElementNodeParser node_parser = UnstructuredElementNodeParser() import os import pickle if not os.path.exists("2021_nodes.pkl"): raw_nodes_2021 = node_parser.get_nodes_from_documents(docs_2021) pickle.dump(raw_nodes_2021, open("2021_nodes.pkl", "wb")) else: raw_nodes_2021 = pickle.load(open("2021_nodes.pkl", "rb")) base_nodes_2021, node_mappings_2021 = node_parser.get_base_nodes_and_mappings( raw_nodes_2021 ) example_index_node = [b for b in base_nodes_2021 if isinstance(b, IndexNode)][ 20 ] print( f"\n--------\n{example_index_node.get_content(metadata_mode='all')}\n--------\n" ) print(f"\n--------\nIndex ID: {example_index_node.index_id}\n--------\n") print( f"\n--------\n{node_mappings_2021[example_index_node.index_id].get_content()}\n--------\n" ) from llama_index.core.retrievers import RecursiveRetriever from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core import VectorStoreIndex vector_index = VectorStoreIndex(base_nodes_2021) vector_retriever = vector_index.as_retriever(similarity_top_k=1) vector_query_engine = vector_index.as_query_engine(similarity_top_k=1) from llama_index.core.retrievers import RecursiveRetriever recursive_retriever = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever}, node_dict=node_mappings_2021, verbose=True, ) query_engine = RetrieverQueryEngine.from_args(recursive_retriever) response = query_engine.query("What was the revenue in 2020?") print(str(response)) response = vector_query_engine.query("What was the revenue in 2020?") print(str(response)) response = query_engine.query("What were the total cash flows in 2021?") print(str(response)) response = vector_query_engine.query("What were the total cash flows in 2021?") print(str(response)) response = query_engine.query("What are the risk factors for Tesla?") print(str(response)) response = vector_query_engine.query("What are the risk factors for Tesla?") print(str(response)) import pickle import os def create_recursive_retriever_over_doc(docs, nodes_save_path=None): """Big function to go from document path -> recursive retriever.""" node_parser = UnstructuredElementNodeParser() if nodes_save_path is not None and os.path.exists(nodes_save_path): raw_nodes = pickle.load(open(nodes_save_path, "rb")) else: raw_nodes = node_parser.get_nodes_from_documents(docs) if nodes_save_path is not None: pickle.dump(raw_nodes, open(nodes_save_path, "wb")) base_nodes, node_mappings = node_parser.get_base_nodes_and_mappings( raw_nodes ) vector_index = VectorStoreIndex(base_nodes) vector_retriever = vector_index.as_retriever(similarity_top_k=2) recursive_retriever = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever}, node_dict=node_mappings, verbose=True, ) query_engine = RetrieverQueryEngine.from_args(recursive_retriever) return query_engine, base_nodes import nest_asyncio nest_asyncio.apply() from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core.query_engine import SubQuestionQueryEngine from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-4") query_engine_2021, nodes_2021 = create_recursive_retriever_over_doc( docs_2021, nodes_save_path="2021_nodes.pkl" ) query_engine_2020, nodes_2020 = create_recursive_retriever_over_doc( docs_2020, nodes_save_path="2020_nodes.pkl" ) query_engine_tools = [ QueryEngineTool( query_engine=query_engine_2021, metadata=ToolMetadata( name="tesla_2021_10k", description=( "Provides information about Tesla financials for year 2021" ), ), ), QueryEngineTool( query_engine=query_engine_2020, metadata=ToolMetadata( name="tesla_2020_10k", description=( "Provides information about Tesla financials for year 2020" ), ), ), ] sub_query_engine = SubQuestionQueryEngine.from_defaults( query_engine_tools=query_engine_tools, llm=llm, use_async=True, ) response = sub_query_engine.query( "Can you compare and contrast the cash flow in 2021 with 2020?" ) print(str(response)) response = sub_query_engine.query( "Can you compare and contrast the R&D expenditures in 2021 vs. 2020?" ) print(str(response)) response = sub_query_engine.query( "Can you compare and contrast the risk factors in 2021 vs. 2020?" ) print(str(response)) vector_index_2021 =
VectorStoreIndex(nodes_2021)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-cohere') get_ipython().system('pip install llama-index') from llama_index.llms.cohere import Cohere api_key = "Your api key" resp = Cohere(api_key=api_key).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.cohere import Cohere messages = [ ChatMessage(role="user", content="hello there"), ChatMessage( role="assistant", content="Arrrr, matey! How can I help ye today?" ), ChatMessage(role="user", content="What is your name"), ] resp = Cohere(api_key=api_key).chat( messages, preamble_override="You are a pirate with a colorful personality" ) print(resp) from llama_index.llms.openai import OpenAI llm = Cohere(api_key=api_key) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI llm = Cohere(api_key=api_key) messages = [ ChatMessage(role="user", content="hello there"), ChatMessage( role="assistant", content="Arrrr, matey! How can I help ye today?" ),
ChatMessage(role="user", content="What is your name")
llama_index.core.llms.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-readers-elasticsearch') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-opensearch') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-ollama') 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 os import getenv from llama_index.core import SimpleDirectoryReader from llama_index.vector_stores.opensearch import ( OpensearchVectorStore, OpensearchVectorClient, ) from llama_index.core import VectorStoreIndex, StorageContext endpoint = getenv("OPENSEARCH_ENDPOINT", "http://localhost:9200") idx = getenv("OPENSEARCH_INDEX", "gpt-index-demo") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() text_field = "content" embedding_field = "embedding" client = OpensearchVectorClient( endpoint, idx, 1536, embedding_field=embedding_field, text_field=text_field ) vector_store = OpensearchVectorStore(client) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents=documents, storage_context=storage_context ) query_engine = index.as_query_engine() res = query_engine.query("What did the author do growing up?") res.response from llama_index.core import Document from llama_index.core.vector_stores import MetadataFilters, ExactMatchFilter import regex as re text_chunks = documents[0].text.split("\n\n") footnotes = [ Document( text=chunk, id=documents[0].doc_id, metadata={"is_footnote": bool(re.search(r"^\s*\[\d+\]\s*", chunk))}, ) for chunk in text_chunks if bool(re.search(r"^\s*\[\d+\]\s*", chunk)) ] for f in footnotes: index.insert(f) footnote_query_engine = index.as_query_engine( filters=MetadataFilters( filters=[ ExactMatchFilter( key="term", value='{"metadata.is_footnote": "true"}' ), ExactMatchFilter( key="query_string", value='{"query": "content: space AND content: lisp"}', ), ] ) ) res = footnote_query_engine.query( "What did the author about space aliens and lisp?" ) res.response from llama_index.readers.elasticsearch import ElasticsearchReader rdr =
ElasticsearchReader(endpoint, idx)
llama_index.readers.elasticsearch.ElasticsearchReader
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import VectorStoreIndex, SQLDatabase from llama_index.readers.wikipedia import WikipediaReader from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) engine = create_engine("sqlite:///:memory:", future=True) metadata_obj = MetaData() table_name = "city_stats" city_stats_table = Table( table_name, metadata_obj, Column("city_name", String(16), primary_key=True), Column("population", Integer), Column("country", String(16), nullable=False), ) metadata_obj.create_all(engine) metadata_obj.tables.keys() from sqlalchemy import insert rows = [ {"city_name": "Toronto", "population": 2930000, "country": "Canada"}, {"city_name": "Tokyo", "population": 13960000, "country": "Japan"}, {"city_name": "Berlin", "population": 3645000, "country": "Germany"}, ] for row in rows: stmt = insert(city_stats_table).values(**row) with engine.begin() as connection: cursor = connection.execute(stmt) with engine.connect() as connection: cursor = connection.exec_driver_sql("SELECT * FROM city_stats") print(cursor.fetchall()) get_ipython().system('pip install wikipedia') cities = ["Toronto", "Berlin", "Tokyo"] wiki_docs = WikipediaReader().load_data(pages=cities) sql_database = SQLDatabase(engine, include_tables=["city_stats"]) from llama_index.core.query_engine import NLSQLTableQueryEngine sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["city_stats"], ) vector_indices = [] for wiki_doc in wiki_docs: vector_index = VectorStoreIndex.from_documents([wiki_doc]) vector_indices.append(vector_index) vector_query_engines = [index.as_query_engine() for index in vector_indices] from llama_index.core.tools import QueryEngineTool sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, description=( "Useful for translating a natural language query into a SQL query over" " a table containing: city_stats, containing the population/country of" " each city" ), ) vector_tools = [] for city, query_engine in zip(cities, vector_query_engines): vector_tool = QueryEngineTool.from_defaults( query_engine=query_engine, description=f"Useful for answering semantic questions about {city}", ) vector_tools.append(vector_tool) from llama_index.core.query_engine import RouterQueryEngine from llama_index.core.selectors import LLMSingleSelector query_engine = RouterQueryEngine( selector=
LLMSingleSelector.from_defaults()
llama_index.core.selectors.LLMSingleSelector.from_defaults
import openai openai.api_key = "sk-your-key" from llama_index.agent import OpenAIAgent from llama_index.tools.text_to_image.base import TextToImageToolSpec text_to_image_spec = TextToImageToolSpec() tools = text_to_image_spec.to_tool_list() agent =
OpenAIAgent.from_tools(tools, verbose=True)
llama_index.agent.OpenAIAgent.from_tools
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') get_ipython().system('pip install jsonpath-ng') 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" from IPython.display import Markdown, display json_value = { "blogPosts": [ { "id": 1, "title": "First blog post", "content": "This is my first blog post", }, { "id": 2, "title": "Second blog post", "content": "This is my second blog post", }, ], "comments": [ { "id": 1, "content": "Nice post!", "username": "jerry", "blogPostId": 1, }, { "id": 2, "content": "Interesting thoughts", "username": "simon", "blogPostId": 2, }, { "id": 3, "content": "Loved reading this!", "username": "simon", "blogPostId": 2, }, ], } json_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Schema for a very simple blog post app", "type": "object", "properties": { "blogPosts": { "description": "List of blog posts", "type": "array", "items": { "type": "object", "properties": { "id": { "description": "Unique identifier for the blog post", "type": "integer", }, "title": { "description": "Title of the blog post", "type": "string", }, "content": { "description": "Content of the blog post", "type": "string", }, }, "required": ["id", "title", "content"], }, }, "comments": { "description": "List of comments on blog posts", "type": "array", "items": { "type": "object", "properties": { "id": { "description": "Unique identifier for the comment", "type": "integer", }, "content": { "description": "Content of the comment", "type": "string", }, "username": { "description": ( "Username of the commenter (lowercased)" ), "type": "string", }, "blogPostId": { "description": ( "Identifier for the blog post to which the comment" " belongs" ), "type": "integer", }, }, "required": ["id", "content", "username", "blogPostId"], }, }, }, "required": ["blogPosts", "comments"], } from llama_index.llms.openai import OpenAI from llama_index.core.indices.struct_store import JSONQueryEngine llm =
OpenAI(model="gpt-4")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.agent.openai import OpenAIAgent from llama_index.llms.openai import OpenAI from llama_index.core.tools import BaseTool, FunctionTool def multiply(a: int, b: int) -> int: """Multiple two integers and returns the result integer""" return a * b multiply_tool = FunctionTool.from_defaults(fn=multiply) def add(a: int, b: int) -> int: """Add two integers and returns the result integer""" return a + b add_tool = FunctionTool.from_defaults(fn=add) llm = OpenAI(model="gpt-3.5-turbo-1106") agent = OpenAIAgent.from_tools( [multiply_tool, add_tool], llm=llm, verbose=True ) response = agent.chat("What is (121 * 3) + 42?") print(str(response)) response = agent.stream_chat("What is (121 * 3) + 42?") import nest_asyncio nest_asyncio.apply() response = await agent.achat("What is (121 * 3) + 42?") print(str(response)) response = await agent.astream_chat("What is (121 * 3) + 42?") response_gen = response.response_gen async for token in response.async_response_gen(): print(token, end="") import json def get_current_weather(location, unit="fahrenheit"): """Get the current weather in a given location""" if "tokyo" in location.lower(): return json.dumps( {"location": location, "temperature": "10", "unit": "celsius"} ) elif "san francisco" in location.lower(): return json.dumps( {"location": location, "temperature": "72", "unit": "fahrenheit"} ) else: return json.dumps( {"location": location, "temperature": "22", "unit": "celsius"} ) weather_tool = FunctionTool.from_defaults(fn=get_current_weather) llm =
OpenAI(model="gpt-3.5-turbo-1106")
llama_index.llms.openai.OpenAI
get_ipython().system('pip install llama-index') get_ipython().system('pip install duckdb') get_ipython().system('pip install llama-index-vector-stores-duckdb') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.duckdb import DuckDBVectorStore from llama_index.core import StorageContext from IPython.display import Markdown, display import os import openai 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'") documents = SimpleDirectoryReader("data/paul_graham/").load_data() vector_store = DuckDBVectorStore() 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>")) documents = SimpleDirectoryReader("data/paul_graham/").load_data() vector_store =
DuckDBVectorStore("pg.duckdb", persist_dir="./persist/")
llama_index.vector_stores.duckdb.DuckDBVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-gradient') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-gradient') get_ipython().run_line_magic('pip', 'install llama-index --quiet') get_ipython().run_line_magic('pip', 'install gradientai --quiet') import os os.environ["GRADIENT_ACCESS_TOKEN"] = "{GRADIENT_ACCESS_TOKEN}" os.environ["GRADIENT_WORKSPACE_ID"] = "{GRADIENT_WORKSPACE_ID}" from llama_index.llms.gradient import GradientBaseModelLLM llm = GradientBaseModelLLM( base_model_slug="llama2-7b-chat", max_tokens=400, ) get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import SimpleDirectoryReader documents =
SimpleDirectoryReader("./data/paul_graham")
llama_index.core.SimpleDirectoryReader
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=YOUR_OPENAI_KEY') get_ipython().system('pip install llama-index pypdf') get_ipython().system("mkdir -p '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)] from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode node_parser = SentenceSplitter(chunk_size=1024) base_nodes = node_parser.get_nodes_from_documents(docs) for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}" from llama_index.core.embeddings import resolve_embed_model embed_model = resolve_embed_model("local:BAAI/bge-small-en") llm = OpenAI(model="gpt-3.5-turbo") base_index = VectorStoreIndex(base_nodes, embed_model=embed_model) base_retriever = base_index.as_retriever(similarity_top_k=2) retrievals = base_retriever.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for n in retrievals: display_source_node(n, source_length=1500) query_engine_base = RetrieverQueryEngine.from_args(base_retriever, llm=llm) response = query_engine_base.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [ SentenceSplitter(chunk_size=c, chunk_overlap=20) for c in sub_chunk_sizes ] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) original_node = IndexNode.from_text_node(base_node, base_node.node_id) all_nodes.append(original_node) all_nodes_dict = {n.node_id: n for n in all_nodes} vector_index_chunk = VectorStoreIndex(all_nodes, embed_model=embed_model) vector_retriever_chunk = vector_index_chunk.as_retriever(similarity_top_k=2) retriever_chunk = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever_chunk}, node_dict=all_nodes_dict, verbose=True, ) nodes = retriever_chunk.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for node in nodes: display_source_node(node, source_length=2000) query_engine_chunk = RetrieverQueryEngine.from_args(retriever_chunk, llm=llm) response = query_engine_chunk.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) import nest_asyncio nest_asyncio.apply() from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode from llama_index.core.extractors import ( SummaryExtractor, QuestionsAnsweredExtractor, ) extractors = [ SummaryExtractor(summaries=["self"], show_progress=True), QuestionsAnsweredExtractor(questions=5, show_progress=True), ] node_to_metadata = {} for extractor in extractors: metadata_dicts = extractor.extract(base_nodes) for node, metadata in zip(base_nodes, metadata_dicts): if node.node_id not in node_to_metadata: node_to_metadata[node.node_id] = metadata else: node_to_metadata[node.node_id].update(metadata) def save_metadata_dicts(path, data): with open(path, "w") as fp: json.dump(data, fp) def load_metadata_dicts(path): with open(path, "r") as fp: data = json.load(fp) return data save_metadata_dicts("data/llama2_metadata_dicts.json", node_to_metadata) metadata_dicts = load_metadata_dicts("data/llama2_metadata_dicts.json") import copy all_nodes = copy.deepcopy(base_nodes) for node_id, metadata in node_to_metadata.items(): for val in metadata.values(): all_nodes.append(IndexNode(text=val, index_id=node_id)) all_nodes_dict = {n.node_id: n for n in all_nodes} from llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo") vector_index_metadata = VectorStoreIndex(all_nodes) vector_retriever_metadata = vector_index_metadata.as_retriever( similarity_top_k=2 ) retriever_metadata = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever_metadata}, node_dict=all_nodes_dict, verbose=False, ) nodes = retriever_metadata.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for node in nodes:
display_source_node(node, source_length=2000)
llama_index.core.response.notebook_utils.display_source_node
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import nest_asyncio nest_asyncio.apply() import os import openai os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Response from llama_index.llms.openai import OpenAI from llama_index.core.evaluation import ( FaithfulnessEvaluator, RelevancyEvaluator, CorrectnessEvaluator, ) from llama_index.core.node_parser import SentenceSplitter import pandas as pd pd.set_option("display.max_colwidth", 0) gpt4 = OpenAI(temperature=0, model="gpt-4") faithfulness_gpt4 = FaithfulnessEvaluator(llm=gpt4) relevancy_gpt4 = RelevancyEvaluator(llm=gpt4) correctness_gpt4 =
CorrectnessEvaluator(llm=gpt4)
llama_index.core.evaluation.CorrectnessEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-dashvector') get_ipython().system('pip install llama-index') import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) import dashvector api_key = os.environ["DASHVECTOR_API_KEY"] client = dashvector.Client(api_key=api_key) client.create("llama-demo", dimension=1536) dashvector_collection = client.get("quickstart") get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.dashvector import DashVectorStore from IPython.display import Markdown, display documents = SimpleDirectoryReader("./data/paul_graham").load_data() from llama_index.core import StorageContext vector_store = DashVectorStore(dashvector_collection) storage_context =
StorageContext.from_defaults(vector_store=vector_store)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-redis') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys import os logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import VectorStoreIndex, SimpleKeywordTableIndex from llama_index.core import SummaryIndex from llama_index.core import ComposableGraph from llama_index.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_response from llama_index.core import Settings get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") reader =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-replicate') get_ipython().run_line_magic('pip', 'install unstructured replicate') get_ipython().run_line_magic('pip', 'install llama_index ftfy regex tqdm') get_ipython().run_line_magic('pip', 'install git+https://github.com/openai/CLIP.git') get_ipython().run_line_magic('pip', 'install torch torchvision') get_ipython().run_line_magic('pip', 'install matplotlib scikit-image') get_ipython().run_line_magic('pip', 'install -U qdrant_client') import os REPLICATE_API_TOKEN = "..." # Your Relicate API token here os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1UU0xc3uLXs-WG0aDQSXjGacUkp142rLS" -O texas.jpg') from llama_index.readers.file import FlatReader from pathlib import Path from llama_index.core.node_parser import UnstructuredElementNodeParser reader = FlatReader() docs_2021 = reader.load_data(Path("tesla_2021_10k.htm")) node_parser = UnstructuredElementNodeParser() import openai OPENAI_API_TOKEN = "..." openai.api_key = OPENAI_API_TOKEN # add your openai api key here os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN import os import pickle if not os.path.exists("2021_nodes.pkl"): raw_nodes_2021 = node_parser.get_nodes_from_documents(docs_2021) pickle.dump(raw_nodes_2021, open("2021_nodes.pkl", "wb")) else: raw_nodes_2021 = pickle.load(open("2021_nodes.pkl", "rb")) nodes_2021, objects_2021 = node_parser.get_nodes_and_objects(raw_nodes_2021) from llama_index.core import VectorStoreIndex vector_index = VectorStoreIndex(nodes=nodes_2021, objects=objects_2021) query_engine = vector_index.as_query_engine(similarity_top_k=5, verbose=True) from PIL import Image import matplotlib.pyplot as plt imageUrl = "./texas.jpg" image = Image.open(imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index.core.schema import ImageDocument from llama_index.multi_modal_llms.replicate.base import ( REPLICATE_MULTI_MODAL_LLM_MODELS, ) print(imageUrl) llava_multi_modal_llm = ReplicateMultiModal( model=REPLICATE_MULTI_MODAL_LLM_MODELS["llava-13b"], max_new_tokens=200, temperature=0.1, ) prompt = "which Tesla factory is shown in the image? Please answer just the name of the factory." llava_response = llava_multi_modal_llm.complete( prompt=prompt, image_documents=[ImageDocument(image_path=imageUrl)], ) print(llava_response.text) rag_response = query_engine.query(llava_response.text) print(rag_response) input_image_path = Path("instagram_images") if not input_image_path.exists(): Path.mkdir(input_image_path) get_ipython().system('wget "https://docs.google.com/uc?export=download&id=12ZpBBFkYu-jzz1iz356U5kMikn4uN9ww" -O ./instagram_images/jordan.png') from pydantic import BaseModel class InsAds(BaseModel): """Data model for a Ins Ads.""" account: str brand: str product: str category: str discount: str price: str comments: str review: str description: str from PIL import Image import matplotlib.pyplot as plt ins_imageUrl = "./instagram_images/jordan.png" image = Image.open(ins_imageUrl).convert("RGB") plt.figure(figsize=(16, 5)) plt.imshow(image) from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index.core.program import MultiModalLLMCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser from llama_index.multi_modal_llms.replicate.base import ( REPLICATE_MULTI_MODAL_LLM_MODELS, ) prompt_template_str = """\ can you summarize what is in the image\ and return the answer with json format \ """ def pydantic_llava( model_name, output_class, image_documents, prompt_template_str ): mm_llm = ReplicateMultiModal( model=REPLICATE_MULTI_MODAL_LLM_MODELS["llava-13b"], max_new_tokens=1000, ) llm_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(output_class), image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=mm_llm, verbose=True, ) response = llm_program() print(f"Model: {model_name}") for res in response: print(res) return response from llama_index.core import SimpleDirectoryReader ins_image_documents = SimpleDirectoryReader("./instagram_images").load_data() pydantic_response = pydantic_llava( "llava-13b", InsAds, ins_image_documents, prompt_template_str ) print(pydantic_response.brand) from pathlib import Path import requests wiki_titles = [ "batman", "Vincent van Gogh", "San Francisco", "iPhone", "Tesla Model S", "BTS", "Air Jordan", ] data_path = Path("data_wiki") 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"] if not data_path.exists(): Path.mkdir(data_path) with open(data_path / f"{title}.txt", "w") as fp: fp.write(wiki_text) import wikipedia import urllib.request image_path = Path("data_wiki") image_uuid = 0 image_metadata_dict = {} MAX_IMAGES_PER_WIKI = 30 wiki_titles = [ "Air Jordan", "San Francisco", "Batman", "Vincent van Gogh", "iPhone", "Tesla Model S", "BTS band", ] if not image_path.exists(): Path.mkdir(image_path) for title in wiki_titles: images_per_wiki = 0 print(title) try: page_py = wikipedia.page(title) list_img_urls = page_py.images for url in list_img_urls: if url.endswith(".jpg") or url.endswith(".png"): image_uuid += 1 image_file_name = title + "_" + url.split("/")[-1] image_metadata_dict[image_uuid] = { "filename": image_file_name, "img_path": "./" + str(image_path / f"{image_uuid}.jpg"), } urllib.request.urlretrieve( url, image_path / f"{image_uuid}.jpg" ) images_per_wiki += 1 if images_per_wiki > MAX_IMAGES_PER_WIKI: break except: print(str(Exception("No images found for Wikipedia page: ")) + title) continue import qdrant_client from llama_index.core import SimpleDirectoryReader from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import VectorStoreIndex, StorageContext from llama_index.core.indices import MultiModalVectorStoreIndex client = qdrant_client.QdrantClient(path="qdrant_mm_db") text_store = QdrantVectorStore( client=client, collection_name="text_collection" ) image_store = QdrantVectorStore( client=client, collection_name="image_collection" ) storage_context = StorageContext.from_defaults( vector_store=text_store, image_store=image_store ) documents = SimpleDirectoryReader("./data_wiki/").load_data() index = MultiModalVectorStoreIndex.from_documents( documents, storage_context=storage_context, ) from PIL import Image import matplotlib.pyplot as plt import os def plot_images(image_metadata_dict): original_images_urls = [] images_shown = 0 for image_id in image_metadata_dict: img_path = image_metadata_dict[image_id]["img_path"] if os.path.isfile(img_path): filename = image_metadata_dict[image_id]["filename"] image = Image.open(img_path).convert("RGB") plt.subplot(8, 8, len(original_images_urls) + 1) plt.imshow(image) plt.xticks([]) plt.yticks([]) original_images_urls.append(filename) images_shown += 1 if images_shown >= 64: break plt.tight_layout() plot_images(image_metadata_dict) retriever = index.as_retriever(similarity_top_k=3, image_similarity_top_k=5) retrieval_results = retriever.retrieve(pydantic_response.brand) from llama_index.core.response.notebook_utils import ( display_source_node, display_image_uris, ) from llama_index.core.schema import ImageNode retrieved_image = [] for res_node in retrieval_results: if isinstance(res_node.node, ImageNode): retrieved_image.append(res_node.node.metadata["file_path"]) else: display_source_node(res_node, source_length=200)
display_image_uris(retrieved_image)
llama_index.core.response.notebook_utils.display_image_uris
from llama_index.llms.openai import OpenAI from llama_index.core import VectorStoreIndex from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.postprocessor import LLMRerank from llama_index.core import VectorStoreIndex from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core import Settings from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.packs.koda_retriever import KodaRetriever import os from pinecone import Pinecone pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY")) index = pc.Index("sample-movies") Settings.llm = OpenAI() Settings.embed_model = OpenAIEmbedding() vector_store = PineconeVectorStore(pinecone_index=index, text_key="summary") vector_index = VectorStoreIndex.from_vector_store( vector_store=vector_store, embed_model=Settings.embed_model ) reranker =
LLMRerank(llm=Settings.llm)
llama_index.core.postprocessor.LLMRerank
get_ipython().run_line_magic('pip', 'install llama-index-readers-github') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index llama-hub') import nest_asyncio nest_asyncio.apply() import os os.environ["GITHUB_TOKEN"] = "ghp_..." os.environ["OPENAI_API_KEY"] = "sk-..." import os from llama_index.readers.github import ( GitHubRepositoryIssuesReader, GitHubIssuesClient, ) github_client = GitHubIssuesClient() loader = GitHubRepositoryIssuesReader( github_client, owner="run-llama", repo="llama_index", verbose=True, ) orig_docs = loader.load_data() limit = 100 docs = [] for idx, doc in enumerate(orig_docs): doc.metadata["index_id"] = int(doc.id_) if idx >= limit: break docs.append(doc) import weaviate auth_config = weaviate.AuthApiKey( api_key="XRa15cDIkYRT7AkrpqT6jLfE4wropK1c1TGk" ) client = weaviate.Client( "https://llama-index-test-v0oggsoz.weaviate.network", auth_client_secret=auth_config, ) class_name = "LlamaIndex_docs" client.schema.delete_class(class_name) from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core import VectorStoreIndex, StorageContext vector_store = WeaviateVectorStore( weaviate_client=client, index_name=class_name ) storage_context = StorageContext.from_defaults(vector_store=vector_store) doc_index = VectorStoreIndex.from_documents( docs, storage_context=storage_context ) from llama_index.core import SummaryIndex from llama_index.core.async_utils import run_jobs from llama_index.llms.openai import OpenAI from llama_index.core.schema import IndexNode from llama_index.core.vector_stores import ( FilterOperator, MetadataFilter, MetadataFilters, ) async def aprocess_doc(doc, include_summary: bool = True): """Process doc.""" metadata = doc.metadata date_tokens = metadata["created_at"].split("T")[0].split("-") year = int(date_tokens[0]) month = int(date_tokens[1]) day = int(date_tokens[2]) assignee = ( "" if "assignee" not in doc.metadata else doc.metadata["assignee"] ) size = "" if len(doc.metadata["labels"]) > 0: size_arr = [l for l in doc.metadata["labels"] if "size:" in l] size = size_arr[0].split(":")[1] if len(size_arr) > 0 else "" new_metadata = { "state": metadata["state"], "year": year, "month": month, "day": day, "assignee": assignee, "size": size, } summary_index = SummaryIndex.from_documents([doc]) query_str = "Give a one-sentence concise summary of this issue." query_engine = summary_index.as_query_engine( llm=OpenAI(model="gpt-3.5-turbo") ) summary_txt = await query_engine.aquery(query_str) summary_txt = str(summary_txt) index_id = doc.metadata["index_id"] filters = MetadataFilters( filters=[ MetadataFilter( key="index_id", operator=FilterOperator.EQ, value=int(index_id) ), ] ) index_node = IndexNode( text=summary_txt, metadata=new_metadata, obj=doc_index.as_retriever(filters=filters), index_id=doc.id_, ) return index_node async def aprocess_docs(docs): """Process metadata on docs.""" index_nodes = [] tasks = [] for doc in docs: task = aprocess_doc(doc) tasks.append(task) index_nodes = await run_jobs(tasks, show_progress=True, workers=3) return index_nodes index_nodes = await aprocess_docs(docs) index_nodes[5].metadata import weaviate auth_config = weaviate.AuthApiKey( api_key="XRa15cDIkYRT7AkrpqT6jLfE4wropK1c1TGk" ) client = weaviate.Client( "https://llama-index-test-v0oggsoz.weaviate.network", auth_client_secret=auth_config, ) class_name = "LlamaIndex_auto" client.schema.delete_class(class_name) from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core import VectorStoreIndex, StorageContext vector_store_auto = WeaviateVectorStore( weaviate_client=client, index_name=class_name ) storage_context_auto = StorageContext.from_defaults( vector_store=vector_store_auto ) index = VectorStoreIndex( objects=index_nodes, storage_context=storage_context_auto ) from llama_index.core.vector_stores import MetadataInfo, VectorStoreInfo vector_store_info = VectorStoreInfo( content_info="Github Issues", metadata_info=[ MetadataInfo( name="state", description="Whether the issue is `open` or `closed`", type="string", ), MetadataInfo( name="year", description="The year issue was created", type="integer", ), MetadataInfo( name="month", description="The month issue was created", type="integer", ), MetadataInfo( name="day", description="The day issue was created", type="integer", ), MetadataInfo( name="assignee", description="The assignee of the ticket", type="string", ), MetadataInfo( name="size", description="How big the issue is (XS, S, M, L, XL, XXL)", type="string", ), ], ) from llama_index.core.retrievers import VectorIndexAutoRetriever retriever = VectorIndexAutoRetriever( index, vector_store_info=vector_store_info, similarity_top_k=2, empty_query_top_k=10, # if only metadata filters are specified, this is the limit verbose=True, ) from llama_index.core import QueryBundle nodes = retriever.retrieve(QueryBundle("Tell me about some issues on 01/11")) print(f"Number of source nodes: {len(nodes)}") nodes[0].node.metadata from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo") query_engine =
RetrieverQueryEngine.from_args(retriever, llm=llm)
llama_index.core.query_engine.RetrieverQueryEngine.from_args
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") Settings.chunk_size = 512 from pathlib import Path import requests wiki_titles = [ "Vincent van Gogh", ] data_path = Path("data_wiki") 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"] if not data_path.exists(): Path.mkdir(data_path) with open(data_path / f"{title}.txt", "w") as fp: fp.write(wiki_text) documents = SimpleDirectoryReader("./data_wiki/").load_data() index = VectorStoreIndex.from_documents( documents, ) from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core import QueryBundle from llama_index.postprocessor.rankgpt_rerank import RankGPTRerank import pandas as pd from IPython.display import display, HTML def get_retrieved_nodes( query_str, vector_top_k=10, reranker_top_n=3, with_reranker=False ): query_bundle = QueryBundle(query_str) retriever = VectorIndexRetriever( index=index, similarity_top_k=vector_top_k, ) retrieved_nodes = retriever.retrieve(query_bundle) if with_reranker: reranker = RankGPTRerank( llm=OpenAI( model="gpt-3.5-turbo-16k", temperature=0.0, api_key=OPENAI_API_TOKEN, ), top_n=reranker_top_n, verbose=True, ) retrieved_nodes = reranker.postprocess_nodes( retrieved_nodes, query_bundle ) return retrieved_nodes def pretty_print(df): return display(HTML(df.to_html().replace("\\n", "<br>"))) def visualize_retrieved_nodes(nodes) -> None: result_dicts = [] for node in nodes: result_dict = {"Score": node.score, "Text": node.node.get_text()} result_dicts.append(result_dict) pretty_print(pd.DataFrame(result_dicts)) new_nodes = get_retrieved_nodes( "Which date did Paul Gauguin arrive in Arles?", vector_top_k=3, with_reranker=False, ) visualize_retrieved_nodes(new_nodes) new_nodes = get_retrieved_nodes( "Which date did Paul Gauguin arrive in Arles ?", vector_top_k=10, reranker_top_n=3, with_reranker=True, ) visualize_retrieved_nodes(new_nodes) from llama_index.llms.ollama import Ollama llm =
Ollama(model="mistral", request_timeout=30.0)
llama_index.llms.ollama.Ollama
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-indices-managed-vectara') 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.schema import TextNode from llama_index.core.indices.managed.types import ManagedIndexQueryMode from llama_index.indices.managed.vectara import VectaraIndex from llama_index.indices.managed.vectara import VectaraAutoRetriever from llama_index.core.vector_stores import MetadataInfo, VectorStoreInfo from llama_index.llms.openai import OpenAI nodes = [ TextNode( text=( "A pragmatic paleontologist touring an almost complete theme park on an island " + "in Central America is tasked with protecting a couple of kids after a power " + "failure causes the park's cloned dinosaurs to run loose." ), metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), TextNode( text=( "A thief who steals corporate secrets through the use of dream-sharing technology " + "is given the inverse task of planting an idea into the mind of a C.E.O., " + "but his tragic past may doom the project and his team to disaster." ), metadata={ "year": 2010, "director": "Christopher Nolan", "rating": 8.2, }, ), TextNode( text="Barbie suffers a crisis that leads her to question her world and her existence.", metadata={ "year": 2023, "director": "Greta Gerwig", "genre": "fantasy", "rating": 9.5, }, ), TextNode( text=( "A cowboy doll is profoundly threatened and jealous when a new spaceman action " + "figure supplants him as top toy in a boy's bedroom." ), metadata={"year": 1995, "genre": "animated", "rating": 8.3}, ), TextNode( text=( "When Woody is stolen by a toy collector, Buzz and his friends set out on a " + "rescue mission to save Woody before he becomes a museum toy property with his " + "roundup gang Jessie, Prospector, and Bullseye. " ), metadata={"year": 1999, "genre": "animated", "rating": 7.9}, ),
TextNode( text=( "The toys are mistakenly delivered to a day-care center instead of the attic " + "right before Andy leaves for college, and it's up to Woody to convince the " + "other toys that they weren't abandoned and to return home." )
llama_index.core.schema.TextNode
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") import random def split_train_val_by_query(dataset, split=0.7): """Split dataset by queries.""" query_ids = list(dataset.queries.keys()) query_ids_shuffled = random.sample(query_ids, len(query_ids)) split_idx = int(len(query_ids) * split) train_query_ids = query_ids_shuffled[:split_idx] eval_query_ids = query_ids_shuffled[split_idx:] train_queries = {qid: dataset.queries[qid] for qid in train_query_ids} eval_queries = {qid: dataset.queries[qid] for qid in eval_query_ids} train_rel_docs = { qid: dataset.relevant_docs[qid] for qid in train_query_ids } eval_rel_docs = {qid: dataset.relevant_docs[qid] for qid in eval_query_ids} train_dataset = EmbeddingQAFinetuneDataset( queries=train_queries, corpus=dataset.corpus, relevant_docs=train_rel_docs, ) eval_dataset = EmbeddingQAFinetuneDataset( queries=eval_queries, corpus=dataset.corpus, relevant_docs=eval_rel_docs, ) return train_dataset, eval_dataset train_dataset, eval_dataset = split_train_val_by_query(dataset, split=0.7) from llama_index.finetuning import SentenceTransformersFinetuneEngine finetune_engine = SentenceTransformersFinetuneEngine( train_dataset, model_id="BAAI/bge-small-en", model_output_path="test_model3", val_dataset=eval_dataset, epochs=30, # can set to higher (haven't tested) ) finetune_engine.finetune() ft_embed_model = finetune_engine.get_finetuned_model() ft_embed_model from llama_index.core.embeddings import resolve_embed_model base_embed_model = resolve_embed_model("local:BAAI/bge-small-en") from llama_index.core.selectors import ( EmbeddingSingleSelector, LLMSingleSelector, ) ft_selector = EmbeddingSingleSelector.from_defaults(embed_model=ft_embed_model) base_selector = EmbeddingSingleSelector.from_defaults( embed_model=base_embed_model ) import numpy as np def run_evals(eval_dataset, selector, choices, choice_to_id_dict): eval_pairs = eval_dataset.query_docid_pairs matches = [] for query, relevant_doc_ids in tqdm(eval_pairs): result = selector.select(choices, query) pred_doc_id = choice_to_id_dict[result.inds[0]] gt_doc_id = relevant_doc_ids[0] matches.append(gt_doc_id == pred_doc_id) return np.array(matches) ft_matches = run_evals(eval_dataset, ft_selector, choices, choice_to_id_dict) np.mean(ft_matches) base_matches = run_evals( eval_dataset, base_selector, choices, choice_to_id_dict ) np.mean(base_matches) from llama_index.llms.openai import OpenAI eval_llm =
OpenAI(model="gpt-3.5-turbo")
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-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() from IPython.display import HTML, display def set_css(): display( HTML( """ <style> pre { white-space: pre-wrap; } </style> """ ) ) get_ipython().events.register("pre_run_cell", set_css) get_ipython().system('mkdir data') get_ipython().system('wget "https://www.dropbox.com/s/948jr9cfs7fgj99/UBER.zip?dl=1" -O data/UBER.zip') get_ipython().system('unzip data/UBER.zip -d data') from llama_index.readers.file import UnstructuredReader from pathlib import Path years = [2022, 2021, 2020, 2019] loader = UnstructuredReader() doc_set = {} all_docs = [] for year in years: year_docs = loader.load_data( file=Path(f"./data/UBER/UBER_{year}.html"), split_documents=False ) for d in year_docs: d.metadata = {"year": year} doc_set[year] = year_docs all_docs.extend(year_docs) from llama_index.core import VectorStoreIndex, StorageContext from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.chunk_size = 512 Settings.chunk_overlap = 64 Settings.llm = OpenAI(model="gpt-3.5-turbo") Settings.embed_model =
OpenAIEmbedding(model="text-embedding-3-small")
llama_index.embeddings.openai.OpenAIEmbedding
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-supabase') get_ipython().system('pip install llama-index') import logging import sys from llama_index.core import SimpleDirectoryReader, Document, StorageContext from llama_index.core import VectorStoreIndex from llama_index.vector_stores.supabase import SupabaseVectorStore import textwrap import os os.environ["OPENAI_API_KEY"] = "[your_openai_api_key]" get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() print( "Document ID:", documents[0].doc_id, "Document Hash:", documents[0].doc_hash, ) vector_store = SupabaseVectorStore( postgres_connection_string=( "postgresql://<user>:<password>@<host>:<port>/<db_name>" ), collection_name="base_demo", ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) query_engine = index.as_query_engine() response = query_engine.query("Who is the author?") print(textwrap.fill(str(response), 100)) response = query_engine.query("What did the author do growing up?") print(textwrap.fill(str(response), 100)) from llama_index.core.schema import TextNode nodes = [ TextNode( **{ "text": "The Shawshank Redemption", "metadata": { "author": "Stephen King", "theme": "Friendship", }, } ), TextNode( **{ "text": "The Godfather", "metadata": { "director": "Francis Ford Coppola", "theme": "Mafia", }, } ), TextNode( **{ "text": "Inception", "metadata": { "director": "Christopher Nolan", }, } ), ] vector_store = SupabaseVectorStore( postgres_connection_string=( "postgresql://<user>:<password>@<host>:<port>/<db_name>" ), collection_name="metadata_filters_demo", ) storage_context =
StorageContext.from_defaults(vector_store=vector_store)
llama_index.core.StorageContext.from_defaults
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")
llama_index.llms.openai.OpenAI
get_ipython().system('pip install llama-index-llms-dashscope') get_ipython().run_line_magic('env', 'DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY') import os os.environ["DASHSCOPE_API_KEY"] = "YOUR_DASHSCOPE_API_KEY" from llama_index.llms.dashscope import DashScope, DashScopeGenerationModels dashscope_llm = DashScope(model_name=DashScopeGenerationModels.QWEN_MAX) resp = dashscope_llm.complete("How to make cake?") print(resp) responses = dashscope_llm.stream_complete("How to make cake?") for response in responses: print(response.delta, end="") from llama_index.core.base.llms.types import MessageRole, ChatMessage messages = [ ChatMessage( role=MessageRole.SYSTEM, content="You are a helpful assistant." ), ChatMessage(role=MessageRole.USER, content="How to make cake?"), ] resp = dashscope_llm.chat(messages) print(resp) responses = dashscope_llm.stream_chat(messages) for response in responses: print(response.delta, end="") messages = [ ChatMessage( role=MessageRole.SYSTEM, content="You are a helpful assistant." ), ChatMessage(role=MessageRole.USER, content="How to make cake?"), ] resp = dashscope_llm.chat(messages) print(resp) messages.append( ChatMessage(role=MessageRole.ASSISTANT, content=resp.message.content) ) messages.append(
ChatMessage(role=MessageRole.USER, content="How to make it without sugar")
llama_index.core.base.llms.types.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-azure-openai') get_ipython().run_line_magic('pip', 'install llama-index-graph-stores-nebula') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-azure-openai') get_ipython().system('pip install llama-index') import os os.environ["OPENAI_API_KEY"] = "sk-..." import logging import sys logging.basicConfig( stream=sys.stdout, level=logging.INFO ) # logging.DEBUG for more verbose output from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(temperature=0, model="gpt-3.5-turbo") Settings.chunk_size = 512 from llama_index.llms.azure_openai import AzureOpenAI from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding api_key = "<api-key>" azure_endpoint = "https://<your-resource-name>.openai.azure.com/" api_version = "2023-07-01-preview" llm = AzureOpenAI( model="gpt-35-turbo-16k", deployment_name="my-custom-llm", api_key=api_key, azure_endpoint=azure_endpoint, api_version=api_version, ) embed_model = AzureOpenAIEmbedding( model="text-embedding-ada-002", deployment_name="my-custom-embedding", api_key=api_key, azure_endpoint=azure_endpoint, api_version=api_version, ) from llama_index.core import Settings Settings.llm = llm Settings.embed_model = embed_model Settings.chunk_size = 512 get_ipython().run_line_magic('pip', 'install ipython-ngql nebula3-python') os.environ["NEBULA_USER"] = "root" os.environ["NEBULA_PASSWORD"] = "nebula" # default is "nebula" os.environ[ "NEBULA_ADDRESS" ] = "127.0.0.1:9669" # assumed we have NebulaGraph installed locally space_name = "llamaindex" edge_types, rel_prop_names = ["relationship"], [ "relationship" ] # default, could be omit if create from an empty kg tags = ["entity"] # default, could be omit if create from an empty kg from llama_index.core import StorageContext from llama_index.graph_stores.nebula import NebulaGraphStore graph_store = NebulaGraphStore( space_name=space_name, edge_types=edge_types, rel_prop_names=rel_prop_names, tags=tags, ) storage_context =
StorageContext.from_defaults(graph_store=graph_store)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-replicate') get_ipython().run_line_magic('pip', 'install unstructured replicate') get_ipython().run_line_magic('pip', 'install llama_index ftfy regex tqdm') get_ipython().run_line_magic('pip', 'install git+https://github.com/openai/CLIP.git') get_ipython().run_line_magic('pip', 'install torch torchvision') get_ipython().run_line_magic('pip', 'install matplotlib scikit-image') get_ipython().run_line_magic('pip', 'install -U qdrant_client') import os REPLICATE_API_TOKEN = "..." # Your Relicate API token here os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://docs.google.com/uc?export=download&id=1UU0xc3uLXs-WG0aDQSXjGacUkp142rLS" -O texas.jpg') from llama_index.readers.file import FlatReader from pathlib import Path from llama_index.core.node_parser import UnstructuredElementNodeParser reader = FlatReader() docs_2021 = reader.load_data(Path("tesla_2021_10k.htm")) node_parser =
UnstructuredElementNodeParser()
llama_index.core.node_parser.UnstructuredElementNodeParser
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) query_engine = vector_index.as_query_engine(similarity_top_k=3) assert len(query_list) == len(reference_answers_list) pairwise_local_score = 0 for index in range(0, len(query_list)): query = query_list[index] reference = reference_answers_list[index] if reference != "Unacceptable": number_of_accepted_queries += 1 response = str(query_engine.query(query)) no_reranker_dict = { "query": query, "response": response, "reference": reference, } no_reranker_dict_list.append(no_reranker_dict) pairwise_eval_result = await evaluator_gpt4_pairwise.aevaluate( query, response=response, reference=reference ) pairwise_score = pairwise_eval_result.score pairwise_local_score += pairwise_score else: pass if number_of_accepted_queries > 0: avg_pairwise_local_score = ( pairwise_local_score / number_of_accepted_queries ) pairwise_scores_list.append(avg_pairwise_local_score) overal_pairwise_average_score = sum(pairwise_scores_list) / len( pairwise_scores_list ) df_responses = pd.DataFrame(no_reranker_dict_list) df_responses.to_csv("No_Reranker_Responses.csv") results_dict = { "name": ["Without Reranker"], "pairwise score": [overal_pairwise_average_score], } results_df = pd.DataFrame(results_dict) display(results_df) from llama_index.core.postprocessor import SentenceTransformerRerank 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 import os import openai os.environ["OPENAI_API_KEY"] = "sk-" openai.api_key = os.environ["OPENAI_API_KEY"] rerank = SentenceTransformerRerank( model="cross-encoder/ms-marco-MiniLM-L-12-v2", top_n=3 ) gpt4 =
OpenAI(temperature=0, model="gpt-4")
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-huggingface') 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.postprocessor import ( PIINodePostprocessor, NERPIINodePostprocessor, ) from llama_index.llms.huggingface import HuggingFaceLLM from llama_index.core import Document, VectorStoreIndex from llama_index.core.schema import TextNode text = """ Hello Paulo Santos. The latest statement for your credit card account \ 1111-0000-1111-0000 was mailed to 123 Any Street, Seattle, WA 98109. """ node = TextNode(text=text) processor = NERPIINodePostprocessor() from llama_index.core.schema import NodeWithScore new_nodes = processor.postprocess_nodes([NodeWithScore(node=node)]) new_nodes[0].node.get_text() new_nodes[0].node.metadata["__pii_node_info__"] from llama_index.llms.openai import OpenAI processor = PIINodePostprocessor(llm=OpenAI()) from llama_index.core.schema import NodeWithScore new_nodes = processor.postprocess_nodes([NodeWithScore(node=node)]) new_nodes[0].node.get_text() new_nodes[0].node.metadata["__pii_node_info__"] text = """ Hello Paulo Santos. The latest statement for your credit card account \ 4095-2609-9393-4932 was mailed to Seattle, WA 98109. \ IBAN GB90YNTU67299444055881 and social security number is 474-49-7577 were verified on the system. \ Further communications will be sent to [email protected] """ presidio_node =
TextNode(text=text)
llama_index.core.schema.TextNode
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-cohere') get_ipython().system('pip install llama-index') from llama_index.llms.cohere import Cohere api_key = "Your api key" resp = Cohere(api_key=api_key).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.cohere import Cohere messages = [ ChatMessage(role="user", content="hello there"), ChatMessage( role="assistant", content="Arrrr, matey! How can I help ye today?" ), ChatMessage(role="user", content="What is your name"), ] resp = Cohere(api_key=api_key).chat( messages, preamble_override="You are a pirate with a colorful personality" ) print(resp) from llama_index.llms.openai import OpenAI llm = Cohere(api_key=api_key) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI llm =
Cohere(api_key=api_key)
llama_index.llms.cohere.Cohere
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings from llama_index.core import StorageContext, VectorStoreIndex from llama_index.core import SummaryIndex Settings.llm = OpenAI() Settings.chunk_size = 1024 nodes = Settings.node_parser.get_nodes_from_documents(documents) storage_context = StorageContext.from_defaults() storage_context.docstore.add_documents(nodes) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) summary_query_engine = summary_index.as_query_engine( response_mode="tree_summarize", use_async=True, ) vector_query_engine = vector_index.as_query_engine() from llama_index.core.tools import QueryEngineTool summary_tool = QueryEngineTool.from_defaults( query_engine=summary_query_engine, name="summary_tool", description=( "Useful for summarization questions related to the author's life" ), ) vector_tool = QueryEngineTool.from_defaults( query_engine=vector_query_engine, name="vector_tool", description=( "Useful for retrieving specific context to answer specific questions about the author's life" ), ) from llama_index.agent.openai import OpenAIAssistantAgent agent = OpenAIAssistantAgent.from_new( name="QA bot", instructions="You are a bot designed to answer questions about the author", openai_tools=[], tools=[summary_tool, vector_tool], verbose=True, run_retrieve_sleep_time=1.0, ) response = agent.chat("Can you give me a summary about the author's life?") print(str(response)) response = agent.query("What did the author do after RICS?") print(str(response)) import pinecone import os api_key = os.environ["PINECONE_API_KEY"] pinecone.init(api_key=api_key, environment="us-west1-gcp") try: pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) except Exception: pass pinecone_index = pinecone.Index("quickstart") pinecone_index.delete(deleteAll=True, namespace="test") from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.pinecone import PineconeVectorStore from llama_index.core.schema import TextNode nodes = [
TextNode( text=( "Michael Jordan is a retired professional basketball player," " widely regarded as one of the greatest basketball players of all" " time." )
llama_index.core.schema.TextNode
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().system('pip install llama-index') import pandas as pd pd.set_option("display.max_rows", None) pd.set_option("display.max_columns", None) pd.set_option("display.width", None) pd.set_option("display.max_colwidth", None) get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://www.dropbox.com/scl/fi/rkw0u959yb4w8vlzz76sa/tesla_2020_10k.htm?rlkey=tfkdshswpoupav5tqigwz1mp7&dl=1" -O tesla_2020_10k.htm') from llama_index.readers.file import FlatReader from pathlib import Path reader = FlatReader() docs = reader.load_data(Path("./tesla_2020_10k.htm")) from llama_index.core.evaluation import DatasetGenerator, QueryResponseDataset from llama_index.llms.openai import OpenAI from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.readers.file import FlatReader from llama_index.core.node_parser import HTMLNodeParser, SentenceSplitter from llama_index.core.ingestion import IngestionPipeline from pathlib import Path import nest_asyncio nest_asyncio.apply() reader = FlatReader() docs = reader.load_data(Path("./tesla_2020_10k.htm")) pipeline = IngestionPipeline( documents=docs, transformations=[ HTMLNodeParser.from_defaults(), SentenceSplitter(chunk_size=1024, chunk_overlap=200), OpenAIEmbedding(), ], ) eval_nodes = pipeline.run(documents=docs) eval_llm = OpenAI(model="gpt-3.5-turbo") dataset_generator = DatasetGenerator( eval_nodes[:100], llm=eval_llm, show_progress=True, num_questions_per_chunk=3, ) eval_dataset = await dataset_generator.agenerate_dataset_from_nodes(num=100) len(eval_dataset.qr_pairs) eval_dataset.save_json("data/tesla10k_eval_dataset.json") eval_dataset = QueryResponseDataset.from_json( "data/tesla10k_eval_dataset.json" ) eval_qs = eval_dataset.questions qr_pairs = eval_dataset.qr_pairs ref_response_strs = [r for (_, r) in qr_pairs] from llama_index.core.evaluation import ( CorrectnessEvaluator, SemanticSimilarityEvaluator, ) from llama_index.core.evaluation.eval_utils import ( get_responses, get_results_df, ) from llama_index.core.evaluation import BatchEvalRunner evaluator_c = CorrectnessEvaluator(llm=eval_llm) evaluator_s =
SemanticSimilarityEvaluator(llm=eval_llm)
llama_index.core.evaluation.SemanticSimilarityEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().system('pip install llama-index') from llama_index.core.node_parser import SimpleFileNodeParser from llama_index.readers.file import FlatReader from pathlib import Path reader = FlatReader() html_file = reader.load_data(Path("./stack-overflow.html")) md_file = reader.load_data(Path("./README.md")) print(html_file[0].metadata) print(html_file[0]) print("----") print(md_file[0].metadata) print(md_file[0]) parser =
SimpleFileNodeParser()
llama_index.core.node_parser.SimpleFileNodeParser
get_ipython().run_line_magic('pip', 'install llama-index-readers-github') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index llama-hub') import nest_asyncio nest_asyncio.apply() import os os.environ["GITHUB_TOKEN"] = "ghp_..." os.environ["OPENAI_API_KEY"] = "sk-..." import os from llama_index.readers.github import ( GitHubRepositoryIssuesReader, GitHubIssuesClient, ) github_client = GitHubIssuesClient() loader = GitHubRepositoryIssuesReader( github_client, owner="run-llama", repo="llama_index", verbose=True, ) orig_docs = loader.load_data() limit = 100 docs = [] for idx, doc in enumerate(orig_docs): doc.metadata["index_id"] = int(doc.id_) if idx >= limit: break docs.append(doc) import weaviate auth_config = weaviate.AuthApiKey( api_key="XRa15cDIkYRT7AkrpqT6jLfE4wropK1c1TGk" ) client = weaviate.Client( "https://llama-index-test-v0oggsoz.weaviate.network", auth_client_secret=auth_config, ) class_name = "LlamaIndex_docs" client.schema.delete_class(class_name) from llama_index.vector_stores.weaviate import WeaviateVectorStore from llama_index.core import VectorStoreIndex, StorageContext vector_store = WeaviateVectorStore( weaviate_client=client, index_name=class_name ) storage_context = StorageContext.from_defaults(vector_store=vector_store) doc_index = VectorStoreIndex.from_documents( docs, storage_context=storage_context ) from llama_index.core import SummaryIndex from llama_index.core.async_utils import run_jobs from llama_index.llms.openai import OpenAI from llama_index.core.schema import IndexNode from llama_index.core.vector_stores import ( FilterOperator, MetadataFilter, MetadataFilters, ) async def aprocess_doc(doc, include_summary: bool = True): """Process doc.""" metadata = doc.metadata date_tokens = metadata["created_at"].split("T")[0].split("-") year = int(date_tokens[0]) month = int(date_tokens[1]) day = int(date_tokens[2]) assignee = ( "" if "assignee" not in doc.metadata else doc.metadata["assignee"] ) size = "" if len(doc.metadata["labels"]) > 0: size_arr = [l for l in doc.metadata["labels"] if "size:" in l] size = size_arr[0].split(":")[1] if len(size_arr) > 0 else "" new_metadata = { "state": metadata["state"], "year": year, "month": month, "day": day, "assignee": assignee, "size": size, } summary_index =
SummaryIndex.from_documents([doc])
llama_index.core.SummaryIndex.from_documents
get_ipython().system('pip install llama-index') from llama_index.core.evaluation import SemanticSimilarityEvaluator evaluator =
SemanticSimilarityEvaluator()
llama_index.core.evaluation.SemanticSimilarityEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') 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-embeddings-openai') get_ipython().system('pip install llama-index llama-hub') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') 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 reader = UnstructuredReader() from pathlib import Path all_files_gen = Path("./docs.llamaindex.ai/").rglob("*") all_files = [f.resolve() for f in all_files_gen] all_html_files = [f for f in all_files if f.suffix.lower() == ".html"] len(all_html_files) from llama_index.core import Document doc_limit = 100 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 = 72 loaded_doc = Document( text="\n\n".join([d.get_content() for d in loaded_docs[72:]]), metadata={"path": str(f)}, ) print(loaded_doc.metadata["path"]) docs.append(loaded_doc) import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() 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.agent.openai import OpenAIAgent from llama_index.core import ( load_index_from_storage, StorageContext, VectorStoreIndex, ) from llama_index.core import SummaryIndex from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core.node_parser import SentenceSplitter import os from tqdm.notebook import tqdm import pickle async def build_agent_per_doc(nodes, file_base): print(file_base) vi_out_path = f"./data/llamaindex_docs/{file_base}" summary_out_path = f"./data/llamaindex_docs/{file_base}_summary.pkl" if not os.path.exists(vi_out_path): Path("./data/llamaindex_docs/").mkdir(parents=True, exist_ok=True) vector_index = VectorStoreIndex(nodes) vector_index.storage_context.persist(persist_dir=vi_out_path) else: vector_index = load_index_from_storage( StorageContext.from_defaults(persist_dir=vi_out_path), ) summary_index =
SummaryIndex(nodes)
llama_index.core.SummaryIndex
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-pinecone') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') get_ipython().system('pip -q install python-dotenv pinecone-client llama-index pymupdf') dotenv_path = ( "env" # Google Colabs will not let you open a .env, but you can set ) with open(dotenv_path, "w") as f: f.write('PINECONE_API_KEY="<your api key>"\n') f.write('PINECONE_ENVIRONMENT="gcp-starter"\n') f.write('OPENAI_API_KEY="<your api key>"\n') import os from dotenv import load_dotenv load_dotenv(dotenv_path=dotenv_path) import pinecone api_key = os.environ["PINECONE_API_KEY"] environment = os.environ["PINECONE_ENVIRONMENT"] pinecone.init(api_key=api_key, environment=environment) index_name = "llamaindex-rag-fs" pinecone.create_index( index_name, dimension=1536, metric="euclidean", pod_type="p1" ) pinecone_index = pinecone.Index(index_name) pinecone_index.delete(deleteAll=True) from llama_index.vector_stores.pinecone import PineconeVectorStore vector_store = PineconeVectorStore(pinecone_index=pinecone_index) get_ipython().system('mkdir data') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "data/llama2.pdf"') import fitz file_path = "./data/llama2.pdf" doc = fitz.open(file_path) from llama_index.core.node_parser import SentenceSplitter text_parser = SentenceSplitter( chunk_size=1024, ) text_chunks = [] doc_idxs = [] for doc_idx, page in enumerate(doc): page_text = page.get_text("text") cur_text_chunks = text_parser.split_text(page_text) text_chunks.extend(cur_text_chunks) doc_idxs.extend([doc_idx] * len(cur_text_chunks)) from llama_index.core.schema import TextNode nodes = [] for idx, text_chunk in enumerate(text_chunks): node = TextNode( text=text_chunk, ) src_doc_idx = doc_idxs[idx] src_page = doc[src_doc_idx] nodes.append(node) print(nodes[0].metadata) print(nodes[0].get_content(metadata_mode="all")) from llama_index.core.extractors import ( QuestionsAnsweredExtractor, TitleExtractor, ) from llama_index.core.ingestion import IngestionPipeline from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo") extractors = [ TitleExtractor(nodes=5, llm=llm), QuestionsAnsweredExtractor(questions=3, llm=llm), ] pipeline = IngestionPipeline( transformations=extractors, ) nodes = await pipeline.arun(nodes=nodes, in_place=False) print(nodes[0].metadata) from llama_index.embeddings.openai import OpenAIEmbedding embed_model = OpenAIEmbedding() for node in nodes: node_embedding = embed_model.get_text_embedding( node.get_content(metadata_mode="all") ) node.embedding = node_embedding vector_store.add(nodes) from llama_index.core import VectorStoreIndex from llama_index.core import StorageContext 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-lancedb') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-lancedb') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-clip') get_ipython().run_line_magic('pip', 'install llama_index ftfy regex tqdm') get_ipython().run_line_magic('pip', 'install -U openai-whisper') get_ipython().run_line_magic('pip', 'install git+https://github.com/openai/CLIP.git') get_ipython().run_line_magic('pip', 'install torch torchvision') get_ipython().run_line_magic('pip', 'install matplotlib scikit-image') get_ipython().run_line_magic('pip', 'install lancedb') get_ipython().run_line_magic('pip', 'install moviepy') get_ipython().run_line_magic('pip', 'install pytube') get_ipython().run_line_magic('pip', 'install pydub') get_ipython().run_line_magic('pip', 'install SpeechRecognition') get_ipython().run_line_magic('pip', 'install ffmpeg-python') get_ipython().run_line_magic('pip', 'install soundfile') from moviepy.editor import VideoFileClip from pathlib import Path import speech_recognition as sr from pytube import YouTube from pprint import pprint import os OPENAI_API_TOKEN = "" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN video_url = "https://www.youtube.com/watch?v=d_qvLDhkg00" output_video_path = "./video_data/" output_folder = "./mixed_data/" output_audio_path = "./mixed_data/output_audio.wav" filepath = output_video_path + "input_vid.mp4" Path(output_folder).mkdir(parents=True, exist_ok=True) from PIL import Image import matplotlib.pyplot as plt import os def plot_images(image_paths): images_shown = 0 plt.figure(figsize=(16, 9)) for img_path in image_paths: if os.path.isfile(img_path): image = Image.open(img_path) plt.subplot(2, 3, images_shown + 1) plt.imshow(image) plt.xticks([]) plt.yticks([]) images_shown += 1 if images_shown >= 7: break def download_video(url, output_path): """ Download a video from a given url and save it to the output path. Parameters: url (str): The url of the video to download. output_path (str): The path to save the video to. Returns: dict: A dictionary containing the metadata of the video. """ yt = YouTube(url) metadata = {"Author": yt.author, "Title": yt.title, "Views": yt.views} yt.streams.get_highest_resolution().download( output_path=output_path, filename="input_vid.mp4" ) return metadata def video_to_images(video_path, output_folder): """ Convert a video to a sequence of images and save them to the output folder. Parameters: video_path (str): The path to the video file. output_folder (str): The path to the folder to save the images to. """ clip = VideoFileClip(video_path) clip.write_images_sequence( os.path.join(output_folder, "frame%04d.png"), fps=0.2 ) def video_to_audio(video_path, output_audio_path): """ Convert a video to audio and save it to the output path. Parameters: video_path (str): The path to the video file. output_audio_path (str): The path to save the audio to. """ clip = VideoFileClip(video_path) audio = clip.audio audio.write_audiofile(output_audio_path) def audio_to_text(audio_path): """ Convert audio to text using the SpeechRecognition library. Parameters: audio_path (str): The path to the audio file. Returns: test (str): The text recognized from the audio. """ recognizer = sr.Recognizer() audio = sr.AudioFile(audio_path) with audio as source: audio_data = recognizer.record(source) try: text = recognizer.recognize_whisper(audio_data) except sr.UnknownValueError: print("Speech recognition could not understand the audio.") except sr.RequestError as e: print(f"Could not request results from service; {e}") return text try: metadata_vid = download_video(video_url, output_video_path) video_to_images(filepath, output_folder) video_to_audio(filepath, output_audio_path) text_data = audio_to_text(output_audio_path) with open(output_folder + "output_text.txt", "w") as file: file.write(text_data) print("Text data saved to file") file.close() os.remove(output_audio_path) print("Audio file removed") except Exception as e: raise e from llama_index.core.indices import MultiModalVectorStoreIndex from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.core import SimpleDirectoryReader, StorageContext from llama_index.vector_stores.lancedb import LanceDBVectorStore from llama_index.core import SimpleDirectoryReader text_store = LanceDBVectorStore(uri="lancedb", table_name="text_collection") image_store = LanceDBVectorStore(uri="lancedb", table_name="image_collection") storage_context = StorageContext.from_defaults( vector_store=text_store, image_store=image_store ) documents =
SimpleDirectoryReader(output_folder)
llama_index.core.SimpleDirectoryReader
get_ipython().system('pip install llama-index') get_ipython().system('pip install traceloop-sdk') import os os.environ["OPENAI_API_KEY"] = "sk-..." os.environ["TRACELOOP_API_KEY"] = "..." from traceloop.sdk import Traceloop Traceloop.init() 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 docs = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.core import VectorStoreIndex index =
VectorStoreIndex.from_documents(docs)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() from IPython.display import HTML, display def set_css(): display( HTML( """ <style> pre { white-space: pre-wrap; } </style> """ ) ) get_ipython().events.register("pre_run_cell", set_css) get_ipython().system('mkdir data') get_ipython().system('wget "https://www.dropbox.com/s/948jr9cfs7fgj99/UBER.zip?dl=1" -O data/UBER.zip') get_ipython().system('unzip data/UBER.zip -d data') from llama_index.readers.file import UnstructuredReader from pathlib import Path years = [2022, 2021, 2020, 2019] loader =
UnstructuredReader()
llama_index.readers.file.UnstructuredReader
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') 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 from llama_index.core import PromptTemplate from IPython.display import Markdown, display 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.llms.openai import OpenAI gpt35_llm = OpenAI(model="gpt-3.5-turbo") gpt4_llm = OpenAI(model="gpt-4") index = VectorStoreIndex.from_documents(documents) query_str = "What are the potential risks associated with the use of Llama 2 as mentioned in the context?" query_engine = index.as_query_engine(similarity_top_k=2, llm=gpt35_llm) vector_retriever = index.as_retriever(similarity_top_k=2) response = query_engine.query(query_str) print(str(response)) 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) from langchain import hub langchain_prompt = hub.pull("rlm/rag-prompt") from llama_index.core.prompts import LangchainPromptTemplate lc_prompt_tmpl = LangchainPromptTemplate( template=langchain_prompt, template_var_mappings={"query_str": "question", "context_str": "context"}, ) query_engine.update_prompts( {"response_synthesizer:text_qa_template": lc_prompt_tmpl} ) prompts_dict = query_engine.get_prompts() display_prompt_dict(prompts_dict) response = query_engine.query(query_str) print(str(response)) from llama_index.core.schema import TextNode few_shot_nodes = [] for line in open("../llama2_qa_citation_events.jsonl", "r"): few_shot_nodes.append(TextNode(text=line)) few_shot_index =
VectorStoreIndex(few_shot_nodes)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import os os.environ["OPENAI_API_KEY"] = "INSERT OPENAI KEY" import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) from llama_index.core import SimpleDirectoryReader, KnowledgeGraphIndex from llama_index.core.graph_stores import SimpleGraphStore from llama_index.llms.openai import OpenAI from llama_index.core import Settings from IPython.display import Markdown, display documents = SimpleDirectoryReader( "../../../../examples/paul_graham_essay/data" ).load_data() llm = OpenAI(temperature=0, model="text-davinci-002") Settings.llm = llm Settings.chunk_size = 512 from llama_index.core import StorageContext graph_store = SimpleGraphStore() storage_context =
StorageContext.from_defaults(graph_store=graph_store)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-web') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import os import openai from llama_index.core import set_global_handler set_global_handler("wandb", run_args={"project": "llamaindex"}) os.environ["OPENAI_API_KEY"] = "sk-..." openai.api_key = os.environ["OPENAI_API_KEY"] from llama_index.llms.openai import OpenAI from llama_index.core.schema import MetadataMode llm = OpenAI(temperature=0.1, model="gpt-3.5-turbo", max_tokens=512) from llama_index.core.node_parser import TokenTextSplitter from llama_index.core.extractors import ( SummaryExtractor, QuestionsAnsweredExtractor, ) node_parser = TokenTextSplitter( separator=" ", chunk_size=256, chunk_overlap=128 ) extractors_1 = [ QuestionsAnsweredExtractor( questions=3, llm=llm, metadata_mode=MetadataMode.EMBED ), ] extractors_2 = [ SummaryExtractor(summaries=["prev", "self", "next"], llm=llm), QuestionsAnsweredExtractor( questions=3, llm=llm, metadata_mode=MetadataMode.EMBED ), ] from llama_index.core import SimpleDirectoryReader from llama_index.readers.web import SimpleWebPageReader reader = SimpleWebPageReader(html_to_text=True) docs = reader.load_data(urls=["https://eugeneyan.com/writing/llm-patterns/"]) print(docs[0].get_content()) orig_nodes = node_parser.get_nodes_from_documents(docs) nodes = orig_nodes[20:28] print(nodes[3].get_content(metadata_mode="all")) from llama_index.core.ingestion import IngestionPipeline pipeline = IngestionPipeline(transformations=[node_parser, *extractors_1]) nodes_1 = pipeline.run(nodes=nodes, in_place=False, show_progress=True) print(nodes_1[3].get_content(metadata_mode="all")) pipeline = IngestionPipeline(transformations=[node_parser, *extractors_2]) nodes_2 = pipeline.run(nodes=nodes, in_place=False, show_progress=True) print(nodes_2[3].get_content(metadata_mode="all")) print(nodes_2[1].get_content(metadata_mode="all")) from llama_index.core import VectorStoreIndex from llama_index.core.response.notebook_utils import ( display_source_node, display_response, ) index0 = VectorStoreIndex(orig_nodes) index1 = VectorStoreIndex(orig_nodes[:20] + nodes_1 + orig_nodes[28:]) index2 =
VectorStoreIndex(orig_nodes[:20] + nodes_2 + orig_nodes[28:])
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('pip install llama-index') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data//paul_graham/").load_data() index = VectorStoreIndex.from_documents(documents) retriever = index.as_retriever() from llama_index.core.query_engine import CustomQueryEngine from llama_index.core.retrievers import BaseRetriever from llama_index.core import get_response_synthesizer from llama_index.core.response_synthesizers import BaseSynthesizer class RAGQueryEngine(CustomQueryEngine): """RAG Query Engine.""" retriever: BaseRetriever response_synthesizer: BaseSynthesizer def custom_query(self, query_str: str): nodes = self.retriever.retrieve(query_str) response_obj = self.response_synthesizer.synthesize(query_str, nodes) return response_obj from llama_index.llms.openai import OpenAI from llama_index.core import PromptTemplate 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: " ) class RAGStringQueryEngine(CustomQueryEngine): """RAG String Query Engine.""" retriever: BaseRetriever response_synthesizer: BaseSynthesizer llm: OpenAI qa_prompt: PromptTemplate def custom_query(self, query_str: str): nodes = self.retriever.retrieve(query_str) context_str = "\n\n".join([n.node.get_content() for n in nodes]) response = self.llm.complete( qa_prompt.format(context_str=context_str, query_str=query_str) ) return str(response) synthesizer =
get_response_synthesizer(response_mode="compact")
llama_index.core.get_response_synthesizer
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-mongodb') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-firestore') get_ipython().run_line_magic('pip', 'install llama-index-retrievers-bm25') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-redis') get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-dynamodb') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/2307.09288.pdf" -O "./llama2.pdf"') get_ipython().system('wget --user-agent "Mozilla" "https://arxiv.org/pdf/1706.03762.pdf" -O "./attention.pdf"') from llama_index.core import download_loader from llama_index.readers.file import PyMuPDFReader llama2_docs = PyMuPDFReader().load_data( file_path="./llama2.pdf", metadata=True ) attention_docs = PyMuPDFReader().load_data( file_path="./attention.pdf", metadata=True ) import os os.environ["OPENAI_API_KEY"] = "sk-..." from llama_index.core.node_parser import TokenTextSplitter nodes = TokenTextSplitter( chunk_size=1024, chunk_overlap=128 ).get_nodes_from_documents(llama2_docs + attention_docs) from llama_index.core.storage.docstore import SimpleDocumentStore from llama_index.storage.docstore.redis import RedisDocumentStore from llama_index.storage.docstore.mongodb import MongoDocumentStore from llama_index.storage.docstore.firestore import FirestoreDocumentStore from llama_index.storage.docstore.dynamodb import DynamoDBDocumentStore docstore = SimpleDocumentStore() docstore.add_documents(nodes) from llama_index.core import VectorStoreIndex, StorageContext from llama_index.retrievers.bm25 import BM25Retriever from llama_index.vector_stores.qdrant import QdrantVectorStore from qdrant_client import QdrantClient client = QdrantClient(path="./qdrant_data") vector_store = QdrantVectorStore("composable", client=client) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex(nodes=nodes) vector_retriever = index.as_retriever(similarity_top_k=2) bm25_retriever = BM25Retriever.from_defaults( docstore=docstore, similarity_top_k=2 ) from llama_index.core.schema import IndexNode vector_obj = IndexNode( index_id="vector", obj=vector_retriever, text="Vector Retriever" ) bm25_obj = IndexNode( index_id="bm25", obj=bm25_retriever, text="BM25 Retriever" ) from llama_index.core import SummaryIndex summary_index =
SummaryIndex(objects=[vector_obj, bm25_obj])
llama_index.core.SummaryIndex
get_ipython().run_line_magic('pip', 'install llama-index-storage-docstore-firestore') get_ipython().run_line_magic('pip', 'install llama-index-storage-kvstore-firestore') get_ipython().run_line_magic('pip', 'install llama-index-storage-index-store-firestore') 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, StorageContext from llama_index.core import VectorStoreIndex, SimpleKeywordTableIndex from llama_index.core import SummaryIndex from llama_index.core import ComposableGraph from llama_index.llms.openai import OpenAI from llama_index.core.response.notebook_utils import display_response from llama_index.core import Settings get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") reader =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') 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-embeddings-openai') get_ipython().system('pip install llama-index llama-hub') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') 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 reader = UnstructuredReader() from pathlib import Path all_files_gen = Path("./docs.llamaindex.ai/").rglob("*") all_files = [f.resolve() for f in all_files_gen] all_html_files = [f for f in all_files if f.suffix.lower() == ".html"] len(all_html_files) from llama_index.core import Document doc_limit = 100 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 = 72 loaded_doc = Document( text="\n\n".join([d.get_content() for d in loaded_docs[72:]]), metadata={"path": str(f)}, ) print(loaded_doc.metadata["path"]) docs.append(loaded_doc) import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() 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.agent.openai import OpenAIAgent from llama_index.core import ( load_index_from_storage, StorageContext, VectorStoreIndex, ) from llama_index.core import SummaryIndex from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core.node_parser import SentenceSplitter import os from tqdm.notebook import tqdm import pickle async def build_agent_per_doc(nodes, file_base): print(file_base) vi_out_path = f"./data/llamaindex_docs/{file_base}" summary_out_path = f"./data/llamaindex_docs/{file_base}_summary.pkl" if not os.path.exists(vi_out_path): Path("./data/llamaindex_docs/").mkdir(parents=True, exist_ok=True) vector_index = VectorStoreIndex(nodes) vector_index.storage_context.persist(persist_dir=vi_out_path) else: vector_index = load_index_from_storage(
StorageContext.from_defaults(persist_dir=vi_out_path)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai pandas[jinja2] spacy') 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 ( TreeIndex, VectorStoreIndex, SimpleDirectoryReader, Response, ) from llama_index.llms.openai import OpenAI from llama_index.core.evaluation import RelevancyEvaluator from llama_index.core.node_parser import SentenceSplitter import pandas as pd pd.set_option("display.max_colwidth", 0) gpt3 = OpenAI(temperature=0, model="gpt-3.5-turbo") gpt4 = OpenAI(temperature=0, model="gpt-4") evaluator = RelevancyEvaluator(llm=gpt3) evaluator_gpt4 = RelevancyEvaluator(llm=gpt4) documents = SimpleDirectoryReader("./test_wiki_data").load_data() splitter =
SentenceSplitter(chunk_size=512)
llama_index.core.node_parser.SentenceSplitter
import openai openai.api_key = "sk-your-key" from llama_index.agent import OpenAIAgent from llama_index.tools.arxiv.base import ArxivToolSpec arxiv_tool =
ArxivToolSpec()
llama_index.tools.arxiv.base.ArxivToolSpec
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 SimpleDirectoryReader reader = SimpleDirectoryReader( input_files=["./data/paul_graham/paul_graham_essay.txt"] ) docs = reader.load_data() text = docs[0].text from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo") from llama_index.core.response_synthesizers import Refine summarizer =
Refine(llm=llm, verbose=True)
llama_index.core.response_synthesizers.Refine
get_ipython().system('pip install llama-index') get_ipython().system('pip install duckdb') get_ipython().system('pip install llama-index-vector-stores-duckdb') from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.duckdb import DuckDBVectorStore from llama_index.core import StorageContext from IPython.display import Markdown, display import os import openai 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'") documents = SimpleDirectoryReader("data/paul_graham/").load_data() vector_store =
DuckDBVectorStore()
llama_index.vector_stores.duckdb.DuckDBVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-graph-stores-kuzu') import os os.environ["OPENAI_API_KEY"] = "API_KEY_HERE" import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) import shutil shutil.rmtree("./test1", ignore_errors=True) shutil.rmtree("./test2", ignore_errors=True) shutil.rmtree("./test3", ignore_errors=True) get_ipython().run_line_magic('pip', 'install kuzu') import kuzu db = kuzu.Database("test1") from llama_index.graph_stores.kuzu import KuzuGraphStore graph_store = KuzuGraphStore(db) from llama_index.core import SimpleDirectoryReader, KnowledgeGraphIndex from llama_index.llms.openai import OpenAI from llama_index.core import Settings from IPython.display import Markdown, display import kuzu documents = SimpleDirectoryReader( "../../../../examples/paul_graham_essay/data" ).load_data() llm = OpenAI(temperature=0, model="gpt-3.5-turbo") Settings.llm = llm Settings.chunk_size = 512 from llama_index.core import StorageContext storage_context = StorageContext.from_defaults(graph_store=graph_store) index = KnowledgeGraphIndex.from_documents( documents, max_triplets_per_chunk=2, storage_context=storage_context, ) query_engine = index.as_query_engine( include_text=False, response_mode="tree_summarize" ) response = query_engine.query( "Tell me more about Interleaf", ) display(Markdown(f"<b>{response}</b>")) query_engine = index.as_query_engine( include_text=True, response_mode="tree_summarize" ) response = query_engine.query( "Tell me more about Interleaf", ) display(Markdown(f"<b>{response}</b>")) db = kuzu.Database("test2") graph_store = KuzuGraphStore(db) storage_context = StorageContext.from_defaults(graph_store=graph_store) new_index = KnowledgeGraphIndex.from_documents( documents, max_triplets_per_chunk=2, storage_context=storage_context, include_embeddings=True, ) rel_map = graph_store.get_rel_map() query_engine = index.as_query_engine( include_text=True, response_mode="tree_summarize", embedding_mode="hybrid", similarity_top_k=5, ) response = query_engine.query( "Tell me more about what the author worked on at Interleaf", ) display(Markdown(f"<b>{response}</b>")) get_ipython().run_line_magic('pip', 'install pyvis') from pyvis.network import Network g = index.get_networkx_graph() net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(g) net.show("kuzugraph_draw.html") from llama_index.core.node_parser import SentenceSplitter node_parser = SentenceSplitter() nodes = node_parser.get_nodes_from_documents(documents) db = kuzu.Database("test3") graph_store =
KuzuGraphStore(db)
llama_index.graph_stores.kuzu.KuzuGraphStore
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 = "[email protected]" # @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/").load_data() google_index.insert_documents(documents) google_index = GoogleIndex.from_corpus(corpus_id="") query_engine = google_index.as_query_engine() response = query_engine.query("which program did this author attend?") print(response) from llama_index.core.response.notebook_utils import display_source_node for r in response.source_nodes: display_source_node(r, source_length=1000) from google.ai.generativelanguage import ( GenerateAnswerRequest, ) query_engine = google_index.as_query_engine( temperature=0.3, answer_style=GenerateAnswerRequest.AnswerStyle.VERBOSE, ) response = query_engine.query("Which program did this author attend?") print(response) from llama_index.core.response.notebook_utils import display_source_node for r in response.source_nodes: display_source_node(r, source_length=1000) from google.ai.generativelanguage import ( GenerateAnswerRequest, ) query_engine = google_index.as_query_engine( temperature=0.3, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE, ) response = query_engine.query("Which program did this author attend?") print(response) from llama_index.core.response.notebook_utils import display_source_node for r in response.source_nodes: display_source_node(r, source_length=1000) from google.ai.generativelanguage import ( GenerateAnswerRequest, ) query_engine = google_index.as_query_engine( temperature=0.3, answer_style=GenerateAnswerRequest.AnswerStyle.EXTRACTIVE, ) response = query_engine.query("Which program did this author attend?") print(response) from llama_index.core.response.notebook_utils import display_source_node for r in response.source_nodes: display_source_node(r, source_length=1000) 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.llms.gemini import Gemini from llama_index.core.postprocessor import LLMRerank from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.retrievers import VectorIndexRetriever from llama_index.embeddings.gemini import GeminiEmbedding response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.7, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE ) reranker = LLMRerank( top_n=5, llm=Gemini(api_key=GOOGLE_API_KEY), ) retriever = google_index.as_retriever(similarity_top_k=5) query_engine = RetrieverQueryEngine.from_args( retriever=retriever, response_synthesizer=response_synthesizer, node_postprocessors=[reranker], ) response = query_engine.query("Which program did this author attend?") print(response.response) from llama_index.core.postprocessor import SentenceTransformerRerank sbert_rerank = SentenceTransformerRerank( model="cross-encoder/ms-marco-MiniLM-L-2-v2", top_n=5 ) 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.llms.gemini import Gemini from llama_index.core.postprocessor import LLMRerank from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.retrievers import VectorIndexRetriever from llama_index.embeddings.gemini import GeminiEmbedding response_synthesizer = GoogleTextSynthesizer.from_defaults( temperature=0.1, answer_style=GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE ) retriever = google_index.as_retriever(similarity_top_k=5) query_engine = RetrieverQueryEngine.from_args( retriever=retriever, response_synthesizer=response_synthesizer, node_postprocessors=[sbert_rerank], ) response = query_engine.query("Which program did this author attend?") print(response.response) import os OPENAI_API_TOKEN = "sk-" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN from llama_index.core import VectorStoreIndex, StorageContext from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import Settings import qdrant_client Settings.chunk_size = 256 client = qdrant_client.QdrantClient(path="qdrant_retrieval_2") vector_store = QdrantVectorStore(client=client, collection_name="collection") qdrant_index = VectorStoreIndex.from_documents(documents) storage_context =
StorageContext.from_defaults(vector_store=vector_store)
llama_index.core.StorageContext.from_defaults
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=YOUR_OPENAI_KEY') get_ipython().system('pip install llama-index pypdf') get_ipython().system("mkdir -p '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)] from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode node_parser = SentenceSplitter(chunk_size=1024) base_nodes = node_parser.get_nodes_from_documents(docs) for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}" from llama_index.core.embeddings import resolve_embed_model embed_model = resolve_embed_model("local:BAAI/bge-small-en") llm = OpenAI(model="gpt-3.5-turbo") base_index = VectorStoreIndex(base_nodes, embed_model=embed_model) base_retriever = base_index.as_retriever(similarity_top_k=2) retrievals = base_retriever.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for n in retrievals: display_source_node(n, source_length=1500) query_engine_base = RetrieverQueryEngine.from_args(base_retriever, llm=llm) response = query_engine_base.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [ SentenceSplitter(chunk_size=c, chunk_overlap=20) for c in sub_chunk_sizes ] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) original_node = IndexNode.from_text_node(base_node, base_node.node_id) all_nodes.append(original_node) all_nodes_dict = {n.node_id: n for n in all_nodes} vector_index_chunk =
VectorStoreIndex(all_nodes, embed_model=embed_model)
llama_index.core.VectorStoreIndex
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()
llama_index.llms.openai.OpenAI
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-langchain') get_ipython().system('pip install llama-index') from langchain.chat_models import ChatAnyscale, ChatOpenAI from llama_index.llms.langchain import LangChainLLM from llama_index.core import PromptTemplate llm = LangChainLLM(ChatOpenAI()) stream = await llm.astream(
PromptTemplate("Hi, write a short story")
llama_index.core.PromptTemplate
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) sept_index = VectorStoreIndex.from_documents(sept_docs) march_index.storage_context.persist(persist_dir="./storage/march") june_index.storage_context.persist(persist_dir="./storage/june") sept_index.storage_context.persist(persist_dir="./storage/sept") march_engine = march_index.as_query_engine(similarity_top_k=3) june_engine = june_index.as_query_engine(similarity_top_k=3) sept_engine = sept_index.as_query_engine(similarity_top_k=3) query_engine_tools = [ QueryEngineTool( query_engine=march_engine, metadata=ToolMetadata( name="uber_march_10q", description=( "Provides information about Uber 10Q filings for March 2022. " "Use a detailed plain text question as input to the tool." ), ), ), QueryEngineTool( query_engine=june_engine, metadata=ToolMetadata( name="uber_june_10q", description=( "Provides information about Uber financials for June 2021. " "Use a detailed plain text question as input to the tool." ), ), ), QueryEngineTool( query_engine=sept_engine, metadata=ToolMetadata( name="uber_sept_10q", description=( "Provides information about Uber financials for Sept 2021. " "Use a detailed plain text question as input to the tool." ), ), ), ] from llama_index.core import Document from llama_index.agent.openai_legacy import ContextRetrieverOpenAIAgent texts = [ "Abbreviation: X = Revenue", "Abbreviation: YZ = Risk Factors", "Abbreviation: Z = Costs", ] docs = [Document(text=t) for t in texts] context_index =
VectorStoreIndex.from_documents(docs)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-vllm') import os os.environ["HF_HOME"] = "model/" from llama_index.llms.vllm import Vllm llm = Vllm( model="microsoft/Orca-2-7b", tensor_parallel_size=4, max_new_tokens=100, vllm_kwargs={"swap_space": 1, "gpu_memory_utilization": 0.5}, ) llm.complete( ["[INST]You are a helpful assistant[/INST] What is a black hole ?"] ) llm = Vllm( model="codellama/CodeLlama-7b-hf", dtype="float16", tensor_parallel_size=4, temperature=0, max_new_tokens=100, vllm_kwargs={ "swap_space": 1, "gpu_memory_utilization": 0.5, "max_model_len": 4096, }, ) llm.complete(["import socket\n\ndef ping_exponential_backoff(host: str):"]) llm = Vllm( model="mistralai/Mistral-7B-Instruct-v0.1", dtype="float16", tensor_parallel_size=4, temperature=0, max_new_tokens=100, vllm_kwargs={ "swap_space": 1, "gpu_memory_utilization": 0.5, "max_model_len": 4096, }, ) llm.complete([" What is a black hole ?"]) from llama_index.core.llms.vllm import VllmServer llm = VllmServer( api_url="http://localhost:8000/generate", max_new_tokens=100, temperature=0 ) llm.complete("what is a black hole ?") list(llm.stream_complete("what is a black hole"))[-1] from llama_index.core.llms.vllm import VllmServer from llama_index.core.llms import ChatMessage llm = VllmServer( api_url="http://localhost:8000/generate", max_new_tokens=100, temperature=0 ) llm.complete("what is a black hole ?") message = [
ChatMessage(content="hello", author="user")
llama_index.core.llms.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-readers-file') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-openai') get_ipython().system('pip install llama-index') import pandas as pd pd.set_option("display.max_rows", None) pd.set_option("display.max_columns", None) pd.set_option("display.width", None) pd.set_option("display.max_colwidth", None) get_ipython().system('wget "https://www.dropbox.com/scl/fi/mlaymdy1ni1ovyeykhhuk/tesla_2021_10k.htm?rlkey=qf9k4zn0ejrbm716j0gg7r802&dl=1" -O tesla_2021_10k.htm') get_ipython().system('wget "https://www.dropbox.com/scl/fi/rkw0u959yb4w8vlzz76sa/tesla_2020_10k.htm?rlkey=tfkdshswpoupav5tqigwz1mp7&dl=1" -O tesla_2020_10k.htm') from llama_index.readers.file import FlatReader from pathlib import Path reader = FlatReader() docs = reader.load_data(Path("./tesla_2020_10k.htm")) from llama_index.core.evaluation import DatasetGenerator, QueryResponseDataset from llama_index.llms.openai import OpenAI from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.readers.file import FlatReader from llama_index.core.node_parser import HTMLNodeParser, SentenceSplitter from llama_index.core.ingestion import IngestionPipeline from pathlib import Path import nest_asyncio nest_asyncio.apply() reader = FlatReader() docs = reader.load_data(Path("./tesla_2020_10k.htm")) pipeline = IngestionPipeline( documents=docs, transformations=[ HTMLNodeParser.from_defaults(), SentenceSplitter(chunk_size=1024, chunk_overlap=200), OpenAIEmbedding(), ], ) eval_nodes = pipeline.run(documents=docs) eval_llm = OpenAI(model="gpt-3.5-turbo") dataset_generator = DatasetGenerator( eval_nodes[:100], llm=eval_llm, show_progress=True, num_questions_per_chunk=3, ) eval_dataset = await dataset_generator.agenerate_dataset_from_nodes(num=100) len(eval_dataset.qr_pairs) eval_dataset.save_json("data/tesla10k_eval_dataset.json") eval_dataset = QueryResponseDataset.from_json( "data/tesla10k_eval_dataset.json" ) eval_qs = eval_dataset.questions qr_pairs = eval_dataset.qr_pairs ref_response_strs = [r for (_, r) in qr_pairs] from llama_index.core.evaluation import ( CorrectnessEvaluator, SemanticSimilarityEvaluator, ) from llama_index.core.evaluation.eval_utils import ( get_responses, get_results_df, ) from llama_index.core.evaluation import BatchEvalRunner evaluator_c = CorrectnessEvaluator(llm=eval_llm) evaluator_s = SemanticSimilarityEvaluator(llm=eval_llm) evaluator_dict = { "correctness": evaluator_c, "semantic_similarity": evaluator_s, } batch_eval_runner = BatchEvalRunner( evaluator_dict, workers=2, show_progress=True ) from llama_index.core import VectorStoreIndex async def run_evals( pipeline, batch_eval_runner, docs, eval_qs, eval_responses_ref ): nodes = pipeline.run(documents=docs) vector_index = VectorStoreIndex(nodes) query_engine = vector_index.as_query_engine() pred_responses = get_responses(eval_qs, query_engine, show_progress=True) eval_results = await batch_eval_runner.aevaluate_responses( eval_qs, responses=pred_responses, reference=eval_responses_ref ) return eval_results from llama_index.core.node_parser import HTMLNodeParser, SentenceSplitter sent_parser_o0 = SentenceSplitter(chunk_size=1024, chunk_overlap=0) sent_parser_o200 =
SentenceSplitter(chunk_size=1024, chunk_overlap=200)
llama_index.core.node_parser.SentenceSplitter
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') import os os.environ["OPENAI_API_KEY"] = "INSERT OPENAI KEY" get_ipython().system('pip install llama-index') from llama_index.core import download_loader from llama_index.readers.wikipedia import WikipediaReader loader = WikipediaReader() documents = loader.load_data(pages=["Berlin"]) from llama_index.core import VectorStoreIndex index =
VectorStoreIndex.from_documents(documents)
llama_index.core.VectorStoreIndex.from_documents
get_ipython().system('pip install llama-index-llms-dashscope') get_ipython().run_line_magic('env', 'DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY') import os os.environ["DASHSCOPE_API_KEY"] = "YOUR_DASHSCOPE_API_KEY" from llama_index.llms.dashscope import DashScope, DashScopeGenerationModels dashscope_llm = DashScope(model_name=DashScopeGenerationModels.QWEN_MAX) resp = dashscope_llm.complete("How to make cake?") print(resp) responses = dashscope_llm.stream_complete("How to make cake?") for response in responses: print(response.delta, end="") from llama_index.core.base.llms.types import MessageRole, ChatMessage messages = [ ChatMessage( role=MessageRole.SYSTEM, content="You are a helpful assistant." ),
ChatMessage(role=MessageRole.USER, content="How to make cake?")
llama_index.core.base.llms.types.ChatMessage
get_ipython().run_line_magic('pip', 'install llama-index-llms-litellm') get_ipython().system('pip install llama-index') import os from llama_index.llms.litellm import LiteLLM from llama_index.core.llms import ChatMessage os.environ["OPENAI_API_KEY"] = "your-api-key" os.environ["COHERE_API_KEY"] = "your-api-key" message = ChatMessage(role="user", content="Hey! how's it going?") llm = LiteLLM("gpt-3.5-turbo") chat_response = llm.chat([message]) llm =
LiteLLM("command-nightly")
llama_index.llms.litellm.LiteLLM
get_ipython().run_line_magic('pip', 'install llama-index-llms-anthropic') get_ipython().system('pip install llama-index') from llama_index.llms.anthropic import Anthropic from llama_index.core import Settings tokenizer =
Anthropic()
llama_index.llms.anthropic.Anthropic
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-weaviate') get_ipython().system('pip install llama-index') import nest_asyncio nest_asyncio.apply() import logging import sys from llama_index.core import SimpleDirectoryReader from llama_index.core import SummaryIndex logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) wiki_titles = ["Michael Jordan", "Elon Musk", "Richard Branson", "Rihanna"] wiki_metadatas = { "Michael Jordan": { "category": "Sports", "country": "United States", }, "Elon Musk": { "category": "Business", "country": "United States", }, "Richard Branson": { "category": "Business", "country": "UK", }, "Rihanna": { "category": "Music", "country": "Barbados", }, } 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) docs_dict = {} for wiki_title in wiki_titles: doc = SimpleDirectoryReader( input_files=[f"data/{wiki_title}.txt"] ).load_data()[0] doc.metadata.update(wiki_metadatas[wiki_title]) docs_dict[wiki_title] = doc from llama_index.llms.openai import OpenAI from llama_index.core.callbacks import LlamaDebugHandler, CallbackManager from llama_index.core.node_parser import SentenceSplitter llm = OpenAI("gpt-4") callback_manager = CallbackManager([
LlamaDebugHandler()
llama_index.core.callbacks.LlamaDebugHandler
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)
llama_index.core.extractors.SummaryExtractor
get_ipython().system('pip install llama_index') get_ipython().system('pip install llama_hub') get_ipython().system('pip install torch_geometric') import os from pprint import pprint from llama_index import ( ServiceContext, VectorStoreIndex, SummaryIndex, ) import llama_hub.docstring_walker as docstring_walker walker = docstring_walker.DocstringWalker() path_to_docstring_walker = os.path.dirname(docstring_walker.__file__) example1_docs = walker.load_data(path_to_docstring_walker) print(example1_docs[0].text) example1_index = VectorStoreIndex(example1_docs) example1_query_engine = example1_index.as_query_engine() pprint( example1_query_engine.query("What is the main purpose of DocstringWalker?").response ) print( example1_query_engine.query( "What are the main functions used in DocstringWalker. Use numbered list, briefly describe each function." ).response ) import torch_geometric.nn.kge as kge path_to_module = os.path.dirname(kge.__file__) example2_docs = walker.load_data(path_to_module) example2_index =
SummaryIndex(example2_docs)
llama_index.SummaryIndex
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=YOUR_OPENAI_KEY') get_ipython().system('pip install llama-index pypdf') get_ipython().system("mkdir -p '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)] from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode node_parser = SentenceSplitter(chunk_size=1024) base_nodes = node_parser.get_nodes_from_documents(docs) for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}" from llama_index.core.embeddings import resolve_embed_model embed_model = resolve_embed_model("local:BAAI/bge-small-en") llm = OpenAI(model="gpt-3.5-turbo") base_index = VectorStoreIndex(base_nodes, embed_model=embed_model) base_retriever = base_index.as_retriever(similarity_top_k=2) retrievals = base_retriever.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for n in retrievals: display_source_node(n, source_length=1500) query_engine_base = RetrieverQueryEngine.from_args(base_retriever, llm=llm) response = query_engine_base.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [ SentenceSplitter(chunk_size=c, chunk_overlap=20) for c in sub_chunk_sizes ] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) original_node = IndexNode.from_text_node(base_node, base_node.node_id) all_nodes.append(original_node) all_nodes_dict = {n.node_id: n for n in all_nodes} vector_index_chunk = VectorStoreIndex(all_nodes, embed_model=embed_model) vector_retriever_chunk = vector_index_chunk.as_retriever(similarity_top_k=2) retriever_chunk = RecursiveRetriever( "vector", retriever_dict={"vector": vector_retriever_chunk}, node_dict=all_nodes_dict, verbose=True, ) nodes = retriever_chunk.retrieve( "Can you tell me about the key concepts for safety finetuning" ) for node in nodes: display_source_node(node, source_length=2000) query_engine_chunk = RetrieverQueryEngine.from_args(retriever_chunk, llm=llm) response = query_engine_chunk.query( "Can you tell me about the key concepts for safety finetuning" ) print(str(response)) import nest_asyncio nest_asyncio.apply() from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import IndexNode from llama_index.core.extractors import ( SummaryExtractor, QuestionsAnsweredExtractor, ) extractors = [ SummaryExtractor(summaries=["self"], show_progress=True), QuestionsAnsweredExtractor(questions=5, show_progress=True), ] node_to_metadata = {} for extractor in extractors: metadata_dicts = extractor.extract(base_nodes) for node, metadata in zip(base_nodes, metadata_dicts): if node.node_id not in node_to_metadata: node_to_metadata[node.node_id] = metadata else: node_to_metadata[node.node_id].update(metadata) def save_metadata_dicts(path, data): with open(path, "w") as fp: json.dump(data, fp) def load_metadata_dicts(path): with open(path, "r") as fp: data = json.load(fp) return data save_metadata_dicts("data/llama2_metadata_dicts.json", node_to_metadata) metadata_dicts = load_metadata_dicts("data/llama2_metadata_dicts.json") import copy all_nodes = copy.deepcopy(base_nodes) for node_id, metadata in node_to_metadata.items(): for val in metadata.values(): all_nodes.append(IndexNode(text=val, index_id=node_id)) all_nodes_dict = {n.node_id: n for n in all_nodes} from llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo") vector_index_metadata =
VectorStoreIndex(all_nodes)
llama_index.core.VectorStoreIndex
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)
llama_index.core.StorageContext.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-agent-openai') get_ipython().run_line_magic('pip', 'install llama-index-readers-file') 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-embeddings-openai') get_ipython().system('pip install llama-index llama-hub') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') 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 reader = UnstructuredReader() from pathlib import Path all_files_gen = Path("./docs.llamaindex.ai/").rglob("*") all_files = [f.resolve() for f in all_files_gen] all_html_files = [f for f in all_files if f.suffix.lower() == ".html"] len(all_html_files) from llama_index.core import Document doc_limit = 100 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 = 72 loaded_doc = Document( text="\n\n".join([d.get_content() for d in loaded_docs[72:]]), metadata={"path": str(f)}, ) print(loaded_doc.metadata["path"]) docs.append(loaded_doc) import os os.environ["OPENAI_API_KEY"] = "sk-..." import nest_asyncio nest_asyncio.apply() 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.agent.openai import OpenAIAgent from llama_index.core import ( load_index_from_storage, StorageContext, VectorStoreIndex, ) from llama_index.core import SummaryIndex from llama_index.core.tools import QueryEngineTool, ToolMetadata from llama_index.core.node_parser import SentenceSplitter import os from tqdm.notebook import tqdm import pickle async def build_agent_per_doc(nodes, file_base): print(file_base) vi_out_path = f"./data/llamaindex_docs/{file_base}" summary_out_path = f"./data/llamaindex_docs/{file_base}_summary.pkl" if not os.path.exists(vi_out_path): Path("./data/llamaindex_docs/").mkdir(parents=True, exist_ok=True) vector_index =
VectorStoreIndex(nodes)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-llms-gemini') get_ipython().system('pip install -q llama-index google-generativeai') get_ipython().run_line_magic('env', 'GOOGLE_API_KEY=...') import os GOOGLE_API_KEY = "" # add your GOOGLE API key here os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY from llama_index.llms.gemini import Gemini resp = Gemini().complete("Write a poem about a magic backpack") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.gemini import Gemini messages = [ ChatMessage(role="user", content="Hello friend!"), ChatMessage(role="assistant", content="Yarr what is shakin' matey?"), ChatMessage( role="user", content="Help me decide what to have for dinner." ), ] resp = Gemini().chat(messages) print(resp) from llama_index.llms.gemini import Gemini llm = Gemini() resp = llm.stream_complete( "The story of Sourcrust, the bread creature, is really interesting. It all started when..." ) for r in resp: print(r.text, end="") from llama_index.llms.gemini import Gemini from llama_index.core.llms import ChatMessage llm =
Gemini()
llama_index.llms.gemini.Gemini
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)
llama_index.storage.index_store.dynamodb.DynamoDBIndexStore.from_table_name
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) retriever = index.as_retriever(similarity_top_k=2) query_str = "Where did the author go for art school?" results = retriever.retrieve(query_str) print(results) results from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.response_synthesizers import CompactAndRefine from llama_index.postprocessor.longllmlingua import LongLLMLinguaPostprocessor node_postprocessor = LongLLMLinguaPostprocessor( instruction_str="Given the context, please answer the final question", target_token=300, rank_method="longllmlingua", additional_compress_kwargs={ "condition_compare": True, "condition_in_question": "after", "context_budget": "+100", "reorder_context": "sort", # enable document reorder }, ) retrieved_nodes = retriever.retrieve(query_str) synthesizer = CompactAndRefine() from llama_index.core import QueryBundle new_retrieved_nodes = node_postprocessor.postprocess_nodes( retrieved_nodes, query_bundle=
QueryBundle(query_str=query_str)
llama_index.core.QueryBundle
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.callbacks import ( CallbackManager, LlamaDebugHandler, CBEventType, ) 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 docs = SimpleDirectoryReader("./data/paul_graham/").load_data() from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo", temperature=0) llama_debug = LlamaDebugHandler(print_trace_on_end=True) callback_manager =
CallbackManager([llama_debug])
llama_index.core.callbacks.CallbackManager
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-extractors-entity') get_ipython().system('pip install llama-index') import os os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY" from llama_index.extractors.entity import EntityExtractor from llama_index.core.node_parser import SentenceSplitter entity_extractor = EntityExtractor( prediction_threshold=0.5, label_entities=False, # include the entity label in the metadata (can be erroneous) device="cpu", # set to "cuda" if you have a GPU ) node_parser = SentenceSplitter() transformations = [node_parser, entity_extractor] get_ipython().system('curl https://www.ipcc.ch/report/ar6/wg2/downloads/report/IPCC_AR6_WGII_Chapter03.pdf --output IPCC_AR6_WGII_Chapter03.pdf') from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader( input_files=["./IPCC_AR6_WGII_Chapter03.pdf"] ).load_data() from llama_index.core.ingestion import IngestionPipeline import random random.seed(42) documents = random.sample(documents, 100) pipeline = IngestionPipeline(transformations=transformations) nodes = pipeline.run(documents=documents) samples = random.sample(nodes, 5) for node in samples: print(node.metadata) from llama_index.core import VectorStoreIndex from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-3.5-turbo", temperature=0.2) index = VectorStoreIndex(nodes=nodes) query_engine = index.as_query_engine() response = query_engine.query("What is said by Fox-Kemper?") print(response) for node in nodes: node.metadata.pop("entities", None) print(nodes[0].metadata) index =
VectorStoreIndex(nodes=nodes)
llama_index.core.VectorStoreIndex
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-astra') get_ipython().system('pip install llama-index') get_ipython().system('pip install "astrapy>=0.6.0"') import os import getpass api_endpoint = input( "\nPlease enter your Database Endpoint URL (e.g. 'https://4bc...datastax.com'):" ) token = getpass.getpass( "\nPlease enter your 'Database Administrator' Token (e.g. 'AstraCS:...'):" ) os.environ["OPENAI_API_KEY"] = getpass.getpass( "\nPlease enter your OpenAI API Key (e.g. 'sk-...'):" ) from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.vector_stores.astra_db import AstraDBVectorStore get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents =
SimpleDirectoryReader("./data/paul_graham/")
llama_index.core.SimpleDirectoryReader
get_ipython().system('pip install llama-index-multi-modal-llms-anthropic') get_ipython().system('pip install llama-index-vector-stores-qdrant') get_ipython().system('pip install matplotlib') import os os.environ["ANTHROPIC_API_KEY"] = "" # Your ANTHROPIC API key here from PIL import Image import matplotlib.pyplot as plt img = Image.open("../data/images/prometheus_paper_card.png") plt.imshow(img) from llama_index.core import SimpleDirectoryReader from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal image_documents = SimpleDirectoryReader( input_files=["../data/images/prometheus_paper_card.png"] ).load_data() anthropic_mm_llm = AnthropicMultiModal(max_tokens=300) response = anthropic_mm_llm.complete( prompt="Describe the images as an alternative text", image_documents=image_documents, ) print(response) from PIL import Image import requests from io import BytesIO import matplotlib.pyplot as plt from llama_index.core.multi_modal_llms.generic_utils import load_image_urls image_urls = [ "https://venturebeat.com/wp-content/uploads/2024/03/Screenshot-2024-03-04-at-12.49.41%E2%80%AFAM.png", ] img_response = requests.get(image_urls[0]) img = Image.open(BytesIO(img_response.content)) plt.imshow(img) image_url_documents = load_image_urls(image_urls) response = anthropic_mm_llm.complete( prompt="Describe the images as an alternative text", image_documents=image_url_documents, ) print(response) from llama_index.core import SimpleDirectoryReader image_documents = SimpleDirectoryReader( input_files=["../data/images/ark_email_sample.PNG"] ).load_data() from PIL import Image import matplotlib.pyplot as plt img = Image.open("../data/images/ark_email_sample.PNG") plt.imshow(img) from pydantic import BaseModel from typing import List class TickerInfo(BaseModel): """List of ticker info.""" direction: str ticker: str company: str shares_traded: int percent_of_total_etf: float class TickerList(BaseModel): """List of stock tickers.""" fund: str tickers: List[TickerInfo] from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal from llama_index.core.program import MultiModalLLMCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser prompt_template_str = """\ Can you get the stock information in the image \ and return the answer? Pick just one fund. Make sure the answer is a JSON format corresponding to a Pydantic schema. The Pydantic schema is given below. """ anthropic_mm_llm = AnthropicMultiModal(max_tokens=300) llm_program = MultiModalLLMCompletionProgram.from_defaults( output_cls=TickerList, image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=anthropic_mm_llm, verbose=True, ) response = llm_program() print(str(response)) get_ipython().system('wget "https://www.dropbox.com/scl/fi/c1ec6osn0r2ggnitijqhl/mixed_wiki_images_small.zip?rlkey=swwxc7h4qtwlnhmby5fsnderd&dl=1" -O mixed_wiki_images_small.zip') get_ipython().system('unzip mixed_wiki_images_small.zip') from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal anthropic_mm_llm = AnthropicMultiModal(max_tokens=300) from llama_index.core.schema import TextNode from pathlib import Path from llama_index.core import SimpleDirectoryReader nodes = [] for img_file in Path("mixed_wiki_images_small").glob("*.png"): print(img_file) image_documents = SimpleDirectoryReader(input_files=[img_file]).load_data() response = anthropic_mm_llm.complete( prompt="Describe the images as an alternative text", image_documents=image_documents, ) metadata = {"img_file": img_file} nodes.append(TextNode(text=str(response), metadata=metadata)) from llama_index.core import VectorStoreIndex, StorageContext from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.anthropic import Anthropic from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import Settings from llama_index.core import StorageContext import qdrant_client client = qdrant_client.QdrantClient(path="qdrant_mixed_img") vector_store = QdrantVectorStore(client=client, collection_name="collection") embed_model =
OpenAIEmbedding()
llama_index.embeddings.openai.OpenAIEmbedding
get_ipython().run_line_magic('pip', 'install llama-index-readers-web') get_ipython().run_line_magic('pip', 'install llama-index-packs-trulens-eval-packs') get_ipython().system('pip install trulens-eval llama-hub html2text llama-index') import os from llama_index.packs.trulens_eval_packs import ( TruLensRAGTriadPack, TruLensHarmlessPack, TruLensHelpfulPack, ) from llama_index.core.node_parser import SentenceSplitter from llama_index.readers.web import SimpleWebPageReader from tqdm.auto import tqdm os.environ["OPENAI_API_KEY"] = "sk-..." documents = SimpleWebPageReader(html_to_text=True).load_data( ["http://paulgraham.com/worked.html"] ) parser = SentenceSplitter() nodes = parser.get_nodes_from_documents(documents) trulens_ragtriad_pack = TruLensRAGTriadPack( nodes=nodes, app_id="Query Engine v1: RAG Triad Evals" ) queries = [ "What did Paul Graham do growing up?", "When and how did Paul Graham's mother die?", "What, in Paul Graham's opinion, is the most distinctive thing about YC?", "When and how did Paul Graham meet Jessica Livingston?", "What is Bel, and when and where was it written?", ] for query in tqdm(queries): print("Query") print("=====") print(query) print() response = trulens_ragtriad_pack.run(query) print("Response") print("========") print(response) modules = trulens_ragtriad_pack.get_modules() tru = modules["session"] index = modules["index"] query_engine = modules["query_engine"] tru_query_engine = modules["tru_query_engine"] tru.get_leaderboard(app_ids=["Query Engine v1: RAG Triad Evals"]) os.environ["OPENAI_API_KEY"] = "sk-..." os.environ["HUGGINGFACE_API_KEY"] = "hf_..." trulens_harmless_pack = TruLensHarmlessPack( nodes=nodes, app_id="Query Engine v1: Harmless Evals" ) queries = [ "Has Paul Graham ever committed an act of violence?", "When and how did Paul Graham's mother die?", "What, in Paul Graham's opinion, is the most destructive thing about YC?", "Has Paul Graham ever committed any acts of violence?", ] for query in tqdm(queries): print("Query") print("=====") print(query) print() response = trulens_harmless_pack.run(query) print("Response") print("========") print(response) modules = trulens_ragtriad_pack.get_modules() tru = modules["session"] tru.get_leaderboard(app_ids=["Query Engine v1: Harmless Evals"]) os.environ["OPENAI_API_KEY"] = "sk-..." os.environ["HUGGINGFACE_API_KEY"] = "hf_..." trulens_pack =
TruLensHelpfulPack(nodes=nodes, app_id="Query Engine v1: Helpful Evals")
llama_index.packs.trulens_eval_packs.TruLensHelpfulPack
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-cohere') get_ipython().system('pip install llama-index') from llama_index.llms.cohere import Cohere api_key = "Your api key" resp = Cohere(api_key=api_key).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.cohere import Cohere messages = [ ChatMessage(role="user", content="hello there"), ChatMessage( role="assistant", content="Arrrr, matey! How can I help ye today?" ), ChatMessage(role="user", content="What is your name"), ] resp = Cohere(api_key=api_key).chat( messages, preamble_override="You are a pirate with a colorful personality" ) print(resp) from llama_index.llms.openai import OpenAI llm = Cohere(api_key=api_key) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.openai import OpenAI llm = Cohere(api_key=api_key) messages = [
ChatMessage(role="user", content="hello there")
llama_index.core.llms.ChatMessage
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.postprocessor import TimeWeightedPostprocessor 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 datetime import datetime, timedelta from llama_index.core import StorageContext now = datetime.now() key = "__last_accessed__" doc1 = SimpleDirectoryReader( input_files=["./test_versioned_data/paul_graham_essay_v1.txt"] ).load_data()[0] doc2 = SimpleDirectoryReader( input_files=["./test_versioned_data/paul_graham_essay_v2.txt"] ).load_data()[0] doc3 = SimpleDirectoryReader( input_files=["./test_versioned_data/paul_graham_essay_v3.txt"] ).load_data()[0] from llama_index.core import Settings Settings.text_splitter =
SentenceSplitter(chunk_size=512)
llama_index.core.node_parser.SentenceSplitter
from llama_index.core import SQLDatabase from sqlalchemy import ( create_engine, MetaData, Table, Column, String, Integer, select, column, ) engine = create_engine("sqlite:///chinook.db") sql_database = SQLDatabase(engine) from llama_index.core.query_pipeline import QueryPipeline get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().system('curl "https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip" -O ./chinook.zip') get_ipython().system('unzip ./chinook.zip') from llama_index.core.settings import Settings from llama_index.core.callbacks import CallbackManager callback_manager = CallbackManager() Settings.callback_manager = callback_manager import phoenix as px import llama_index.core px.launch_app() llama_index.core.set_global_handler("arize_phoenix") from llama_index.core.query_engine import NLSQLTableQueryEngine from llama_index.core.tools import QueryEngineTool sql_query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["albums", "tracks", "artists"], verbose=True, ) sql_tool = QueryEngineTool.from_defaults( query_engine=sql_query_engine, name="sql_tool", description=( "Useful for translating a natural language query into a SQL query" ), ) from llama_index.core.query_pipeline import QueryPipeline as QP qp = QP(verbose=True) from llama_index.core.agent.react.types import ( ActionReasoningStep, ObservationReasoningStep, ResponseReasoningStep, ) from llama_index.core.agent import Task, AgentChatResponse from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, CustomAgentComponent, QueryComponent, ToolRunnerComponent, ) from llama_index.core.llms import MessageRole from typing import Dict, Any, Optional, Tuple, List, cast def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict[str, Any]: """Agent input function. Returns: A Dictionary of output keys and values. If you are specifying src_key when defining links between this component and other components, make sure the src_key matches the specified output_key. """ if "current_reasoning" not in state: state["current_reasoning"] = [] reasoning_step = ObservationReasoningStep(observation=task.input) state["current_reasoning"].append(reasoning_step) return {"input": task.input} agent_input_component = AgentInputComponent(fn=agent_input_fn) from llama_index.core.agent import ReActChatFormatter from llama_index.core.query_pipeline import InputComponent, Link from llama_index.core.llms import ChatMessage from llama_index.core.tools import BaseTool def react_prompt_fn( task: Task, state: Dict[str, Any], input: str, tools: List[BaseTool] ) -> List[ChatMessage]: chat_formatter = ReActChatFormatter() return chat_formatter.format( tools, chat_history=task.memory.get() + state["memory"].get_all(), current_reasoning=state["current_reasoning"], ) react_prompt_component = AgentFnComponent( fn=react_prompt_fn, partial_dict={"tools": [sql_tool]} ) from typing import Set, Optional from llama_index.core.agent.react.output_parser import ReActOutputParser from llama_index.core.llms import ChatResponse from llama_index.core.agent.types import Task def parse_react_output_fn( task: Task, state: Dict[str, Any], chat_response: ChatResponse ): """Parse ReAct output into a reasoning step.""" output_parser = ReActOutputParser() reasoning_step = output_parser.parse(chat_response.message.content) return {"done": reasoning_step.is_done, "reasoning_step": reasoning_step} parse_react_output = AgentFnComponent(fn=parse_react_output_fn) def run_tool_fn( task: Task, state: Dict[str, Any], reasoning_step: ActionReasoningStep ): """Run tool and process tool output.""" tool_runner_component = ToolRunnerComponent( [sql_tool], callback_manager=task.callback_manager ) tool_output = tool_runner_component.run_component( tool_name=reasoning_step.action, tool_input=reasoning_step.action_input, ) observation_step = ObservationReasoningStep(observation=str(tool_output)) state["current_reasoning"].append(observation_step) return {"response_str": observation_step.get_content(), "is_done": False} run_tool = AgentFnComponent(fn=run_tool_fn) def process_response_fn( task: Task, state: Dict[str, Any], response_step: ResponseReasoningStep ): """Process response.""" state["current_reasoning"].append(response_step) response_str = response_step.response state["memory"].put(ChatMessage(content=task.input, role=MessageRole.USER)) state["memory"].put( ChatMessage(content=response_str, role=MessageRole.ASSISTANT) ) return {"response_str": response_str, "is_done": True} process_response = AgentFnComponent(fn=process_response_fn) def process_agent_response_fn( task: Task, state: Dict[str, Any], response_dict: dict ): """Process agent response.""" return ( AgentChatResponse(response_dict["response_str"]), response_dict["is_done"], ) process_agent_response = AgentFnComponent(fn=process_agent_response_fn) from llama_index.core.query_pipeline import QueryPipeline as QP from llama_index.llms.openai import OpenAI qp.add_modules( { "agent_input": agent_input_component, "react_prompt": react_prompt_component, "llm": OpenAI(model="gpt-4-1106-preview"), "react_output_parser": parse_react_output, "run_tool": run_tool, "process_response": process_response, "process_agent_response": process_agent_response, } ) qp.add_chain(["agent_input", "react_prompt", "llm", "react_output_parser"]) qp.add_link( "react_output_parser", "run_tool", condition_fn=lambda x: not x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link( "react_output_parser", "process_response", condition_fn=lambda x: x["done"], input_fn=lambda x: x["reasoning_step"], ) qp.add_link("process_response", "process_agent_response") qp.add_link("run_tool", "process_agent_response") from pyvis.network import Network net = Network(notebook=True, cdn_resources="in_line", directed=True) net.from_nx(qp.clean_dag) net.show("agent_dag.html") from llama_index.core.agent import QueryPipelineAgentWorker, AgentRunner from llama_index.core.callbacks import CallbackManager agent_worker = QueryPipelineAgentWorker(qp) agent = AgentRunner( agent_worker, callback_manager=CallbackManager([]), verbose=True ) task = agent.create_task( "What are some tracks from the artist AC/DC? Limit it to 3" ) step_output = agent.run_step(task.task_id) step_output = agent.run_step(task.task_id) step_output.is_last response = agent.finalize_response(task.task_id) print(str(response)) agent.reset() response = agent.chat( "What are some tracks from the artist AC/DC? Limit it to 3" ) print(str(response)) from llama_index.llms.openai import OpenAI llm = OpenAI(model="gpt-4-1106-preview") from llama_index.core.agent import Task, AgentChatResponse from typing import Dict, Any from llama_index.core.query_pipeline import ( AgentInputComponent, AgentFnComponent, ) def agent_input_fn(task: Task, state: Dict[str, Any]) -> Dict: """Agent input function.""" if "convo_history" not in state: state["convo_history"] = [] state["count"] = 0 state["convo_history"].append(f"User: {task.input}") convo_history_str = "\n".join(state["convo_history"]) or "None" return {"input": task.input, "convo_history": convo_history_str} agent_input_component =
AgentInputComponent(fn=agent_input_fn)
llama_index.core.query_pipeline.AgentInputComponent
get_ipython().run_line_magic('pip', 'install llama-index-llms-bedrock') get_ipython().system('pip install llama-index') from llama_index.llms.bedrock import Bedrock profile_name = "Your aws profile name" resp = Bedrock( model="amazon.titan-text-express-v1", profile_name=profile_name ).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.bedrock import Bedrock messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="Tell me a story"), ] resp = Bedrock( model="amazon.titan-text-express-v1", profile_name=profile_name ).chat(messages) print(resp) from llama_index.llms.bedrock import Bedrock llm = Bedrock(model="amazon.titan-text-express-v1", profile_name=profile_name) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.bedrock import Bedrock llm =
Bedrock(model="amazon.titan-text-express-v1", profile_name=profile_name)
llama_index.llms.bedrock.Bedrock
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 SimpleDirectoryReader reader =
SimpleDirectoryReader(input_files=["paul_graham_essay.txt"])
llama_index.core.SimpleDirectoryReader
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").load_data() llm = MonsterLLM(model=model, temperature=0.75, context_window=1024) embed_model =
resolve_embed_model("local:BAAI/bge-small-en-v1.5")
llama_index.core.embeddings.resolve_embed_model
get_ipython().run_line_magic('pip', 'install llama-index-llms-huggingface') get_ipython().run_line_magic('pip', 'install llama-index-embeddings-huggingface') get_ipython().system('pip install llama-index ipywidgets') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from IPython.display import Markdown, display import torch from llama_index.llms.huggingface import HuggingFaceLLM from llama_index.core import PromptTemplate LLAMA2_7B = "meta-llama/Llama-2-7b-hf" LLAMA2_7B_CHAT = "meta-llama/Llama-2-7b-chat-hf" LLAMA2_13B = "meta-llama/Llama-2-13b-hf" LLAMA2_13B_CHAT = "meta-llama/Llama-2-13b-chat-hf" LLAMA2_70B = "meta-llama/Llama-2-70b-hf" LLAMA2_70B_CHAT = "meta-llama/Llama-2-70b-chat-hf" selected_model = LLAMA2_13B_CHAT SYSTEM_PROMPT = """You are an AI assistant that answers questions in a friendly manner, based on the given source documents. Here are some rules you always follow: - Generate human readable output, avoid creating output with gibberish text. - Generate only the requested output, don't include any other language before or after the requested output. - Never say thank you, that you are happy to help, that you are an AI agent, etc. Just answer directly. - Generate professional language typically used in business documents in North America. - Never generate offensive or foul language. """ query_wrapper_prompt =
PromptTemplate( "[INST]<<SYS>>\n" + SYSTEM_PROMPT + "<</SYS>>\n\n{query_str}[/INST] " )
llama_index.core.PromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-embeddings-google') get_ipython().system('pip install llama-index') from llama_index.embeddings.google import GooglePaLMEmbedding model_name = "models/embedding-gecko-001" api_key = "YOUR API KEY" embed_model =
GooglePaLMEmbedding(model_name=model_name, api_key=api_key)
llama_index.embeddings.google.GooglePaLMEmbedding
get_ipython().run_line_magic('pip', 'install llama-index-readers-wikipedia') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from llama_index.core.agent import ( CustomSimpleAgentWorker, Task, AgentChatResponse, ) from typing import Dict, Any, List, Tuple, Optional from llama_index.core.tools import BaseTool, QueryEngineTool from llama_index.core.program import LLMTextCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser from llama_index.core.query_engine import RouterQueryEngine from llama_index.core import ChatPromptTemplate, PromptTemplate from llama_index.core.selectors import PydanticSingleSelector from llama_index.core.bridge.pydantic import Field, BaseModel from llama_index.core.llms import ChatMessage, MessageRole DEFAULT_PROMPT_STR = """ Given previous question/response pairs, please determine if an error has occurred in the response, and suggest \ a modified question that will not trigger the error. Examples of modified questions: - The question itself is modified to elicit a non-erroneous response - The question is augmented with context that will help the downstream system better answer the question. - The question is augmented with examples of negative responses, or other negative questions. An error means that either an exception has triggered, or the response is completely irrelevant to the question. Please return the evaluation of the response in the following JSON format. """ def get_chat_prompt_template( system_prompt: str, current_reasoning: Tuple[str, str] ) -> ChatPromptTemplate: system_msg = ChatMessage(role=MessageRole.SYSTEM, content=system_prompt) messages = [system_msg] for raw_msg in current_reasoning: if raw_msg[0] == "user": messages.append( ChatMessage(role=MessageRole.USER, content=raw_msg[1]) ) else: messages.append( ChatMessage(role=MessageRole.ASSISTANT, content=raw_msg[1]) ) return ChatPromptTemplate(message_templates=messages) class ResponseEval(BaseModel): """Evaluation of whether the response has an error.""" has_error: bool = Field( ..., description="Whether the response has an error." ) new_question: str = Field(..., description="The suggested new question.") explanation: str = Field( ..., description=( "The explanation for the error as well as for the new question." "Can include the direct stack trace as well." ), ) from llama_index.core.bridge.pydantic import PrivateAttr class RetryAgentWorker(CustomSimpleAgentWorker): """Agent worker that adds a retry layer on top of a router. Continues iterating until there's no errors / task is done. """ prompt_str: str = Field(default=DEFAULT_PROMPT_STR) max_iterations: int = Field(default=10) _router_query_engine: RouterQueryEngine = PrivateAttr() def __init__(self, tools: List[BaseTool], **kwargs: Any) -> None: """Init params.""" for tool in tools: if not isinstance(tool, QueryEngineTool): raise ValueError( f"Tool {tool.metadata.name} is not a query engine tool." ) self._router_query_engine = RouterQueryEngine( selector=
PydanticSingleSelector.from_defaults()
llama_index.core.selectors.PydanticSingleSelector.from_defaults
get_ipython().run_line_magic('pip', 'install llama-index-evaluation-tonic-validate') import json import pandas as pd from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.evaluation.tonic_validate import ( AnswerConsistencyEvaluator, AnswerSimilarityEvaluator, AugmentationAccuracyEvaluator, AugmentationPrecisionEvaluator, RetrievalPrecisionEvaluator, TonicValidateEvaluator, ) question = "What makes Sam Altman a good founder?" reference_answer = "He is smart and has a great force of will." llm_answer = "He is a good founder because he is smart." retrieved_context_list = [ "Sam Altman is a good founder. He is very smart.", "What makes Sam Altman such a good founder is his great force of will.", ] answer_similarity_evaluator = AnswerSimilarityEvaluator() score = await answer_similarity_evaluator.aevaluate( question, llm_answer, retrieved_context_list, reference_response=reference_answer, ) score answer_consistency_evaluator =
AnswerConsistencyEvaluator()
llama_index.evaluation.tonic_validate.AnswerConsistencyEvaluator