Skip to content

Commit

Permalink
Linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Luisotee committed Dec 15, 2024
1 parent b8df9b1 commit af2debb
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 27 deletions.
27 changes: 20 additions & 7 deletions apps/ai_api/eda_ai_api/api/routes/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@
from eda_ai_api.utils.prompts import (
INSUFFICIENT_TEMPLATES,
PROPOSAL_TEMPLATE,
ROUTER_TEMPLATE,
TOPIC_TEMPLATE,
RESPONSE_PROCESSOR_TEMPLATE,
TOPIC_TEMPLATE,
)

router = APIRouter()
Expand Down Expand Up @@ -99,6 +98,15 @@ async def process_decision(
processed_response = await process_llm_response(message, response.text)
return {"response": processed_response}

# Add crew result and return
crew_result = (
ProposalWriterCrew()
.crew()
.kickoff(inputs={"project": community_project, "grant": grant_call})
)
processed_response = await process_llm_response(message, str(crew_result))
return {"response": processed_response}

elif decision == "heartbeat":
processed_response = await process_llm_response(
message, str({"is_alive": True})
Expand All @@ -123,13 +131,15 @@ async def classifier_route(
) -> ClassifierResponse:
"""Main route handler with conversation memory"""
try:
logger.info(
f"New request - Session: {session_id}, User: {session_id + uuid.uuid4().hex}"
)
# Generate a default session_id if none provided
current_session_id = session_id or str(uuid.uuid4())
user_id = f"{current_session_id}_{uuid.uuid4().hex}"

logger.info(f"New request - Session: {current_session_id}, User: {user_id}")

zep = ZepConversationManager()
session_id = await zep.get_or_create_session(
user_id=session_id + uuid.uuid4().hex, session_id=session_id
user_id=user_id, session_id=current_session_id
)

# Process inputs
Expand All @@ -153,7 +163,10 @@ async def classifier_route(
context = "\n".join([f"{msg['role']}: {msg['content']}" for msg in history])

router_prompt = PromptTemplate(
"""Previous conversation:\n{context}\n\nGiven the current user message, determine the appropriate service:\n{message}\n\nReturn only one word (discovery/proposal/onboarding/heartbeat):"""
"""Previous conversation:\n{context}\n\n"""
"""Given the current user message, determine the appropriate service:"""
"""\n{message}\n\n"""
"""Return only one word (discovery/proposal/onboarding/heartbeat):"""
)

response = llm.complete(
Expand Down
9 changes: 7 additions & 2 deletions apps/ai_api/eda_ai_api/utils/audio_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
import tempfile
from typing import Dict, Optional
from typing import Optional

from fastapi import UploadFile

Expand Down Expand Up @@ -40,11 +40,16 @@ async def process_audio_file(audio: UploadFile) -> str:
content = await audio.read()

try:
# Add null check and default to mp3
file_format = "mp3"
if content_type is not None:
file_format = ALLOWED_FORMATS.get(content_type, "mp3")

if content_type == "audio/ogg":
audio_path = convert_ogg(content, output_format="mp3")
else:
with tempfile.NamedTemporaryFile(
suffix=f".{ALLOWED_FORMATS.get(content_type, 'mp3')}", delete=False
suffix=f".{file_format}", delete=False
) as temp_file:
temp_file.write(content)
audio_path = temp_file.name
Expand Down
2 changes: 1 addition & 1 deletion apps/ai_api/eda_ai_api/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
from loguru import logger


def setup_logging():
def setup_logger() -> None:
logger.add("api.log", rotation="500 MB")
7 changes: 5 additions & 2 deletions apps/ai_api/eda_ai_api/utils/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ async def get_or_create_session(
if session_id:
try:
await self.client.memory.get(session_id=session_id)
logger.info(f"Found existing session: {session_id}")
return session_id
except Exception:
pass
except Exception as e:
logger.warning(f"Failed to get session {session_id}: {str(e)}")
# Continue to create new session

user_id = user_id or uuid.uuid4().hex
await self.client.user.add(
Expand All @@ -35,6 +37,7 @@ async def get_or_create_session(
)

await self.client.memory.add(session_id=new_session_id, messages=[])
logger.info(f"Created new session: {new_session_id}")

return new_session_id

Expand Down
33 changes: 18 additions & 15 deletions apps/ai_api/eda_ai_api/utils/prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@
{context}
The user wants to write a proposal but hasn't provided enough information.
Generate a friendly response in the same language as the user's message asking for:
1. The project name and brief description
2. The specific grant program they're applying to (if any)
3. The main objectives of their project
4. The target community or region
Generate a friendly response asking for:
1. Project name and brief description
2. Specific grant program (if any)
3. Main project objectives
4. Target community/region
User message: {message}
Expand All @@ -59,11 +59,11 @@
"""Previous conversation:
{context}
The user wants to find grant opportunities but hasn't provided enough information.
Generate a friendly response in the same language as the user's message asking for:
1. The main topics or areas of their project
2. The target region or community
3. Any specific funding requirements or preferences
The user wants to find grant opportunities but needs more information.
Generate a friendly response asking for:
1. Main project topics/areas
2. Target region/community
3. Funding requirements/preferences
User message: {message}
Expand All @@ -72,7 +72,8 @@
}

RESPONSE_PROCESSOR_TEMPLATE = PromptTemplate(
"""IMPORTANT: You must respond in exactly the same language as the user's original message:
"""IMPORTANT: You must respond in exactly the same language as the user's
original message:
{original_message}
Process this response to:
Expand All @@ -85,11 +86,13 @@
- ```code``` for technical terms
- ~strikethrough~ for corrections
- Lists with emoji bullets
- For URLs: Write "Link: " followed by the plain URL (no markdown)
Example: "Link: https://example.com"
- For URLs:
Write "Link: " followed by URL
Example:
Link: http://example.com
5. If response looks like JSON, convert to natural language in the user's language:
- For heartbeat: "*Yes, I'm here! 🟢*\n_Ready to help you!_" (translate to match user's language)
- For errors: "⚠️ *Error*: _[error message]_" (translate to match user's language)
- For heartbeat: "*Yes, I'm here! 🟢*\n_Ready to help you!_"
- For errors: "⚠️ *Error*: _[error message]_"
- For other JSON: Convert to organized message with formatting (in user's language)
Original response:
Expand Down

0 comments on commit af2debb

Please sign in to comment.