Wmble/finalproject
0
1!pip install openai langchain llama_index==0.6.18 pypdf PyCryptodome gradio2 3from llama_index import StorageContext, ServiceContext, GPTVectorStoreIndex, LLMPredictor, PromptHelper, SimpleDirectoryReader, load_index_from_storage4from langchain.chat_models import ChatOpenAI5import gradio as gr6import sys7import os8import openai9 10# Set your API key as an environment variable.11os.environ['OPENAI_API_KEY'] = "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"12openai.organization = "org-fjp01yLcT3HhXZc5Qpl98j1k"13 14# Use your API key.15openai.api_key = os.getenv("OPENAI_API_KEY")16 17def create_service_context():18 19 #constraint parameters20 max_input_size = 409621 num_outputs = 70022 max_chunk_overlap = .523 chunk_size_limit = 80024 25 #allows the user to explicitly set certain constraint parameters26 prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)27 28 #LLMPredictor is a wrapper class around LangChain's LLMChain that allows easy integration into LlamaIndex29 #llm_predictor = LLMPredictor(llm=ChatOpenAI(temperature=0.5, model_name="gpt-3.5-turbo", max_tokens=num_outputs))30 llm_predictor = LLMPredictor(llm=ChatOpenAI(temperature=0.5, model_name="gpt-3.5-turbo", max_tokens=num_outputs))31 32 #constructs service_context33 service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)34 return service_context35 36def data_ingestion_indexing(directory_path):37 38 #loads data from the specified directory path39 documents = SimpleDirectoryReader(directory_path).load_data()40 41 #when first building the index42 index = GPTVectorStoreIndex.from_documents(43 documents, service_context=create_service_context()44 )45 46 #persist index to disk, default "storage" folder47 index.storage_context.persist()48 49 return index50 51def data_querying(input_text):52 53 #rebuild storage context54 storage_context = StorageContext.from_defaults(persist_dir="./storage")55 56 #loads index from storage57 index = load_index_from_storage(storage_context, service_context=create_service_context())58 59 #queries the index with the input text60 response = index.as_query_engine().query(input_text)61 62 return response.response63 64iface = gr.Interface(fn=data_querying,65 inputs=gr.components.Textbox(lines=7, label="What is your question?"),66 outputs="text",67 title="iCED Chat Bot")68 69#passes in data directory70index = data_ingestion_indexing("data")71 72iface.launch(share=True)