from llama_index import (
SimpleDirectoryReader,
Document,
StorageContext,
load_index_from_storage
)
from llama_index.node_parser import SentenceWindowNodeParser
from llama_index.llms import OpenAI
from llama_index.embeddings import OpenAIEmbedding
from llama_index import ServiceContext
from llama_index import VectorStoreIndex
from llama_index.indices.postprocessor import MetadataReplacementPostProcessor
from llama_index.indices.postprocessor import SentenceTransformerRerank
from llama_index.llms import OpenAI
for loading environment variables
from decouple import config
from trulens_eval import Feedback, Tru, TruLlama
from trulens_eval.feedback import Groundedness
from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens
with open(“./eval_questions.txt”, “r”) as eval_qn:
for qn in eval_qn:
qn_stripped = qn.strip()
eval_questions.append(qn_stripped)
def run_eval(eval_questions: List[str]):
for qn in eval_questions:
eval using context window
with tru_query_engine_recorder as recording:
sentence_window_engine.query(qn)
run_eval(eval_questions=eval_questions)
run dashboard
tru.run_dashboard()
from typing import List
from llama_index import (
Document,
VectorStoreIndex,
SimpleDirectoryReader,
ServiceContext,
)
from llama_index.retrievers import RecursiveRetriever
from llama_index.query_engine import RetrieverQueryEngine
from llama_index.node_parser import SimpleNodeParser
from llama_index.embeddings import OpenAIEmbedding
from llama_index.schema import IndexNode
from llama_index.llms import OpenAI
for loading environment variables
from decouple import config
import os
from trulens_eval import Feedback, Tru, TruLlama
from trulens_eval.feedback import Groundedness
from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens
for idx, node in enumerate(base_nodes):
node.id_ = f"node-{idx}“
create parent child documents
sub_chunk_sizes = [128, 256, 512]
sub_node_parsers = [
SimpleNodeParser.from_defaults(chunk_size=c, chunk_overlap=0) 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)
with open(“./eval_questions.txt”, “r”) as eval_qn:
for qn in eval_qn:
qn_stripped = qn.strip()
eval_questions.append(qn_stripped)
def run_eval(eval_questions: List[str]):
for qn in eval_questions:
eval using context window
with tru_query_engine_recorder as recording:
query_engine_chunk.query(qn)
run_eval(eval_questions=eval_questions)
run dashboard
tru.run_dashboard()
from typing import List
from llama_index import (
StorageContext,
VectorStoreIndex,
SimpleDirectoryReader,
ServiceContext,
load_index_from_storage
)
from llama_index.node_parser import SimpleNodeParser
from llama_index.embeddings import OpenAIEmbedding
from llama_index.llms import OpenAI
from llama_index.query_engine import RetrieverQueryEngine
from trulens_eval import Feedback, Tru, TruLlama
from trulens_eval.feedback import Groundedness
from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens
with open(“./eval_questions.txt”, “r”) as eval_qn:
for qn in eval_qn:
qn_stripped = qn.strip()
eval_questions.append(qn_stripped)
def run_eval(eval_questions: List[str]):
for qn in eval_questions:
eval using context window
with tru_query_engine_recorder as recording:
query_engine.query(qn)
run_eval(eval_questions=eval_questions)
run dashboard
tru.run_dashboard()
can you combine above three code into one streamlit app using advance oops technique, use streamlit tab to switch between code
To combine the three code samples into one advanced Streamlit application using object-oriented programming (OOP) techniques and Streamlit tabs, we can define a base class for shared functionality and then create subclass implementations for each of the specific indexing and query setups. Below is an example of how to structure such an application.
Please note that this code is only a schematic example to illustrate the OOP approach and will not run as is, due to its complexity and dependencies that would need to be properly set up for a real-world application.
import streamlit as st
import os
from typing import List
from decouple import config
# ... (other imports that your code requires)
# Set environment variables
os.environ["OPENAI_API_KEY"] = config("OPENAI_API_KEY")
# Define the base class for a general indexing and querying setup
class BaseIndexingQueryingSystem:
def __init__(self, input_dir: str, index_save_dir: str,
llm_model: str, temperature: float,
similarity_top_k: int, rerank_top_n: int):
self.input_dir = input_dir
self.index_save_dir = index_save_dir
self.llm_model = llm_model
self.temperature = temperature
self.similarity_top_k = similarity_top_k
self.rerank_top_n = rerank_top_n
def load_documents(self):
raise NotImplementedError()
def create_index(self):
raise NotImplementedError()
def create_query_engine(self):
raise NotImplementedError()
def run_eval(self, eval_questions: List[str]):
raise NotImplementedError()
def setup_tru_components(self):
# Common TRU component setup can be here
pass
def display_ui(self):
# Streamlit UI elements specific to this system
pass
# Define subclass implementations for each specific setup
class SentenceWindowIndexingQueryingSystem(BaseIndexingQueryingSystem):
# Override methods to provide functionality for sentence window indexing and querying
pass
class ChunkRetrieverIndexingQueryingSystem(BaseIndexingQueryingSystem):
# Override methods to provide functionality for chunk retriever indexing and querying
pass
class BasicRAGIndexingQueryingSystem(BaseIndexingQueryingSystem):
# Override methods to provide functionality for Basic RAG indexing and querying
pass
# Create instances of each subclass implementation
sentence_window_system = SentenceWindowIndexingQueryingSystem(...)
chunk_retriever_system = ChunkRetrieverIndexingQueryingSystem(...)
basic_rag_system = BasicRAGIndexingQueryingSystem(...)
# Define a function to render the tabs with switchable interfaces
def render_tabs(systems):
tab_labels = ["Sentence Window", "Chunk Retriever", "Basic RAG"]
tab_systems = systems
with st.tabs(tab_labels):
for i, system in zip(tab_labels, tab_systems):
with st.container():
st.header(f"{i} Query Interface")
system.display_ui()
# Main application
def main():
# Display UI to switch between configurations
systems = [sentence_window_system, chunk_retriever_system, basic_rag_system]
render_tabs(systems)
# ... any other Streamlit interaction code ...
if __name__ == "__main__":
main()
This example demonstrates how to integrate multiple setups into a single app while keeping the separate concerns modularized via OOP principles. Each subclass would implement its own version of the load_documents, create_index, create_query_engine, run_eval, and display_ui methods according to its specific functionality.
In the main() function, we instantiate the different system objects and then pass them to the render_tabs function to render the Streamlit UI tabs. Each tab will call the display_ui method of the corresponding system, which encapsulates the UI and functionality for that specific indexing/querying setup.
Remember to replace the ... with your actual implementation details and integrate your code as needed into the placeholder methods provided in the OOP structure. This code is intended to guide you toward the desired OOP Streamlit application organization and provide a framework for combining the three code samples you provided.