Fix: LangChain Dependences
This commit is contained in:
parent
5235541b76
commit
9e26bc4d7a
6
Rakefile
6
Rakefile
@ -53,6 +53,12 @@ namespace :live do
|
||||
|
||||
end
|
||||
|
||||
desc 'iterar'
|
||||
task :tdd do
|
||||
compose('exec', 'app', "bash -c 'cd app && flake8 *'")
|
||||
compose('exec', 'app', "bash -c 'cd app && pytest -vvv'")
|
||||
end
|
||||
|
||||
def compose(*arg, compose: DOCKER_COMPOSE)
|
||||
sh "docker compose -f #{compose} #{arg.join(' ')}"
|
||||
end
|
||||
|
@ -14,8 +14,7 @@ from langchain_tools.agent_tools import (
|
||||
get_current_date_and_time
|
||||
)
|
||||
from langchain_community.tools.gmail.utils import (
|
||||
build_resource_service, get_gmail_credentials
|
||||
)
|
||||
build_resource_service, get_gmail_credentials)
|
||||
from langchain_community.agent_toolkits import GmailToolkit
|
||||
|
||||
# Cargar las variables de entorno
|
||||
@ -43,20 +42,55 @@ toolkit = GmailToolkit(api_resource=api_resource)
|
||||
# Crear herramientas
|
||||
tools = toolkit.get_tools()
|
||||
search = TavilySearchResults(max_results=2)
|
||||
tools.extend([search, redact_email, list_calendar_events,
|
||||
create_calendar_event, get_company_info, get_current_date_and_time])
|
||||
tools.extend([
|
||||
search, redact_email, list_calendar_events,
|
||||
create_calendar_event, get_company_info,
|
||||
get_current_date_and_time])
|
||||
|
||||
# Definir el sistema prompt
|
||||
system_prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
("system", "Eres Mariana, el asistente virtual de OneCluster, una empresa de software que ofrece soluciones personalizadas. Asume el tono de J.A.R.V.I.S.: cordial, atento y con tacto en todo momento."),
|
||||
("system", "Preséntate como Mariana en el primer mensaje y pregunta el nombre del usuario si no lo tienes registrado."),
|
||||
("system", "Si el usuario ya ha interactuado antes, usa su nombre sin necesidad de volver a preguntar."),
|
||||
("system", "OneCluster es una empresa de software especializada en desarrollo a medida. Solo responde a preguntas y solicitudes relacionadas con la empresa y sus servicios."),
|
||||
("system", "Si necesitas información adicional sobre la empresa, usa la función get_company_info."),
|
||||
("system", "Antes de enviar correos o crear eventos, muestra los detalles al usuario para que los confirme antes de ejecutar la tarea."),
|
||||
("system", "Si te preguntan algo no relacionado con los servicios de OneCluster, responde que solo puedes ayudar con temas relacionados con la empresa y sus soluciones."),
|
||||
("system", "Evita mencionar o hacer alusión a las herramientas que utilizas internamente. Esa información es confidencial."),
|
||||
(
|
||||
"system",
|
||||
"Eres Mariana, el asistente virtual de OneCluster, una empresa de "
|
||||
"software que ofrece soluciones personalizadas. Asume el tono de "
|
||||
"J.A.R.V.I.S.: cordial, atento y con tacto en todo momento."
|
||||
),
|
||||
("system",
|
||||
"Preséntate como Mariana en el primer mensaje y pregunta el nombre "
|
||||
"del usuario si no lo tienes registrado."
|
||||
),
|
||||
("system",
|
||||
"Si el usuario ya ha interactuado antes, usa su nombre sin necesidad "
|
||||
"de volver a preguntar."
|
||||
),
|
||||
("system",
|
||||
"Si el primer mensaje del usuario es una solicitud, pregúntale su "
|
||||
"nombre antes de responder si aún no lo conoces."
|
||||
),
|
||||
("system",
|
||||
"OneCluster es una empresa de software especializada en desarrollo a "
|
||||
"medida. Solo responde a preguntas y solicitudes relacionadas con la "
|
||||
"empresa y sus servicios."
|
||||
),
|
||||
("system",
|
||||
"Si necesitas información adicional sobre la empresa, usa la función "
|
||||
"get_company_info."
|
||||
),
|
||||
("system",
|
||||
"Antes de enviar correos o crear eventos, muestra los detalles al "
|
||||
"usuario para que los confirme antes de ejecutar la tarea."
|
||||
),
|
||||
("system",
|
||||
"Si te preguntan algo no relacionado con los servicios de OneCluster,"
|
||||
" responde que solo puedes ayudar con temas relacionados con la "
|
||||
"empresa y sus soluciones."
|
||||
),
|
||||
(
|
||||
"system",
|
||||
"Evita mencionar o hacer alusión a las herramientas que utilizas "
|
||||
"internamente. Esa información es confidencial."
|
||||
),
|
||||
("placeholder", "{messages}"),
|
||||
]
|
||||
)
|
||||
@ -88,7 +122,8 @@ def process_text():
|
||||
# Procesar el texto con LangChain
|
||||
events = graph.stream(
|
||||
{"messages": [("user", user_input)], "is_last_step": False},
|
||||
config={"configurable": {"thread_id": "thread-1", "recursion_limit": 50}},
|
||||
config={"configurable": {
|
||||
"thread_id": "thread-1", "recursion_limit": 50}},
|
||||
stream_mode="updates"
|
||||
)
|
||||
|
1
app/credentials.json
Normal file
1
app/credentials.json
Normal file
@ -0,0 +1 @@
|
||||
{"installed":{"client_id":"845924256677-ddb5l20d43j02cqfri5j4blcf2ia57ts.apps.googleusercontent.com","project_id":"black-pier-285900","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
|
1
app/credentials_2.json
Normal file
1
app/credentials_2.json
Normal file
@ -0,0 +1 @@
|
||||
{"installed":{"client_id":"629922809906-pl9l1ipout6d5hh19ku50sfvnqgu8ir2.apps.googleusercontent.com","project_id":"calendar-424503","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
|
@ -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": []}
|
||||
)
|
||||
|
@ -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")
|
||||
|
||||
|
@ -32,7 +32,9 @@ llm = ChatOpenAI(
|
||||
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'
|
||||
# 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/"],
|
||||
@ -54,25 +56,47 @@ tools.append(get_current_date_and_time)
|
||||
|
||||
system_prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
("system", "Eres Mariana, el asistente virtual de OneCluster, una empresa de software que ofrece soluciones personalizadas. Asume el tono de J.A.R.V.I.S.: cordial, atento y con tacto en todo momento."),
|
||||
|
||||
# Instrucciones sobre presentación y tono
|
||||
("system", "Preséntate como Mariana en el primer mensaje y pregunta el nombre del usuario si no lo tienes registrado."),
|
||||
("system", "Si el usuario ya ha interactuado antes, usa su nombre sin necesidad de volver a preguntar."),
|
||||
("system", "Si el primer mensaje del usuario es una solicitud, pregúntale su nombre antes de responder si aún no lo conoces."),
|
||||
|
||||
# Instrucciones sobre el manejo de solicitudes y tareas
|
||||
("system", "OneCluster es una empresa de software especializada en desarrollo a medida. Solo responde a preguntas y solicitudes relacionadas con la empresa y sus servicios."),
|
||||
("system", "Si necesitas información adicional sobre la empresa, usa la función get_company_info."),
|
||||
("system", "Antes de enviar correos o crear eventos, muestra los detalles al usuario para que los confirme antes de ejecutar la tarea."),
|
||||
|
||||
# Cómo manejar preguntas fuera del alcance
|
||||
("system", "Si te preguntan algo no relacionado con los servicios de OneCluster, responde que solo puedes ayudar con temas relacionados con la empresa y sus soluciones."),
|
||||
|
||||
# Prohibición de revelar herramientas internas
|
||||
("system", "Evita mencionar o hacer alusión a las herramientas que utilizas internamente. Esa información es confidencial."),
|
||||
|
||||
# Placeholder para el contenido dinámico de la conversación
|
||||
(
|
||||
"system",
|
||||
"Eres Mariana, el asistente virtual de OneCluster, una empresa de "
|
||||
"software que ofrece soluciones personalizadas. Asume el tono de "
|
||||
"J.A.R.V.I.S.: cordial, atento y con tacto en todo momento."
|
||||
),
|
||||
("system",
|
||||
"Preséntate como Mariana en el primer mensaje y pregunta el nombre "
|
||||
"del usuario si no lo tienes registrado."
|
||||
),
|
||||
("system",
|
||||
"Si el usuario ya ha interactuado antes, usa su nombre sin necesidad "
|
||||
"de volver a preguntar."
|
||||
),
|
||||
("system",
|
||||
"Si el primer mensaje del usuario es una solicitud, pregúntale su "
|
||||
"nombre antes de responder si aún no lo conoces."
|
||||
),
|
||||
("system",
|
||||
"OneCluster es una empresa de software especializada en desarrollo a "
|
||||
"medida. Solo responde a preguntas y solicitudes relacionadas con la "
|
||||
"empresa y sus servicios."
|
||||
),
|
||||
("system",
|
||||
"Si necesitas información adicional sobre la empresa, usa la función "
|
||||
"get_company_info."
|
||||
),
|
||||
("system",
|
||||
"Antes de enviar correos o crear eventos, muestra los detalles al "
|
||||
"usuario para que los confirme antes de ejecutar la tarea."
|
||||
),
|
||||
("system",
|
||||
"Si te preguntan algo no relacionado con los servicios de OneCluster,"
|
||||
" responde que solo puedes ayudar con temas relacionados con la "
|
||||
"empresa y sus soluciones."
|
||||
),
|
||||
(
|
||||
"system",
|
||||
"Evita mencionar o hacer alusión a las herramientas que utilizas "
|
||||
"internamente. Esa información es confidencial."
|
||||
),
|
||||
("placeholder", "{messages}"),
|
||||
]
|
||||
)
|
||||
@ -84,13 +108,15 @@ class State(TypedDict):
|
||||
|
||||
|
||||
# Creamos el graph con el estado definido
|
||||
graph= create_react_agent(
|
||||
model = llm, tools = tools, state_schema = State,
|
||||
state_modifier = system_prompt,
|
||||
checkpointer = MemorySaver()
|
||||
graph = create_react_agent(
|
||||
model=llm,
|
||||
tools=tools,
|
||||
state_schema=State,
|
||||
state_modifier=system_prompt,
|
||||
checkpointer=MemorySaver()
|
||||
)
|
||||
|
||||
config= {"configurable": {"thread_id": "thread-1", "recursion_limit": 50}}
|
||||
config = {"configurable": {"thread_id": "thread-1", "recursion_limit": 50}}
|
||||
|
||||
|
||||
while True:
|
||||
@ -99,11 +125,11 @@ while True:
|
||||
print("Goodbye!")
|
||||
break
|
||||
|
||||
events = graph.stream(
|
||||
{"messages": [("user", user_input)],
|
||||
events = graph.stream({
|
||||
"messages": [("user", user_input)],
|
||||
"is_last_step": False},
|
||||
config, stream_mode = "updates")
|
||||
config, stream_mode="updates")
|
||||
|
||||
for event in events:
|
||||
if "agent" in event:
|
||||
print(f"\nAsistente: {event["agent"]["messages"][-1].content}\n")
|
||||
print(f"\nAsistente: {event['agent']['messages'][-1].content}\n")
|
||||
|
@ -31,7 +31,7 @@ def bot_mensajes(message):
|
||||
|
||||
# Si el mensaje es una nota de voz
|
||||
if message.voice:
|
||||
user_name = message.from_user.first_name
|
||||
# user_ = message.from_user.first_name
|
||||
file_info = bot.get_file(message.voice.file_id)
|
||||
downloaded_file = bot.download_file(file_info.file_path)
|
||||
file_path = "audios/nota_de_voz.ogg"
|
||||
|
@ -24,7 +24,8 @@ retriever = create_retriever(
|
||||
qa = create_rag_chain(
|
||||
llm, retriever)
|
||||
|
||||
prompt: str = "Dame información detallada sobre los sercivios que ofrese OneCluster."
|
||||
prompt: str =\
|
||||
"Dame información detallada sobre los sercivios que ofrese OneCluster."
|
||||
respuesta = qa.invoke(
|
||||
{"input": prompt, "chat_history": []}
|
||||
)
|
||||
|
@ -5,10 +5,14 @@ from langchain.chains.combine_documents import create_stuff_documents_chain
|
||||
|
||||
|
||||
def create_rag_chain(llm, retriever):
|
||||
contextualize_q_system_prompt = """Given a chat history and the latest user question \
|
||||
which might reference context in the chat history, formulate a standalone question \
|
||||
which can be understood without the chat history. Do NOT answer the question, \
|
||||
just reformulate it if needed and otherwise return it as is."""
|
||||
contextualize_q_system_prompt = """
|
||||
Given a chat history and the latest user question \
|
||||
which might reference context in the chat history,
|
||||
formulate a standalone question \
|
||||
which can be understood without the chat history.
|
||||
Do NOT answer the question, \
|
||||
just reformulate it if needed and otherwise return it as is.
|
||||
"""
|
||||
contextualize_q_prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
("system", contextualize_q_system_prompt),
|
||||
@ -21,12 +25,13 @@ def create_rag_chain(llm, retriever):
|
||||
)
|
||||
|
||||
# ___________________Chain con el chat history_______________________-
|
||||
qa_system_prompt = """You are an assistant for question-answering tasks. \
|
||||
qa_system_prompt = """
|
||||
You are an assistant for question-answering tasks. \
|
||||
Use the following pieces of retrieved context to answer the question. \
|
||||
If you don't know the answer, just say that you don't know. \
|
||||
The length of the answer should be sufficient to address what is being asked, \
|
||||
The length of the answer should be sufficient to address
|
||||
what is being asked, \
|
||||
meaning don't limit yourself in length.\
|
||||
|
||||
{context}"""
|
||||
qa_prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
@ -37,4 +42,5 @@ def create_rag_chain(llm, retriever):
|
||||
)
|
||||
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
|
||||
|
||||
return create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
||||
return create_retrieval_chain(
|
||||
history_aware_retriever, question_answer_chain)
|
||||
|
@ -4,7 +4,9 @@ from langchain_chroma import Chroma
|
||||
def create_retriever(embeddings, persist_directory: str):
|
||||
# Cargamos la vectorstore
|
||||
# vectordb = Chroma.from_documents(
|
||||
# persist_directory=st.session_state.persist_directory, # Este es el directorio del la vs del docuemnto del usuario que se encuentra cargado en la session_state.
|
||||
# persist_directory=st.session_state.persist_directory,
|
||||
# Este es el directorio del la vs del docuemnto del usuario
|
||||
# que se encuentra cargado en la session_state.
|
||||
# embedding_function=embeddings,
|
||||
# )
|
||||
vectordb = Chroma(
|
||||
|
@ -13,3 +13,5 @@ def create_verctorstore(docs_split: list, embeddings, file_name: str):
|
||||
documents=docs_split,
|
||||
embedding=embeddings,
|
||||
)
|
||||
|
||||
return vectordb
|
||||
|
139
app/server.py
139
app/server.py
@ -1,14 +1,124 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import RedirectResponse
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from langchain_community.chat_models import ChatOpenAI
|
||||
from langserve import add_routes
|
||||
|
||||
from langchain_core.prompts import ChatPromptTemplate
|
||||
|
||||
from langchain_community.tools.tavily_search import TavilySearchResults
|
||||
from langchain_community.tools.gmail.utils import (
|
||||
build_resource_service,
|
||||
get_gmail_credentials)
|
||||
from langchain_community.agent_toolkits import GmailToolkit
|
||||
|
||||
from .langchain_tools.agent_tools import (
|
||||
redact_email,
|
||||
list_calendar_events,
|
||||
create_calendar_event,
|
||||
get_company_info,
|
||||
get_current_date_and_time
|
||||
)
|
||||
|
||||
from langgraph.graph.message import add_messages
|
||||
from langgraph.prebuilt import create_react_agent
|
||||
from langgraph.checkpoint.memory import MemorySaver
|
||||
|
||||
from typing import Annotated
|
||||
from typing_extensions import TypedDict
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
app = FastAPI()
|
||||
llm = ChatOpenAI(
|
||||
model="gpt-4o-mini",
|
||||
temperature=0.9
|
||||
)
|
||||
|
||||
|
||||
# Configuración de Gmail
|
||||
toolkit = GmailToolkit()
|
||||
credentials = get_gmail_credentials(
|
||||
token_file="token.json",
|
||||
scopes=["https://mail.google.com/"],
|
||||
client_secrets_file="credentials.json",
|
||||
)
|
||||
api_resource = build_resource_service(credentials=credentials)
|
||||
toolkit = GmailToolkit(api_resource=api_resource)
|
||||
|
||||
# # Crear herramientas
|
||||
tools = toolkit.get_tools()
|
||||
search = TavilySearchResults(max_results=2)
|
||||
tools.extend([
|
||||
search, redact_email, list_calendar_events,
|
||||
create_calendar_event, get_company_info,
|
||||
get_current_date_and_time])
|
||||
|
||||
# Definir el sistema prompt
|
||||
system_prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
(
|
||||
"system",
|
||||
"Eres Mariana, el asistente virtual de OneCluster, una empresa de "
|
||||
"software que ofrece soluciones personalizadas. Asume el tono de "
|
||||
"J.A.R.V.I.S.: cordial, atento y con tacto en todo momento."
|
||||
),
|
||||
("system",
|
||||
"Preséntate como Mariana en el primer mensaje y pregunta el nombre "
|
||||
"del usuario si no lo tienes registrado."
|
||||
),
|
||||
("system",
|
||||
"Si el usuario ya ha interactuado antes, usa su nombre sin necesidad "
|
||||
"de volver a preguntar."
|
||||
),
|
||||
("system",
|
||||
"Si el primer mensaje del usuario es una solicitud, pregúntale su "
|
||||
"nombre antes de responder si aún no lo conoces."
|
||||
),
|
||||
("system",
|
||||
"OneCluster es una empresa de software especializada en desarrollo a "
|
||||
"medida. Solo responde a preguntas y solicitudes relacionadas con la "
|
||||
"empresa y sus servicios."
|
||||
),
|
||||
("system",
|
||||
"Si necesitas información adicional sobre la empresa, usa la función "
|
||||
"get_company_info."
|
||||
),
|
||||
("system",
|
||||
"Antes de enviar correos o crear eventos, muestra los detalles al "
|
||||
"usuario para que los confirme antes de ejecutar la tarea."
|
||||
),
|
||||
("system",
|
||||
"Si te preguntan algo no relacionado con los servicios de OneCluster,"
|
||||
" responde que solo puedes ayudar con temas relacionados con la "
|
||||
"empresa y sus soluciones."
|
||||
),
|
||||
(
|
||||
"system",
|
||||
"Evita mencionar o hacer alusión a las herramientas que utilizas "
|
||||
"internamente. Esa información es confidencial."
|
||||
),
|
||||
("placeholder", "{messages}"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
# Definir el estado del asistente
|
||||
class State(TypedDict):
|
||||
messages: Annotated[list, add_messages]
|
||||
is_last_step: bool
|
||||
|
||||
|
||||
# Crear el graph con el estado definido
|
||||
graph = create_react_agent(
|
||||
model=llm,
|
||||
tools=tools,
|
||||
state_schema=State,
|
||||
state_modifier=system_prompt,
|
||||
checkpointer=MemorySaver()
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def redirect_root_to_docs():
|
||||
return RedirectResponse("/docs")
|
||||
@ -21,6 +131,29 @@ add_routes(
|
||||
path="/openai"
|
||||
)
|
||||
|
||||
|
||||
@app.post("/process_text")
|
||||
async def process_text(request: Request):
|
||||
data = await request.json()
|
||||
user_input = data.get("text")
|
||||
|
||||
# Procesar el texto con LangChain
|
||||
events = graph.stream(
|
||||
{"messages": [("user", user_input)], "is_last_step": False},
|
||||
config={"configurable": {
|
||||
"thread_id": "thread-1", "recursion_limit": 50}},
|
||||
stream_mode="updates"
|
||||
)
|
||||
|
||||
# Preparar la respuesta
|
||||
response = []
|
||||
for event in events:
|
||||
if "agent" in event:
|
||||
response.append(event["agent"]["messages"][-1].content)
|
||||
|
||||
return JSONResponse(content={'response': response})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
|
0
app/test/__init__.py
Normal file
0
app/test/__init__.py
Normal file
38
app/test/test_main.py
Normal file
38
app/test/test_main.py
Normal file
@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
from fastapi.testclient import TestClient
|
||||
from ..server import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_process_text(mocker):
|
||||
# Configurar el texto de entrada
|
||||
test_input = "Hola, ¿cómo estás?"
|
||||
mock_response = [{
|
||||
"agent": {
|
||||
"messages": [{"content": "Estoy bien, ¿en qué te puedo ayudar?"}]}
|
||||
}]
|
||||
|
||||
# Simular la función `graph.stream` usando mocker
|
||||
mock_stream = mocker.patch('app.graph.stream', return_value=mock_response)
|
||||
|
||||
# Realizar la solicitud POST
|
||||
response = client.post('/process_text', json={"text": test_input})
|
||||
|
||||
# Comprobar que el estado de la respuesta es 200 (éxito)
|
||||
assert response.status_code == 200
|
||||
|
||||
# Verificar la respuesta JSON
|
||||
json_data = response.json()
|
||||
expected_response = {
|
||||
'response': ["Estoy bien, ¿en qué te puedo ayudar?"]
|
||||
}
|
||||
assert json_data == expected_response
|
||||
|
||||
# Confirmar que `graph.stream` fue llamada con los parámetros correctos
|
||||
mock_stream.assert_called_once_with(
|
||||
{"messages": [("user", test_input)], "is_last_step": False},
|
||||
config={"configurable": {
|
||||
"thread_id": "thread-1", "recursion_limit": 50}},
|
||||
stream_mode="updates"
|
||||
)
|
1
app/token.json
Normal file
1
app/token.json
Normal file
@ -0,0 +1 @@
|
||||
{"token": "ya29.a0AeDClZBjncDp4ZwNKNtQ5ghKHPr1IT4XkgDc9QtvhPLrFGAR84f5r5iZPCd91VB7_WoJCG3iGQS0MU1n01xdRlEjDl7wVlKjKF0H680Bdim_bzykCXn3Jj0nVVkkHDOZP7RWeP1oAfY7Vjd4qbw_VxOdOzVzG_Bc6Auy4EJINAaCgYKAcYSARASFQHGX2MipaJllxIRMLCcZb2csCZECA0177", "refresh_token": "1//05nbircha66xlCgYIARAAGAUSNwF-L9IrxbE2v7kfLwXb4u0pD6Rin7xEBOTT83DeH7t2ttfD5CDmUCyhDsOaVRMRK_r8UtdoMq8", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "19011937557-bi5nh4afvg4tuqr87v6dp55qj9a9o1h2.apps.googleusercontent.com", "client_secret": "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", "scopes": ["https://mail.google.com/"], "universe_domain": "googleapis.com", "account": "", "expiry": "2024-10-30T01:16:56.882894Z"}
|
1
app/token_2.json
Normal file
1
app/token_2.json
Normal file
@ -0,0 +1 @@
|
||||
{"token": "ya29.a0AeDClZChMN7SEvjp3dFVZtee2pDoqAoPFC7AWiEeIG7H6qN2HDnf7c6DcFuc--aG60e1cAnOpoKf80H8aqrFFYbF4-F4LE_vz9MY8oc21Ra9PwM16FYxGGKcM2wcrrOGaFncs9Um9_yNxzAa6MUVNq88Y_Bhpr2F2mO3o53NjQaCgYKAZESARASFQHGX2Mi7EodrKchyiyPIZ4y5Lwh0Q0177", "refresh_token": "1//05CtNC-Z3ii8qCgYIARAAGAUSNwF-L9IrbOfrB0kNACEJ5HX4T-fmdNUqsGFqn1QFlvK_1L9h0emULUS1yU85IbaNyESXZSQzHU8", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "629922809906-pl9l1ipout6d5hh19ku50sfvnqgu8ir2.apps.googleusercontent.com", "client_secret": "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", "scopes": ["https://www.googleapis.com/auth/calendar"], "universe_domain": "googleapis.com", "account": "", "expiry": "2024-10-30T01:22:34.287442Z"}
|
1969
poetry.lock
generated
1969
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@ -13,9 +13,23 @@ python = "^3.11"
|
||||
uvicorn = "^0.23.2"
|
||||
langserve = {extras = ["server"], version = ">=0.0.30"}
|
||||
pydantic = "<3"
|
||||
langchain-community = "^0.3.5"
|
||||
langgraph = "^0.2.28"
|
||||
langchain-community = "^0.3.1"
|
||||
langchain-openai = "^0.2.5"
|
||||
langgraph = "^0.2.43"
|
||||
langchain-chroma = "^0.1.4"
|
||||
google = "^3.0.0"
|
||||
google-auth = "^2.35.0"
|
||||
google-auth-oauthlib = "^1.2.0"
|
||||
google-api-python-client = "^2.131.0"
|
||||
flake8 = "^7.1.1"
|
||||
httpx = "^0.27.2"
|
||||
pytest = "^8.3.3"
|
||||
requests = "^2.32.3"
|
||||
jsonify = "^0.5"
|
||||
protobuf = "^3.20.3"
|
||||
pytz = "^2024.2"
|
||||
telebot = "^0.0.5"
|
||||
|
||||
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
|
Loading…
Reference in New Issue
Block a user