iShare commited on
Commit
a6a2aba
1 Parent(s): 7b76a1e

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +51 -0
main.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from fastapi import FastAPI, Request, HTTPException
4
+ from langchain.document_loaders import WebBaseLoader
5
+ from langchain.chains.summarize import load_summarize_chain
6
+ from langchain import HuggingFaceHub
7
+ from huggingface_hub import InferenceClient
8
+
9
+ load_dotenv()
10
+ hf_token = os.environ.get('HUGGINGFACEHUB_API_TOKEN')
11
+ #starchat_repo_id = os.environ.get('starchat_repo_id')
12
+ #repo_id=os.environ.get('repo_id')
13
+ #port = os.getenv('port')
14
+
15
+ llm = HuggingFaceHub(repo_id=starchat_repo_id, # for StarChat
16
+ huggingfacehub_api_token=hf_token,
17
+ model_kwargs={"min_length": 512, # for StarChat
18
+ "max_new_tokens": 1024, "do_sample": True, # for StarChat
19
+ "temperature": 0.01,
20
+ "top_k": 50,
21
+ "top_p": 0.95, "eos_token_id": 49155})
22
+ chain = load_summarize_chain(llm, chain_type="stuff")
23
+
24
+ app = FastAPI()
25
+
26
+ @app.post('/')
27
+ async def home_api(request: Request):
28
+ data = await request.json()
29
+ user_query = data['user_question']
30
+ print(user_query)
31
+ return {"Message": "FastAPI Home API Deploy Success on HF"}
32
+
33
+ @app.post('/api/chat')
34
+ async def chat(request: Request):
35
+ data = await request.json()
36
+ user_query = data['user_question']
37
+ print(user_query)
38
+ if user_query.strip() != "":
39
+ try:
40
+ loader = WebBaseLoader(user_query)
41
+ print(user_query)
42
+ docs = loader.load()
43
+ result = chain.run(docs)
44
+ print("AI Summarization: " + result)
45
+ return {'response': result}
46
+ except Exception as e:
47
+ err_msg = "Wrong URL or URL not parsable."
48
+ print(err_msg)
49
+ raise HTTPException(status_code=400, detail=err_msg)
50
+ else:
51
+ raise HTTPException(status_code=400, detail="Invalid user question")