File size: 5,421 Bytes
aba14b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aef499a
0641f61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aba14b1
 
 
 
 
 
 
 
 
 
 
 
 
f040e7b
0641f61
f040e7b
aba14b1
 
 
 
 
 
 
 
 
 
983db37
f040e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aba14b1
e24027c
 
aba14b1
f040e7b
aba14b1
 
f040e7b
 
 
 
 
aba14b1
 
 
 
f040e7b
 
 
 
 
aba14b1
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# Importacion de Librerias
import os
import openai
from llama_index.core import SimpleDirectoryReader, ServiceContext, VectorStoreIndex
from llama_index.core import (
    SimpleDirectoryReader,
    VectorStoreIndex,
    ServiceContext,
    StorageContext,
    Response,
    Document,
    load_index_from_storage
)
from llama_index.llms.openai import OpenAI
import gradio as gr
from gradio import components
import textwrap
import datetime
from llama_index.core import Settings
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.tools import RetrieverTool
from llama_index.core.selectors import LLMSingleSelector, LLMMultiSelector
from llama_index.core.selectors import (
    PydanticMultiSelector,
    PydanticSingleSelector,
)
from llama_index.core.retrievers import (
    BaseRetriever,
    VectorIndexRetriever,
    KGTableRetriever,
    RouterRetriever
)
from llama_index.core import get_response_synthesizer
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.prompts import PromptTemplate
from llama_index.core import QueryBundle
from llama_index.core.schema import NodeWithScore
from llama_index.core.postprocessor import SentenceTransformerRerank
from typing import List

openai.api_key = os.environ.get('openai_key')
os.environ["OPENAI_API_KEY"] = os.environ.get('openai_key')


# Cargar modelo
exec(os.environ.get('storage_context'))



### Inicio context ###

# load index
system_prompt = """Eres el asistente virtual de la empresa Pharma.IA, responde las consultas como un experto en fabricacion de medicamentos, validacion de software e inteligencia artificial. Responder en español y en forma breve. 
Cuando no tengas la respuesta indica al usuario que consulte a info@pharma-ia.com.ar. Consulta:
"""
### Fin context ###



import gradio as gr
from gradio import components
import textwrap


# Definir la interfaz de usuario con Gradio
with gr.Blocks(theme='sudeepshouche/minimalist') as demo:
    chat_history = []
    chat_history_engine = []
       


    def refresh(chat_history):
        global kg_data
        global chat_history_engine
        kg_data = []
        chat_history_engine = []
        chat_history = [[None, None]]
        gr.Info("¡Listo! Ya puedes seguir chateando.")
        return chat_history


    def summarize_assistant_messages(chat_history: List[ChatMessage]) -> List[ChatMessage]:
        # Encontrar la anteúltima respuesta del asistente
        assistant_messages = [msg for msg in chat_history if msg.role == MessageRole.ASSISTANT]
        if len(assistant_messages) < 2:
            return chat_history  # No hay suficientes mensajes del asistente para resumir
    
        anteultima_respuesta = assistant_messages[-2]
    
        # Usar GPT-3.5 para generar un resumen de la anteúltima respuesta del asistente
        prompt = Prompt(f"Responder SOLO con un resumen completo pero más corto del siguiente texto: \n\n{anteultima_respuesta.content}")
        llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)
        response = llm.predict(prompt)
    
        # Crear un nuevo ChatMessage con el resumen como contenido y el rol de asistente
        summarized_message = ChatMessage(content=response, role=MessageRole.ASSISTANT)
    
        # Reconstruir el historial de chat reemplazando la anteúltima respuesta del asistente con el resumen
        new_chat_history = [msg if msg != anteultima_respuesta else summarized_message for msg in chat_history]
    
        return new_chat_history
        
    
    def respond(message, chat_history):      
        global chat_history_engine
        global result_metadata
 
        # Si chat_history está vacío, inicialízalo con el mensaje del usuario actual
        if not chat_history:  
            chat_history = [[message, ""]]  
        else:
            # Si chat_history no está vacío, agrega el mensaje actual al final de la lista
            chat_history.append([message, ""])

        chat_history_engine = summarize_assistant_messages(chat_history_engine)
        #chat_history_engine.append(ChatMessage(role=MessageRole.USER, content=message))   
        response = chat_engine.stream_chat(message, chat_history=chat_history_engine)
      
          
        for text in response.response_gen:
            chat_history[-1][1] += text  # Agrega el texto de respuesta al último mensaje en chat_history
            yield "", chat_history

        print("----------")
        print(memory.get_all())



            
    gr.Markdown("""
    # Asistente Pharma.IA
    Realiza tus consultas sobre nuestras actividades y servicios
    """)
    
    with gr.Row():
        with gr.Column():
            chatbot = gr.Chatbot(show_label=False, show_copy_button=True, ) #layout="panel"             
            pregunta = gr.Textbox(show_label=False, autofocus=True, placeholder="Realiza tu consulta...")
            pregunta.submit(respond, [pregunta, chatbot], [pregunta, chatbot])
                
            with gr.Row():                    
                btn_send = gr.Button(value="Preguntar", variant="primary")
                clear = gr.Button(value="Limpiar")


    btn_send.click(respond, [pregunta, chatbot], [pregunta, chatbot])

    clear.click(refresh, inputs=[chatbot], outputs=[chatbot])
    
    #response.change(visible, [], [btn_graph])


demo.queue()
demo.launch()