Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +111 -0
- requirements.txt +10 -0
app.py
ADDED
@@ -0,0 +1,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 |
+
|
23 |
+
@tool
|
24 |
+
def consultar_db_via_api(query: str):
|
25 |
+
"""
|
26 |
+
Consulta la DB SQLite con una consulta puntual. Máximo puedes solicitar hasta 20 registros.
|
27 |
+
NO USES COMILLAS DOBLES AL INICIO Y AL FINAL DE LA CONSULTA.
|
28 |
+
|
29 |
+
|
30 |
+
Parámetros:
|
31 |
+
- query (str): La consulta SQL a ejecutar en la base de datos.
|
32 |
+
|
33 |
+
Retorna:
|
34 |
+
- dict: Los resultados de la consulta en formato JSON.
|
35 |
+
"""
|
36 |
+
try:
|
37 |
+
query = query.strip('"')
|
38 |
+
if query.endswith(";"):
|
39 |
+
query = query[:-1]
|
40 |
+
query = query.replace("'", "\\'")
|
41 |
+
format_query_json = {"query": query}
|
42 |
+
response = requests.post(
|
43 |
+
url="https://jairodanielmt-arduino-data-post.hf.space/execute",
|
44 |
+
json=format_query_json,
|
45 |
+
headers={"Content-Type": "application/json"},
|
46 |
+
)
|
47 |
+
response.raise_for_status()
|
48 |
+
data = response.json()
|
49 |
+
return data
|
50 |
+
except requests.exceptions.RequestException as e:
|
51 |
+
print(f"Error al consultar la API: {e}")
|
52 |
+
if e.response is not None:
|
53 |
+
print(e.response.text)
|
54 |
+
return None
|
55 |
+
|
56 |
+
|
57 |
+
prompt = hub.pull("hwchase17/react")
|
58 |
+
tools = [consultar_db_via_api]
|
59 |
+
|
60 |
+
llm = ChatOpenAI(
|
61 |
+
model="deepseek-chat",
|
62 |
+
base_url="https://api.deepseek.com",
|
63 |
+
temperature=0.3,
|
64 |
+
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
65 |
+
)
|
66 |
+
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
|
67 |
+
agent_executor = AgentExecutor(
|
68 |
+
agent=agent,
|
69 |
+
tools=tools,
|
70 |
+
verbose=True,
|
71 |
+
handle_parsing_errors=True,
|
72 |
+
max_iterations=20,
|
73 |
+
)
|
74 |
+
|
75 |
+
|
76 |
+
def ask_agent(consulta) -> str:
|
77 |
+
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:"
|
78 |
+
query = f"{d} {consulta}"
|
79 |
+
output = agent_executor.invoke({"input": query})
|
80 |
+
return output["output"]
|
81 |
+
|
82 |
+
|
83 |
+
import streamlit as st
|
84 |
+
|
85 |
+
# configurar la página
|
86 |
+
st.set_page_config(
|
87 |
+
page_title="Chatbot - Arduino 🤖",
|
88 |
+
page_icon="🤖",
|
89 |
+
layout="centered",
|
90 |
+
initial_sidebar_state="collapsed",
|
91 |
+
)
|
92 |
+
|
93 |
+
st.title("Chatbot monitoreo de sensores de Arduino 🤖")
|
94 |
+
|
95 |
+
if "history" not in st.session_state:
|
96 |
+
st.session_state["history"] = []
|
97 |
+
|
98 |
+
pregunta = st.chat_input("Escribe tu consulta...")
|
99 |
+
|
100 |
+
if pregunta:
|
101 |
+
st.session_state["history"].append({"role": "user", "content": pregunta})
|
102 |
+
respuesta = ask_agent(pregunta)
|
103 |
+
st.session_state["history"].append({"role": "ai", "content": respuesta})
|
104 |
+
|
105 |
+
for message in st.session_state["history"]:
|
106 |
+
if message["role"] == "user":
|
107 |
+
with st.chat_message(name="user", avatar="👩💻"):
|
108 |
+
st.write(message["content"])
|
109 |
+
else:
|
110 |
+
with st.chat_message(name="ai", avatar="🍦"):
|
111 |
+
st.write(message["content"])
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
langchain
|
2 |
+
langchain-community
|
3 |
+
langchain-openai
|
4 |
+
langchain-core
|
5 |
+
langchain-huggingface
|
6 |
+
langchain-experimental
|
7 |
+
faiss-cpu
|
8 |
+
python-dotenv
|
9 |
+
torch
|
10 |
+
langchainhub
|