Copain22 commited on
Commit
880fc9b
·
verified ·
1 Parent(s): 201fe87

update ap.py

Browse files
Files changed (1) hide show
  1. app.py +72 -50
app.py CHANGED
@@ -1,64 +1,86 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
38
 
39
- response += token
40
- yield response
 
41
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ import torch, os
2
  import gradio as gr
3
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
4
+ from llama_index.core.memory import ChatMemoryBuffer
5
+ from llama_index.llms.huggingface import HuggingFaceLLM
6
+ from llama_index.embeddings.langchain import LangchainEmbedding
7
+ from langchain.embeddings.huggingface import HuggingFaceEmbeddings
8
+ from llama_index.core import PromptTemplate
9
 
10
+ # ---------- 1. Load menu PDF ----------
11
+ docs = SimpleDirectoryReader(input_files=["cafeoneeleven.pdf"]).load_data()
12
 
13
+ # ---------- 2. LLM + embeddings ----------
14
+ SYSTEM_PROMPT = """
15
+ You are a friendly café assistant for Café Eleven. Your job is to:
16
+ 1. Greet the customer warmly
17
+ 2. Help them place their order
18
+ 3. Ask for pickup time
19
+ 4. Suggest add-ons/extras from our menu
20
+ 5. Confirm the complete order
 
21
 
22
+ Menu items are embedded in the document. Always:
23
+ - Be polite and professional
24
+ - Confirm order details clearly
25
+ - Suggest popular combinations
26
+ - Never make up items not in our menu
27
+ """
28
 
29
+ wrapper_prompt = PromptTemplate(
30
+ """<s>[INST] <<SYS>>
31
+ {system_prompt}
32
+ Current conversation:
33
+ {chat_history}
34
+ <</SYS>>
35
 
36
+ {query_str} [/INST]"""
37
+ )
38
 
39
+ llm = HuggingFaceLLM(
40
+ tokenizer_name="meta-llama/Llama-2-7b-chat-hf",
41
+ model_name="meta-llama/Llama-2-7b-chat-hf",
42
+ context_window=3900,
43
+ max_new_tokens=256,
44
+ generate_kwargs={"temperature": 0.2, "do_sample": True},
45
+ device_map="auto",
46
+ model_kwargs={"torch_dtype": torch.float16, "load_in_4bit": True},
47
+ system_prompt=SYSTEM_PROMPT,
48
+ query_wrapper_prompt=wrapper_prompt,
49
+ )
50
 
51
+ embed_model = LangchainEmbedding(
52
+ HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
53
+ )
54
 
55
+ Settings.llm = llm
56
+ Settings.embed_model = embed_model
57
+ Settings.chunk_size = 512
58
 
59
+ # ---------- 3. Build the chat engine ----------
60
+ memory = ChatMemoryBuffer.from_defaults(token_limit=2000)
61
+ index = VectorStoreIndex.from_documents(docs)
62
+ chat_engine = index.as_chat_engine(
63
+ chat_mode="condense_plus_context",
64
+ memory=memory,
65
+ system_prompt=SYSTEM_PROMPT,
 
 
 
 
 
 
 
 
 
 
66
  )
67
 
68
+ # ---------- 4. Gradio UI ----------
69
+ with gr.Blocks(title="Café Eleven Chat") as demo:
70
+ gr.Markdown("## ☕ Café Eleven Ordering Assistant \nType *quit* to end the chat.")
71
+ chatbot = gr.Chatbot()
72
+ user_txt = gr.Textbox(show_label=False, placeholder="Hi, I’d like a latte…")
73
+ clear = gr.Button("Clear")
74
+
75
+ def respond(message, chat_history):
76
+ if message.lower().strip() in {"quit", "exit", "done"}:
77
+ return "Thank you for your order! We'll see you soon.", chat_history
78
+ response = chat_engine.chat(message).response
79
+ chat_history.append((message, response))
80
+ return "", chat_history
81
+
82
+ user_txt.submit(respond, [user_txt, chatbot], [user_txt, chatbot])
83
+ clear.click(lambda: None, None, chatbot, queue=False)
84
 
85
  if __name__ == "__main__":
86
+ demo.queue(concurrency_count=3).launch()