Fix: LangChain Dependences

This commit is contained in:
2024-11-01 22:41:13 -05:00
parent 5235541b76
commit 9e26bc4d7a
19 changed files with 2388 additions and 102 deletions

View File

@@ -6,13 +6,12 @@ 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 rag.split_docs import load_split_docs
from rag.llm import load_llm_openai
from rag.embeddings import load_embeddins
from rag.retriever import create_retriever
from rag.vectorstore import create_verctorstore
from rag.rag_chain import create_rag_chain
from datetime import datetime
from ..rag.split_docs import load_split_docs
from ..rag.llm import load_llm_openai
from ..rag.embeddings import load_embeddins
from ..rag.retriever import create_retriever
from ..rag.vectorstore import create_verctorstore
from ..rag.rag_chain import create_rag_chain
import pytz
import telebot
import os
@@ -62,22 +61,25 @@ def redact_email(topic: str) -> str:
def list_calendar_events(max_results: int = 50) -> list:
"""Use this tool to list upcoming calendar events."""
# Define los alcances que necesitamos para acceder a la API de Google Calendar
# Define los alcances que necesitamos para acceder a
# la API de Google Calendar
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = None
# La ruta al archivo token.json, que contiene los tokens de acceso y actualización
token_path = 'token_2.json'
# La ruta al archivo token.json, que contiene
# los tokens de acceso y actualización
token_path = 'token.json'
# La ruta al archivo de credenciales de OAuth 2.1
creds_path = 'credentials_2.json'
creds_path = 'credentials.json'
# Cargar las credenciales desde el archivo token.json, si existe
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
# Si no hay credenciales válidas disponibles, inicia el flujo de OAuth 2.0 para obtener nuevas credenciales
# Si no hay credenciales válidas disponibles, inicia el flujo de OAuth 2.0
# para obtener nuevas credenciales
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
@@ -90,16 +92,19 @@ def list_calendar_events(max_results: int = 50) -> list:
with open(token_path, 'w') as token_file:
token_file.write(creds.to_json())
# Construye el objeto de servicio para interactuar con la API de Google Calendar
# Construye el objeto de servicio para interactuar
# con la API de Google Calendar
service = build('calendar', 'v3', credentials=creds)
# Identificador del calendario que deseas consultar. 'primary' se refiere al calendario principal del usuario.
# Identificador del calendario que deseas consultar.
# 'primary' se refiere al calendario principal del usuario.
calendar_id = 'primary'
# Realiza una llamada a la API para obtener una lista de eventos.
now = datetime.now(timezone.utc).isoformat() # 'Z' indica UTC
events_result = service.events().list(
calendarId=calendar_id, timeMin=now, maxResults=max_results, singleEvents=True,
calendarId=calendar_id, timeMin=now,
maxResults=max_results, singleEvents=True,
orderBy='startTime').execute()
# Extrae los eventos de la respuesta de la API.
@@ -110,9 +115,11 @@ def list_calendar_events(max_results: int = 50) -> list:
print('No upcoming events found.')
return
# Recorre la lista de eventos y muestra la hora de inicio y el resumen de cada evento.
# Recorre la lista de eventos y muestra la hora de inicio
# y el resumen de cada evento.
for event in events:
# Obtiene la fecha y hora de inicio del evento. Puede ser 'dateTime' o 'date'.
# Obtiene la fecha y hora de inicio del evento.
# Puede ser 'dateTime' o 'date'.
start = event['start'].get('dateTime', event['start'].get('date'))
# Imprime la hora de inicio y el resumen (título) del evento.
print(start, event['summary'])
@@ -143,7 +150,8 @@ def create_calendar_event(
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = None
# La ruta al archivo token.json, que contiene los tokens de acceso y actualización
# La ruta al archivo token.json,
# que contiene los tokens de acceso y actualización
token_path = 'token_2.json'
# La ruta al archivo de credenciales de OAuth 2.0
@@ -153,7 +161,8 @@ def create_calendar_event(
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
# Si no hay credenciales válidas disponibles, inicia el flujo de OAuth 2.0 para obtener nuevas credenciales
# Si no hay credenciales válidas disponibles,
# inicia el flujo de OAuth 2.0 para obtener nuevas credenciales
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
@@ -166,7 +175,8 @@ def create_calendar_event(
with open(token_path, 'w') as token_file:
token_file.write(creds.to_json())
# Construye el objeto de servicio para interactuar con la API de Google Calendar
# Construye el objeto de servicio para
# interactuar con la API de Google Calendar
service = build('calendar', 'v3', credentials=creds)
# Validar y filtrar asistentes
@@ -177,10 +187,12 @@ def create_calendar_event(
else:
raise ValueError(f"'{email}' no es un correo electrónico válido.")
# Identificador del calendario que deseas modificar. 'primary' se refiere al calendario principal del usuario.
# Identificador del calendario que deseas modificar.
# 'primary' se refiere al calendario principal del usuario.
calendar_id = 'primary'
# Define el cuerpo del evento con el título, la hora de inicio y la hora de finalización
# Define el cuerpo del evento con el título,
# la hora de inicio y la hora de finalización
event = {
'summary': title,
'start': {
@@ -196,7 +208,8 @@ def create_calendar_event(
try:
# Crea el evento en el calendario
event = service.events().insert(calendarId=calendar_id, body=event).execute()
event = service.events().insert(
calendarId=calendar_id, body=event).execute()
print('Event created: %s' % (event.get('htmlLink')))
except Exception as e:
print(f"Error al crear el evento: {e}")
@@ -207,7 +220,8 @@ def create_calendar_event(
@tool
def create_quick_add_event(quick_add_text: str):
"""Use this tool to create events in the calendar from natural language,
"""
Use this tool to create events in the calendar from natural language,
using the Quick Add feature of Google Calendar.
"""
quick_add_text: str = input(
@@ -216,7 +230,8 @@ def create_quick_add_event(quick_add_text: str):
creds = None
# La ruta al archivo token.json, que contiene los tokens de acceso y actualización
# La ruta al archivo token.json,
# que contiene los tokens de acceso y actualización
token_path = 'token_2.json'
# La ruta al archivo de credenciales de OAuth 2.0
@@ -226,7 +241,8 @@ def create_quick_add_event(quick_add_text: str):
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
# Si no hay credenciales válidas disponibles, inicia el flujo de OAuth 2.0 para obtener nuevas credenciales
# Si no hay credenciales válidas disponibles,
# inicia el flujo de OAuth 2.0 para obtener nuevas credenciales
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
@@ -239,10 +255,12 @@ def create_quick_add_event(quick_add_text: str):
with open(token_path, 'w') as token_file:
token_file.write(creds.to_json())
# Construye el objeto de servicio para interactuar con la API de Google Calendar
# Construye el objeto de servicio para interactuar
# con la API de Google Calendar
service = build('calendar', 'v3', credentials=creds)
# Identificador del calendario que deseas modificar. 'primary' se refiere al calendario principal del usuario.
# Identificador del calendario que deseas modificar.
# 'primary' se refiere al calendario principal del usuario.
calendar_id = 'primary'
# Crea el evento utilizando la funcionalidad Quick Add
@@ -284,7 +302,10 @@ def send_message(message: str):
@tool
def get_company_info(prompt: str) -> str:
"""Use this function when you need more information about the services offered by OneCluster."""
"""
Use this function when you need more information
about the services offered by OneCluster.
"""
file_path: str = 'onecluster_info.pdf'
docs_split: list = load_split_docs(file_path)
@@ -302,7 +323,9 @@ def get_company_info(prompt: str) -> str:
qa = create_rag_chain(
llm, retriever)
# prompt: str = "Escribe un parrarfo describiendo cuantos son y cuales son los servicios que ofrece OneCluster y brinda detalles sobre cada uno."
# prompt: str = "Escribe un parrarfo describiendo cuantos son y
# cuales son los servicios que ofrece OneCluster
# y brinda detalles sobre cada uno."
response = qa.invoke(
{"input": prompt, "chat_history": []}
)

View File

@@ -1,4 +1,4 @@
from langchain_core.tools import tool
# from langchain_core.tools import tool
from langchain_community.tools.gmail.utils import (
build_resource_service,
get_gmail_credentials,
@@ -10,7 +10,8 @@ from dotenv import load_dotenv
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_tools.agent_tools import (
multiply, redact_email, list_calendar_events,
create_calendar_event, create_quick_add_event,
create_calendar_event,
# create_quick_add_event,
send_message, get_company_info,
get_current_date_and_time
)
@@ -22,8 +23,10 @@ class AgentTools:
toolkit = GmailToolkit()
# Can review scopes here https://developers.google.com/gmail/api/auth/scopes
# For instance, readonly scope is 'https://www.googleapis.com/auth/gmail.readonly'
# Can review scopes here
# https://developers.google.com/gmail/api/auth/scopes
# For instance, readonly scope is
# 'https://www.googleapis.com/auth/gmail.readonly'
credentials = get_gmail_credentials(
token_file="token.json",
scopes=["https://mail.google.com/"],
@@ -53,20 +56,46 @@ class AgentTools:
def load_agent(self, llm, tools):
instructions = """
You are the virtual assistant of OneCluster, a company specialized in providing custom development services focused on creating personalized technological solutions for businesses and companies. Your mission is to offer a warm, friendly, and collaborative service that always reflects OneCluster's core values.
You are the virtual assistant of OneCluster, a company specialized in
providing custom development services focused on creating personalized
technological solutions for businesses and companies.
Your mission is to offer a warm, friendly,
and collaborative service that always
reflects OneCluster's core values.
**User Interactions:**
1. **Initial Greeting:** When starting an interaction with a user, greet them courteously and identify who you have the pleasure of speaking with. Once you know the user's name, address them respectfully throughout the conversation.
**User Interactions:**
1. **Initial Greeting:** When starting an interaction with a user,
greet them courteously and identify who you have the pleasure of
speaking with. Once you know the user's name, address them respectfully
throughout the conversation.
2. **Providing Information:** You have the ability to offer clear and detailed information about the services provided by OneCluster. Make sure to be concise yet informative, adapting the information to the user's needs.
2. **Providing Information:** You have the ability to offer clear and
detailed information about the services provided by OneCluster.
Make sure to be concise yet informative,
adapting the information to the user's needs.
3. **Appointment Scheduling:** You are responsible for scheduling appointments for clients. Before confirming an appointment, always check the availability on OneCluster's calendar to ensure there is space, and check the current date and time so that you have a clear sense of time. Request an email address from the user to schedule the appointment.
3. **Appointment Scheduling:** You are responsible for scheduling
appointments for clients. Before confirming an appointment,
always check the availability on OneCluster's
calendar to ensure there is space,
and check the current date and time so that
you have a clear sense of time.
Request an email address from the user to schedule the appointment.
4. **Handling Unanswered Questions:** If you do not know how to answer a question, politely ask for the client's contact information and clearly identify the problem to be resolved. Then, send this information to oneclustererp@gmail.com with the subject "Unresolved customer query by the agent." Inform the client that you do not have the information at your disposal but that you can escalate the request to the support team, who will respond promptly.
4. **Handling Unanswered Questions:** If you do not know how to
answer a question, politely ask for the client's contact information
and clearly identify the problem to be resolved.
Then, send this information to oneclustererp@gmail.com with the subject
"Unresolved customer query by the agent."
Inform the client that you do not have the information at your
disposal but that you can escalate the request to the support team,
who will respond promptly.
**Style and Tone:**
Maintain a tone that is always friendly, approachable, and professional. Each interaction should reflect OneCluster's commitment to innovation, adaptability, and ongoing collaboration.
"""
**Style and Tone:**
Maintain a tone that is always friendly, approachable, and
professional. Each interaction should reflect OneCluster's
commitment to innovation, adaptability, and ongoing collaboration.
"""
base_prompt = hub.pull("langchain-ai/openai-functions-template")