Se eliminan las herramientas que utilizaban la API de Google, toda vez la implmentacion estaba fallando. Se deja corriendo al Agente con busqueda a internet, el rag y el acceso a la hora y fecha.
This commit is contained in:
@@ -2,9 +2,6 @@ from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.tools import tool
|
||||
from datetime import datetime, timezone
|
||||
from google.oauth2.credentials import Credentials
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from google.auth.transport.requests import Request
|
||||
from googleapiclient.discovery import build
|
||||
from app.rag.split_docs import load_split_docs
|
||||
from app.rag.llm import load_llm_openai
|
||||
@@ -12,7 +9,6 @@ from app.rag.embeddings import load_embeddins
|
||||
from app.rag.retriever import create_retriever
|
||||
from app.rag.vectorstore import create_vectorstore
|
||||
from app.rag.rag_chain import create_rag_chain
|
||||
from app.google_auth import get_google_credentials
|
||||
import pytz
|
||||
import telebot
|
||||
import os
|
||||
@@ -32,128 +28,6 @@ class LangChainTools:
|
||||
)
|
||||
return llm
|
||||
|
||||
def list_calendar_events(self, max_results: int = 50) -> list:
|
||||
"""Lista los próximos eventos del calendario."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Obtener eventos próximos
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
events_result = service.events().list(
|
||||
calendarId='primary',
|
||||
timeMin=now,
|
||||
maxResults=max_results,
|
||||
singleEvents=True,
|
||||
orderBy='startTime'
|
||||
).execute()
|
||||
|
||||
events = events_result.get('items', [])
|
||||
|
||||
if not events:
|
||||
print('No se encontraron eventos próximos.')
|
||||
return []
|
||||
|
||||
# Formatear la salida de eventos
|
||||
formatted_events = []
|
||||
for event in events:
|
||||
start = event['start'].get('dateTime', event['start'].get('date'))
|
||||
formatted_events.append({
|
||||
'start': start,
|
||||
'summary': event['summary'],
|
||||
'id': event['id'],
|
||||
'link': event.get('htmlLink')
|
||||
})
|
||||
print(f"{start} - {event['summary']}")
|
||||
|
||||
return formatted_events
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al listar eventos: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
def create_calendar_event(
|
||||
self, title: str, start_time: datetime,
|
||||
end_time: datetime, attendees: list = None) -> dict:
|
||||
"""Crea un evento en el calendario."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Identificador del calendario principal
|
||||
calendar_id = 'primary'
|
||||
|
||||
# Definir el evento
|
||||
event = {
|
||||
'summary': title,
|
||||
'start': {
|
||||
'dateTime': start_time.strftime('%Y-%m-%dT%H:%M:%S'),
|
||||
'timeZone': 'America/Bogota',
|
||||
},
|
||||
'end': {
|
||||
'dateTime': end_time.strftime('%Y-%m-%dT%H:%M:%S'),
|
||||
'timeZone': 'America/Bogota',
|
||||
},
|
||||
}
|
||||
|
||||
# Agregar asistentes si se proporcionan
|
||||
if attendees and isinstance(attendees, list) and len(attendees) > 0:
|
||||
# Asegurarse de que cada asistente tenga un correo válido
|
||||
attendees_list = []
|
||||
for attendee in attendees:
|
||||
if isinstance(attendee, str) and '@' in attendee:
|
||||
attendees_list.append({'email': attendee.strip()})
|
||||
if attendees_list:
|
||||
event['attendees'] = attendees_list
|
||||
# Enviar invitaciones por correo
|
||||
event['sendUpdates'] = 'all'
|
||||
|
||||
# Crear el evento
|
||||
event = service.events().insert(calendarId=calendar_id, body=event).execute()
|
||||
print(f'Evento creado: {event.get("htmlLink")}')
|
||||
return event
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al crear el evento: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
def create_quick_add_event(self, quick_add_text: str) -> dict:
|
||||
"""Crea un evento rápidamente usando texto en lenguaje natural."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Identificador del calendario principal
|
||||
calendar_id = 'primary'
|
||||
|
||||
# Crear el evento usando quick add
|
||||
event = service.events().quickAdd(
|
||||
calendarId=calendar_id,
|
||||
text=quick_add_text
|
||||
).execute()
|
||||
|
||||
print(f'Evento creado: {event.get("htmlLink")}')
|
||||
return event
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al crear el evento rápido: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
@tool
|
||||
def multiply(first_int: int, second_int: int) -> int:
|
||||
"""Multiply two integers together."""
|
||||
return first_int * second_int
|
||||
|
||||
|
||||
@tool
|
||||
def redact_email(topic: str) -> str:
|
||||
@@ -184,6 +58,7 @@ def send_message(message: str):
|
||||
|
||||
# Escapar caracteres especiales en Markdown
|
||||
from telebot.util import escape_markdown
|
||||
|
||||
safe_message = escape_markdown(message)
|
||||
|
||||
# Enviar mensaje usando MarkdownV2
|
||||
@@ -197,29 +72,22 @@ def get_company_info(prompt: str) -> str:
|
||||
Use this function when you need more information
|
||||
about the services offered by OneCluster.
|
||||
"""
|
||||
file_path: str = 'onecluster_info.pdf'
|
||||
file_path: str = "onecluster_info.pdf"
|
||||
|
||||
try:
|
||||
docs_split: list = load_split_docs(file_path)
|
||||
embeddings_model = load_embeddins()
|
||||
llm = load_llm_openai()
|
||||
|
||||
|
||||
# Usar el nombre corregido de la función
|
||||
create_vectorstore(
|
||||
docs_split,
|
||||
embeddings_model,
|
||||
file_path
|
||||
)
|
||||
|
||||
create_vectorstore(docs_split, embeddings_model, file_path)
|
||||
|
||||
retriever = create_retriever(
|
||||
embeddings_model,
|
||||
persist_directory="embeddings/onecluster_info"
|
||||
embeddings_model, persist_directory="embeddings/onecluster_info"
|
||||
)
|
||||
qa = create_rag_chain(llm, retriever)
|
||||
|
||||
response = qa.invoke(
|
||||
{"input": prompt, "chat_history": []}
|
||||
)
|
||||
response = qa.invoke({"input": prompt, "chat_history": []})
|
||||
|
||||
return response["answer"]
|
||||
except Exception as e:
|
||||
@@ -235,126 +103,6 @@ def get_current_date_and_time():
|
||||
Returns:
|
||||
str: Current date and time in Bogotá, Colombia.
|
||||
"""
|
||||
bogota_tz = pytz.timezone('America/Bogota')
|
||||
bogota_tz = pytz.timezone("America/Bogota")
|
||||
current_date_and_time = datetime.now(bogota_tz)
|
||||
return current_date_and_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
|
||||
@tool
|
||||
def list_calendar_events(max_results: int = 50) -> list:
|
||||
"""Use this tool to list upcoming calendar events."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Obtener eventos próximos
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
events_result = service.events().list(
|
||||
calendarId='primary',
|
||||
timeMin=now,
|
||||
maxResults=max_results,
|
||||
singleEvents=True,
|
||||
orderBy='startTime'
|
||||
).execute()
|
||||
|
||||
events = events_result.get('items', [])
|
||||
|
||||
if not events:
|
||||
print('No se encontraron eventos próximos.')
|
||||
return []
|
||||
|
||||
# Formatear la salida de eventos
|
||||
formatted_events = []
|
||||
for event in events:
|
||||
start = event['start'].get('dateTime', event['start'].get('date'))
|
||||
formatted_events.append({
|
||||
'start': start,
|
||||
'summary': event['summary'],
|
||||
'id': event['id'],
|
||||
'link': event.get('htmlLink')
|
||||
})
|
||||
print(f"{start} - {event['summary']}")
|
||||
|
||||
return formatted_events
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al listar eventos: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
@tool
|
||||
def create_calendar_event(
|
||||
title: str, start_time: datetime,
|
||||
end_time: datetime, attendees: list = None) -> dict:
|
||||
"""Use this tool to create an event in the calendar."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Identificador del calendario principal
|
||||
calendar_id = 'primary'
|
||||
|
||||
# Definir el evento
|
||||
event = {
|
||||
'summary': title,
|
||||
'start': {
|
||||
'dateTime': start_time.strftime('%Y-%m-%dT%H:%M:%S'),
|
||||
'timeZone': 'America/Bogota',
|
||||
},
|
||||
'end': {
|
||||
'dateTime': end_time.strftime('%Y-%m-%dT%H:%M:%S'),
|
||||
'timeZone': 'America/Bogota',
|
||||
},
|
||||
}
|
||||
|
||||
# Agregar asistentes si se proporcionan
|
||||
if attendees and isinstance(attendees, list) and len(attendees) > 0:
|
||||
# Asegurarse de que cada asistente tenga un correo válido
|
||||
attendees_list = []
|
||||
for attendee in attendees:
|
||||
if isinstance(attendee, str) and '@' in attendee:
|
||||
attendees_list.append({'email': attendee.strip()})
|
||||
if attendees_list:
|
||||
event['attendees'] = attendees_list
|
||||
# Enviar invitaciones por correo
|
||||
event['sendUpdates'] = 'all'
|
||||
|
||||
# Crear el evento
|
||||
event = service.events().insert(calendarId=calendar_id, body=event).execute()
|
||||
print(f'Evento creado: {event.get("htmlLink")}')
|
||||
return event
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al crear el evento: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
@tool
|
||||
def create_quick_add_event(quick_add_text: str) -> dict:
|
||||
"""Use this tool to create events in the calendar from natural language."""
|
||||
try:
|
||||
# Usar el sistema centralizado de autenticación
|
||||
creds = get_google_credentials()
|
||||
|
||||
# Construir el servicio de Calendar
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
|
||||
# Identificador del calendario principal
|
||||
calendar_id = 'primary'
|
||||
|
||||
# Crear el evento usando quick add
|
||||
event = service.events().quickAdd(
|
||||
calendarId=calendar_id,
|
||||
text=quick_add_text
|
||||
).execute()
|
||||
|
||||
print(f'Evento creado: {event.get("htmlLink")}')
|
||||
return event
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al crear el evento rápido: {e}")
|
||||
return {"error": str(e)}
|
||||
return current_date_and_time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
Reference in New Issue
Block a user