Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,88 @@
|
|
1 |
-
|
2 |
-
from
|
|
|
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 |
-
|
11 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
29 |
|
30 |
-
|
31 |
-
|
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 |
-
|
40 |
-
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
"""
|
43 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
44 |
-
"""
|
45 |
-
demo = gr.ChatInterface(
|
46 |
-
respond,
|
47 |
-
additional_inputs=[
|
48 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
49 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
50 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
51 |
-
gr.Slider(
|
52 |
-
minimum=0.1,
|
53 |
-
maximum=1.0,
|
54 |
-
value=0.95,
|
55 |
-
step=0.05,
|
56 |
-
label="Top-p (nucleus sampling)",
|
57 |
-
),
|
58 |
-
],
|
59 |
-
)
|
60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
if __name__ == "__main__":
|
63 |
demo.launch()
|
|
|
1 |
+
from langchain.chains import ConversationalRetrievalChain
|
2 |
+
from langchain.memory import ConversationBufferMemory, ConversationSummaryMemory
|
3 |
+
from langchain.chat_models import ChatOpenAI
|
4 |
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
|
7 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
8 |
+
from langchain.vectorstores import Chroma
|
9 |
|
10 |
+
import os
|
11 |
+
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
from langchain.schema import (
|
15 |
+
AIMessage,
|
16 |
+
HumanMessage,
|
17 |
+
SystemMessage
|
18 |
+
)
|
19 |
|
20 |
+
from langchain.prompts import ChatPromptTemplate
|
21 |
+
from langchain.prompts.chat import SystemMessagePromptTemplate, HumanMessagePromptTemplate
|
22 |
|
23 |
+
#embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
|
24 |
+
embeddings = OpenAIEmbeddings(api_key='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')
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
#vectordb=Chroma.from_documents(document_chunks,embedding=embeddings, persist_directory='./ai_vocacional_v2')
|
27 |
+
vectordb = Chroma(persist_directory="./ai_vocacional_v2", embedding_function=embeddings)
|
28 |
|
29 |
+
llm=ChatOpenAI(temperature=0, model_name='gpt-4o-mini', api_key='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')
|
30 |
+
|
31 |
+
memory = ConversationBufferMemory(
|
32 |
+
memory_key='chat_history',
|
33 |
+
return_messages=True)
|
34 |
+
|
35 |
+
general_system_template = r"""
|
36 |
+
Eres un asistente AI avanzado especializado en asesorar a alumnos con su ingreso a la universidad.
|
37 |
+
Toma los siguientes documentos de contexto {context} y responde 煤nicamente basado en este contexto.
|
38 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
general_user_template = "Pregunta:```{question}```"
|
41 |
+
messages = [
|
42 |
+
SystemMessagePromptTemplate.from_template(general_system_template),
|
43 |
+
HumanMessagePromptTemplate.from_template(general_user_template)
|
44 |
+
]
|
45 |
+
qa_prompt = ChatPromptTemplate.from_messages( messages )
|
46 |
+
|
47 |
+
pdf_qa = ConversationalRetrievalChain.from_llm(
|
48 |
+
llm = llm,
|
49 |
+
retriever=vectordb.as_retriever(search_kwargs={'k':16})
|
50 |
+
, combine_docs_chain_kwargs={'prompt': qa_prompt},
|
51 |
+
memory = memory#,max_tokens_limit=4000
|
52 |
+
)
|
53 |
+
|
54 |
+
#Clarification: Si la pregunta del usuario es vaga o le faltan detalles importantes para dar una respuseta, debes realizar preguntas de clarificaci贸n para entender sus necesidades y darle la asistencia adecuada.
|
55 |
+
#Constraints: Debes responder solamente con la informacion disponible y saludar solo una vez. En caso no tengas una respuesta o no est茅s seguro, no inventes respuesta.
|
56 |
+
|
57 |
+
import gradio as gr
|
58 |
+
# Define chat interface
|
59 |
+
with gr.Blocks() as demo:
|
60 |
+
chatbot = gr.Chatbot()
|
61 |
+
msg = gr.Textbox()
|
62 |
+
clear = gr.Button("Clear")
|
63 |
+
chat_history = []
|
64 |
+
|
65 |
+
def user(query, chat_history):
|
66 |
+
print("User query:", query)
|
67 |
+
print("Chat history:", chat_history)
|
68 |
+
|
69 |
+
# Convert chat history to list of tuples
|
70 |
+
chat_history_tuples = []
|
71 |
+
for message in chat_history:
|
72 |
+
chat_history_tuples.append((message[0], message[1]))
|
73 |
+
|
74 |
+
# Get result from QA chain
|
75 |
+
result = pdf_qa({"question": query})#, "chat_history": chat_history_tuples})
|
76 |
+
|
77 |
+
# Append user message and response to chat history
|
78 |
+
chat_history.append((query, result["answer"]))
|
79 |
+
print("Updated chat history:", chat_history)
|
80 |
+
|
81 |
+
return gr.update(value=""), chat_history
|
82 |
+
|
83 |
+
|
84 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False)
|
85 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
86 |
|
87 |
if __name__ == "__main__":
|
88 |
demo.launch()
|