AmandaHydar commited on
Commit
cb6807e
·
1 Parent(s): 7eeb510

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from llama_index import (
4
+ GPTVectorStoreIndex,
5
+ SimpleDirectoryReader,
6
+ ServiceContext,
7
+ StorageContext,
8
+ LLMPredictor,
9
+ load_index_from_storage,
10
+ )
11
+ from langchain.chat_models import ChatOpenAI
12
+
13
+ index_name = "./saved_index"
14
+ documents_folder = "./documents"
15
+
16
+
17
+ @st.cache_resource
18
+ def initialize_index(index_name, documents_folder):
19
+ llm_predictor = LLMPredictor(
20
+ llm=ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
21
+ )
22
+ service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor)
23
+ if os.path.exists(index_name):
24
+ index = load_index_from_storage(
25
+ StorageContext.from_defaults(persist_dir=index_name),
26
+ service_context=service_context,
27
+ )
28
+ else:
29
+ documents = SimpleDirectoryReader(documents_folder).load_data()
30
+ index = GPTVectorStoreIndex.from_documents(
31
+ documents, service_context=service_context
32
+ )
33
+ index.storage_context.persist(persist_dir=index_name)
34
+
35
+ return index
36
+
37
+
38
+ @st.cache_data(max_entries=200, persist=True)
39
+ def query_index(_index, query_text):
40
+ if _index is None:
41
+ return "Please initialize the index!"
42
+ response = _index.as_query_engine().query(query_text)
43
+ return str(response)
44
+
45
+
46
+ st.title("PQL Chat Demo")
47
+ st.header("Welcome to the PQL Chat Demo")
48
+ st.write(
49
+ "Enter a query about Process Mining language PQL. You can check out the documentation [here](https://docs.celonis.com/en/pql---process-query-language.html). Your query will be answered using this documentation as context, using embeddings from text-ada-002 and LLM completions from gpt-3.5-turbo."
50
+ )
51
+
52
+ index = None
53
+ api_key = st.text_input("Enter your OpenAI API key here:", type="password")
54
+ if api_key:
55
+ os.environ["OPENAI_API_KEY"] = api_key
56
+ index = initialize_index(index_name, documents_folder)
57
+
58
+
59
+ if index is None:
60
+ st.warning("Please enter your api key first.")
61
+
62
+ text = st.text_input("Query text:", value="How would I query 'count of touchless invoices' ?")
63
+
64
+ if st.button("Run Query") and text is not None:
65
+ response = query_index(index, text)
66
+ st.markdown(response)
67
+
68
+ llm_col, embed_col = st.columns(2)
69
+ with llm_col:
70
+ st.markdown(
71
+ f"LLM Tokens Used: {index.service_context.llm_predictor._last_token_usage}"
72
+ )
73
+
74
+ with embed_col:
75
+ st.markdown(
76
+ f"Embedding Tokens Used: {index.service_context.embed_model._last_token_usage}"
77
+ )