Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,111 +1,127 @@
|
|
1 |
-
import requests
|
2 |
-
from langchain_openai import ChatOpenAI
|
3 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
4 |
-
from pydantic import BaseModel
|
5 |
-
import os
|
6 |
-
from langchain import hub
|
7 |
-
from pydantic import BaseModel
|
8 |
-
from langchain.agents import AgentExecutor, create_react_agent, tool
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
embeddings = HuggingFaceEmbeddings(
|
13 |
-
model_name="sentence-transformers/distiluse-base-multilingual-cased",
|
14 |
-
encode_kwargs={"normalize_embeddings": True},
|
15 |
-
)
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
class ConsultaAPI(BaseModel):
|
20 |
-
query: str
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from langchain_openai import ChatOpenAI
|
3 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
4 |
+
from pydantic import BaseModel
|
5 |
+
import os
|
6 |
+
from langchain import hub
|
7 |
+
from pydantic import BaseModel
|
8 |
+
from langchain.agents import AgentExecutor, create_react_agent, tool
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
embeddings = HuggingFaceEmbeddings(
|
13 |
+
model_name="sentence-transformers/distiluse-base-multilingual-cased",
|
14 |
+
encode_kwargs={"normalize_embeddings": True},
|
15 |
+
)
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
class ConsultaAPI(BaseModel):
|
20 |
+
query: str
|
21 |
+
|
22 |
+
@tool
|
23 |
+
def check_system_time(format: str = "%Y-%m-%d %H:%M:%S") -> str:
|
24 |
+
"""
|
25 |
+
Devuelve la hora actual del sistema en el formato especificado.
|
26 |
+
Sirve para saber la fecha y hora actual
|
27 |
+
Parámetros:
|
28 |
+
- format (str): El formato de la hora a devolver. Por defecto es "%Y-%m-%d %H:%M:%S", puedes cambiarlo según tus necesidades.
|
29 |
+
|
30 |
+
Retorna:
|
31 |
+
- str: La hora actual del sistema en el formato especificado.
|
32 |
+
"""
|
33 |
+
from datetime import datetime
|
34 |
+
|
35 |
+
current_time = datetime.now().strftime(format)
|
36 |
+
formatted_time = datetime.strptime(current_time, format)
|
37 |
+
return formatted_time
|
38 |
+
|
39 |
+
@tool
|
40 |
+
def consultar_db_via_api(query: str):
|
41 |
+
"""
|
42 |
+
Consulta la DB SQLite con una consulta puntual. Máximo puedes solicitar hasta 20 registros.
|
43 |
+
NO USES COMILLAS DOBLES AL INICIO Y AL FINAL DE LA CONSULTA.
|
44 |
+
|
45 |
+
|
46 |
+
Parámetros:
|
47 |
+
- query (str): La consulta SQL a ejecutar en la base de datos.
|
48 |
+
|
49 |
+
Retorna:
|
50 |
+
- dict: Los resultados de la consulta en formato JSON.
|
51 |
+
"""
|
52 |
+
try:
|
53 |
+
query = query.strip('"')
|
54 |
+
if query.endswith(";"):
|
55 |
+
query = query[:-1]
|
56 |
+
query = query.replace("'", "\\'")
|
57 |
+
format_query_json = {"query": query}
|
58 |
+
response = requests.post(
|
59 |
+
url="https://jairodanielmt-arduino-data-post.hf.space/execute",
|
60 |
+
json=format_query_json,
|
61 |
+
headers={"Content-Type": "application/json"},
|
62 |
+
)
|
63 |
+
response.raise_for_status()
|
64 |
+
data = response.json()
|
65 |
+
return data
|
66 |
+
except requests.exceptions.RequestException as e:
|
67 |
+
print(f"Error al consultar la API: {e}")
|
68 |
+
if e.response is not None:
|
69 |
+
print(e.response.text)
|
70 |
+
return None
|
71 |
+
|
72 |
+
|
73 |
+
prompt = hub.pull("hwchase17/react")
|
74 |
+
tools = [consultar_db_via_api,check_system_time]
|
75 |
+
|
76 |
+
llm = ChatOpenAI(
|
77 |
+
model="deepseek-chat",
|
78 |
+
base_url="https://api.deepseek.com",
|
79 |
+
temperature=0.3,
|
80 |
+
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
81 |
+
)
|
82 |
+
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
|
83 |
+
agent_executor = AgentExecutor(
|
84 |
+
agent=agent,
|
85 |
+
tools=tools,
|
86 |
+
verbose=True,
|
87 |
+
handle_parsing_errors=True,
|
88 |
+
max_iterations=20,
|
89 |
+
)
|
90 |
+
|
91 |
+
|
92 |
+
def ask_agent(consulta) -> str:
|
93 |
+
d = "Eres un asistente, tienes acceso a herramientas tools y tienes permitido ejecutar sentencias SQLite, la unica tabla existente es: la unica tabla tiene la siguiente estructura nombre de la tabla: sensor_data columnas (id INTEGER PK AUTOINCREMENT, timestamp TEXT,humedad_suelo INTEGER, luz INTEGER, turbidez INTEGER, voltaje REAL, estado TEXT) piensa bien antes de generar la consulta SQL:"
|
94 |
+
query = f"{d} {consulta}"
|
95 |
+
output = agent_executor.invoke({"input": query})
|
96 |
+
return output["output"]
|
97 |
+
|
98 |
+
|
99 |
+
import streamlit as st
|
100 |
+
|
101 |
+
# configurar la página
|
102 |
+
st.set_page_config(
|
103 |
+
page_title="Chatbot - Arduino 🤖",
|
104 |
+
page_icon="🤖",
|
105 |
+
layout="centered",
|
106 |
+
initial_sidebar_state="collapsed",
|
107 |
+
)
|
108 |
+
|
109 |
+
st.title("Chatbot monitoreo de sensores de Arduino 🤖")
|
110 |
+
|
111 |
+
if "history" not in st.session_state:
|
112 |
+
st.session_state["history"] = []
|
113 |
+
|
114 |
+
pregunta = st.chat_input("Escribe tu consulta...")
|
115 |
+
|
116 |
+
if pregunta:
|
117 |
+
st.session_state["history"].append({"role": "user", "content": pregunta})
|
118 |
+
respuesta = ask_agent(pregunta)
|
119 |
+
st.session_state["history"].append({"role": "ai", "content": respuesta})
|
120 |
+
|
121 |
+
for message in st.session_state["history"]:
|
122 |
+
if message["role"] == "user":
|
123 |
+
with st.chat_message(name="user", avatar="👩💻"):
|
124 |
+
st.write(message["content"])
|
125 |
+
else:
|
126 |
+
with st.chat_message(name="ai", avatar="🍦"):
|
127 |
+
st.write(message["content"])
|