chore(cleanup): remove contact-related files and update JWT expiration time settings

This commit is contained in:
Davidson Gomes
2025-05-07 11:43:00 -03:00
parent 8979251541
commit 0e3c331a72
21 changed files with 151 additions and 744 deletions

View File

@@ -315,13 +315,13 @@ class A2ATaskManager:
)
# Collect the chunks of the agent's response
contact_id = task_params.sessionId
external_id = task_params.sessionId
full_response = ""
# We use the same streaming function used in the WebSocket
async for chunk in run_agent_stream(
agent_id=str(agent.id),
contact_id=contact_id,
external_id=external_id,
message=query,
session_service=session_service,
artifacts_service=artifacts_service,
@@ -438,13 +438,13 @@ class A2ATaskManager:
async def _run_agent(self, agent: Agent, query: str, session_id: str) -> str:
"""Executes the agent to process the user query."""
try:
# We use the session_id as contact_id to maintain the conversation continuity
contact_id = session_id
# We use the session_id as external_id to maintain the conversation continuity
external_id = session_id
# We call the same function used in the chat API
final_response = await run_agent(
agent_id=str(agent.id),
contact_id=contact_id,
external_id=external_id,
message=query,
session_service=session_service,
artifacts_service=artifacts_service,

View File

@@ -16,7 +16,7 @@ logger = setup_logger(__name__)
async def run_agent(
agent_id: str,
contact_id: str,
external_id: str,
message: str,
session_service: DatabaseSessionService,
artifacts_service: InMemoryArtifactService,
@@ -27,7 +27,9 @@ async def run_agent(
):
exit_stack = None
try:
logger.info(f"Starting execution of agent {agent_id} for contact {contact_id}")
logger.info(
f"Starting execution of agent {agent_id} for external_id {external_id}"
)
logger.info(f"Received message: {message}")
get_root_agent = get_agent(db, agent_id)
@@ -50,22 +52,22 @@ async def run_agent(
artifact_service=artifacts_service,
memory_service=memory_service,
)
adk_session_id = contact_id + "_" + agent_id
adk_session_id = external_id + "_" + agent_id
if session_id is None:
session_id = adk_session_id
logger.info(f"Searching session for contact {contact_id}")
logger.info(f"Searching session for external_id {external_id}")
session = session_service.get_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)
if session is None:
logger.info(f"Creating new session for contact {contact_id}")
logger.info(f"Creating new session for external_id {external_id}")
session = session_service.create_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)
@@ -80,7 +82,7 @@ async def run_agent(
async def process_events():
try:
events_async = agent_runner.run_async(
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
new_message=content,
)
@@ -139,7 +141,7 @@ async def run_agent(
# Add the session to memory after completion
completed_session = session_service.get_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)
@@ -180,7 +182,7 @@ async def run_agent(
async def run_agent_stream(
agent_id: str,
contact_id: str,
external_id: str,
message: str,
session_service: DatabaseSessionService,
artifacts_service: InMemoryArtifactService,
@@ -190,7 +192,7 @@ async def run_agent_stream(
) -> AsyncGenerator[str, None]:
try:
logger.info(
f"Starting streaming execution of agent {agent_id} for contact {contact_id}"
f"Starting streaming execution of agent {agent_id} for external_id {external_id}"
)
logger.info(f"Received message: {message}")
@@ -214,22 +216,22 @@ async def run_agent_stream(
artifact_service=artifacts_service,
memory_service=memory_service,
)
adk_session_id = contact_id + "_" + agent_id
adk_session_id = external_id + "_" + agent_id
if session_id is None:
session_id = adk_session_id
logger.info(f"Searching session for contact {contact_id}")
logger.info(f"Searching session for external_id {external_id}")
session = session_service.get_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)
if session is None:
logger.info(f"Creating new session for contact {contact_id}")
logger.info(f"Creating new session for external_id {external_id}")
session = session_service.create_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)
@@ -238,7 +240,7 @@ async def run_agent_stream(
try:
events_async = agent_runner.run_async(
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
new_message=content,
)
@@ -252,7 +254,7 @@ async def run_agent_stream(
completed_session = session_service.get_session(
app_name=agent_id,
user_id=contact_id,
user_id=external_id,
session_id=adk_session_id,
)

View File

@@ -1,109 +0,0 @@
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from fastapi import HTTPException, status
from src.models.models import Contact
from src.schemas.schemas import ContactCreate
from typing import List, Optional
import uuid
import logging
logger = logging.getLogger(__name__)
def get_contact(db: Session, contact_id: uuid.UUID) -> Optional[Contact]:
"""Search for a contact by ID"""
try:
contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact:
logger.warning(f"Contact not found: {contact_id}")
return None
return contact
except SQLAlchemyError as e:
logger.error(f"Error searching for contact {contact_id}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error searching for contact",
)
def get_contacts_by_client(
db: Session, client_id: uuid.UUID, skip: int = 0, limit: int = 100
) -> List[Contact]:
"""Search for contacts of a client with pagination"""
try:
return (
db.query(Contact)
.filter(Contact.client_id == client_id)
.offset(skip)
.limit(limit)
.all()
)
except SQLAlchemyError as e:
logger.error(f"Error searching for contacts of client {client_id}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error searching for contacts",
)
def create_contact(db: Session, contact: ContactCreate) -> Contact:
"""Create a new contact"""
try:
db_contact = Contact(**contact.model_dump())
db.add(db_contact)
db.commit()
db.refresh(db_contact)
logger.info(f"Contact created successfully: {db_contact.id}")
return db_contact
except SQLAlchemyError as e:
db.rollback()
logger.error(f"Error creating contact: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error creating contact",
)
def update_contact(
db: Session, contact_id: uuid.UUID, contact: ContactCreate
) -> Optional[Contact]:
"""Update an existing contact"""
try:
db_contact = get_contact(db, contact_id)
if not db_contact:
return None
for key, value in contact.model_dump().items():
setattr(db_contact, key, value)
db.commit()
db.refresh(db_contact)
logger.info(f"Contact updated successfully: {contact_id}")
return db_contact
except SQLAlchemyError as e:
db.rollback()
logger.error(f"Error updating contact {contact_id}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error updating contact",
)
def delete_contact(db: Session, contact_id: uuid.UUID) -> bool:
"""Remove a contact"""
try:
db_contact = get_contact(db, contact_id)
if not db_contact:
return False
db.delete(db_contact)
db.commit()
logger.info(f"Contact removed successfully: {contact_id}")
return True
except SQLAlchemyError as e:
db.rollback()
logger.error(f"Error removing contact {contact_id}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error removing contact",
)

View File

@@ -197,10 +197,32 @@ class WorkflowAgent(BaseAgent):
print(f"\n🔄 CONDITION: {label} (Cycle {cycle_count})")
content = state.get("content", [])
print(f"Evaluating condition for content: '{content}'")
conversation_history = state.get("conversation_history", [])
# Obter apenas o evento mais recente para avaliação
latest_event = None
if content and len(content) > 0:
# Ignorar eventos gerados por nós de condição para avaliação
for event in reversed(content):
# Verificar se é um evento gerado pelo condition_node
if (
event.author != "agent"
or not hasattr(event.content, "parts")
or not event.content.parts
):
latest_event = event
break
if latest_event:
print(
f"Avaliando condição apenas para o evento mais recente: '{latest_event}'"
)
# Usar apenas o evento mais recente para avaliação de condição
evaluation_state = state.copy()
if latest_event:
evaluation_state["content"] = [latest_event]
session_id = state.get("session_id", "")
conversation_history = state.get("conversation_history", [])
# Check all conditions
conditions_met = []
@@ -213,9 +235,9 @@ class WorkflowAgent(BaseAgent):
expected_value = condition_data.get("value")
print(
f" Checking if {field} {operator} '{expected_value}' (current value: '{state.get(field, '')}')"
f" Checking if {field} {operator} '{expected_value}' (current value: '{evaluation_state.get(field, '')}')"
)
if self._evaluate_condition(condition, state):
if self._evaluate_condition(condition, evaluation_state):
conditions_met.append(condition_id)
condition_details.append(
f"{field} {operator} '{expected_value}'"
@@ -474,14 +496,35 @@ class WorkflowAgent(BaseAgent):
# If it's a condition node, evaluate the conditions
if node_id in condition_nodes:
conditions = condition_nodes[node_id]
any_condition_met = False
for condition in conditions:
condition_id = condition.get("id")
# Get latest event for evaluation, ignoring condition node informational events
content = state.get("content", [])
latest_event = None
for event in reversed(content):
# Skip events generated by condition nodes
if (
event.author != "agent"
or not hasattr(event.content, "parts")
or not event.content.parts
):
latest_event = event
break
evaluation_state = state.copy()
if latest_event:
evaluation_state["content"] = [latest_event]
# Check if the condition is met
is_condition_met = self._evaluate_condition(condition, state)
is_condition_met = self._evaluate_condition(
condition, evaluation_state
)
if is_condition_met:
any_condition_met = True
print(
f"Condition {condition_id} met. Moving to the next node."
)
@@ -498,12 +541,20 @@ class WorkflowAgent(BaseAgent):
)
# If no condition is met, use the bottom-handle if available
if node_id in edges_map and "bottom-handle" in edges_map[node_id]:
print("No condition met. Using default path (bottom-handle).")
return edges_map[node_id]["bottom-handle"]
else:
print("No condition met and no default path. Closing the flow.")
return END
if not any_condition_met:
if (
node_id in edges_map
and "bottom-handle" in edges_map[node_id]
):
print(
"No condition met. Using default path (bottom-handle)."
)
return edges_map[node_id]["bottom-handle"]
else:
print(
"No condition met and no default path. Closing the flow."
)
return END
# For regular nodes, simply follow the first available connection
if node_id in edges_map: