JairoDanielMT commited on
Commit
5084ab3
·
verified ·
1 Parent(s): 4c5c44b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -111
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
- @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"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"])