dioarafl commited on
Commit
276845e
·
verified ·
1 Parent(s): 2798b74

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex, LLMPredictor, ServiceContext, PromptHelper
3
+ import gradio as gr
4
+
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
+
11
+ # Get Hugging Face API key from environment variable
12
+ hf_api_key = os.getenv("HF_API_KEY")
13
+
14
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
15
+ headers = {"Authorization": f"Bearer {hf_api_key}"}
16
+
17
+
18
+ def query(payload):
19
+ response = requests.post(API_URL, headers=headers, json=payload)
20
+ return response.json()
21
+
22
+ def init_index(directory_path):
23
+ # Model parameters
24
+ max_input_size = 4096
25
+ num_outputs = 512
26
+ max_chunk_overlap = 20
27
+ chunk_size_limit = 600
28
+
29
+ # Prompt helper and predictor
30
+ prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)
31
+ llm_predictor = LLMPredictor(llm=query)
32
+
33
+ # Read documents from the "docs" folder
34
+ documents = SimpleDirectoryReader(directory_path).load_data()
35
+
36
+ # Initialize index with document data
37
+ service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)
38
+ index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context)
39
+
40
+ # Save the created index
41
+ index.save_to_disk('index.json')
42
+
43
+ return index
44
+
45
+ def chatbot(input_text):
46
+ # Load index
47
+ index = GPTSimpleVectorIndex.load_from_disk('index.json')
48
+
49
+ # Get response for the question
50
+ response = index.query(input_text, response_mode="compact")
51
+
52
+ return response.response
53
+
54
+ # Create index
55
+ init_index("docs")
56
+
57
+ # Create UI interface to interact with the Hugging Face model
58
+ iface = gr.Interface(fn=chatbot,
59
+ inputs=gr.components.Textbox(lines=7, placeholder="Enter your question here"),
60
+ outputs="text",
61
+ title="Frost AI ChatBot: Your Knowledge Companion Powered by Hugging Face",
62
+ description="Ask any question about rahasak research papers",
63
+ allow_screenshot=True)
64
+ iface.launch(share=True)