amkyawdev commited on
Commit
4e92cd9
·
verified ·
1 Parent(s): d31477d

feat: Add Chat endpoint for AI conversation

Browse files
Files changed (1) hide show
  1. src/api/agents/chat/router.py +123 -0
src/api/agents/chat/router.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chat Agent Router - API Endpoints for Chat functionality
3
+ """
4
+ from fastapi import APIRouter, HTTPException
5
+ from pydantic import BaseModel, Field
6
+ from typing import List, Optional, Dict, Any
7
+ from src.services.groq_service import generate_response
8
+ from src.api.core.logger import logger
9
+
10
+ router = APIRouter()
11
+
12
+
13
+ class ChatMessage(BaseModel):
14
+ """Chat message model"""
15
+ role: str = Field(..., description="Role: 'user' or 'assistant'")
16
+ content: str = Field(..., description="Message content")
17
+
18
+
19
+ class ChatRequest(BaseModel):
20
+ """Request model for chat"""
21
+ message: str = Field(..., description="User message")
22
+ context: Optional[Dict[str, Any]] = Field(default=None, description="Additional context")
23
+ conversation_id: Optional[str] = Field(default=None, description="Conversation ID for history")
24
+
25
+
26
+ class ChatResponse(BaseModel):
27
+ """Response model for chat"""
28
+ response: str
29
+ conversation_id: Optional[str] = None
30
+ model: str = "llama-3.1-8b-instant"
31
+
32
+
33
+ # Simple in-memory conversation storage
34
+ conversations: Dict[str, List[Dict[str, str]]] = {}
35
+
36
+
37
+ @router.post("/chat", response_model=ChatResponse)
38
+ async def chat(request: ChatRequest) -> ChatResponse:
39
+ """
40
+ Chat endpoint - AI conversation
41
+
42
+ - **message**: User's message
43
+ - **context**: Optional context data
44
+ - **conversation_id**: Optional conversation ID for history
45
+ """
46
+ try:
47
+ logger.info(f"Chat request: {request.message[:50]}...")
48
+
49
+ # Get or create conversation
50
+ conv_id = request.conversation_id or "default"
51
+ if conv_id not in conversations:
52
+ conversations[conv_id] = []
53
+
54
+ # Build messages with history
55
+ messages = [
56
+ {
57
+ "role": "system",
58
+ "content": """You are AmkyawDev AI Assistant, a helpful and friendly AI assistant.
59
+ You can help with coding, answering questions, and various tasks.
60
+ Always be helpful, polite, and provide accurate information."""
61
+ }
62
+ ]
63
+
64
+ # Add conversation history
65
+ messages.extend(conversations[conv_id][-10:]) # Keep last 10 messages
66
+
67
+ # Add current message
68
+ messages.append({"role": "user", "content": request.message})
69
+
70
+ # Generate response
71
+ response_text = await generate_response(
72
+ messages=messages,
73
+ model="llama-3.1-8b-instant",
74
+ temperature=0.7,
75
+ max_tokens=2048
76
+ )
77
+
78
+ # Save to conversation history
79
+ conversations[conv_id].append({"role": "user", "content": request.message})
80
+ conversations[conv_id].append({"role": "assistant", "content": response_text})
81
+
82
+ # Keep history limited
83
+ if len(conversations[conv_id]) > 20:
84
+ conversations[conv_id] = conversations[conv_id][-20:]
85
+
86
+ return ChatResponse(
87
+ response=response_text,
88
+ conversation_id=conv_id,
89
+ model="llama-3.1-8b-instant"
90
+ )
91
+
92
+ except Exception as e:
93
+ logger.error(f"Chat error: {str(e)}")
94
+ raise HTTPException(status_code=500, detail=str(e))
95
+
96
+
97
+ @router.get("/conversations")
98
+ async def get_conversations() -> Dict[str, Any]:
99
+ """Get all conversation IDs"""
100
+ return {
101
+ "conversations": list(conversations.keys()),
102
+ "count": len(conversations)
103
+ }
104
+
105
+
106
+ @router.delete("/conversations/{conversation_id}")
107
+ async def delete_conversation(conversation_id: str) -> Dict[str, str]:
108
+ """Delete a conversation"""
109
+ if conversation_id in conversations:
110
+ del conversations[conversation_id]
111
+ return {"status": "deleted", "conversation_id": conversation_id}
112
+ raise HTTPException(status_code=404, detail="Conversation not found")
113
+
114
+
115
+ @router.get("/conversations/{conversation_id}")
116
+ async def get_conversation(conversation_id: str) -> Dict[str, Any]:
117
+ """Get conversation history"""
118
+ if conversation_id in conversations:
119
+ return {
120
+ "conversation_id": conversation_id,
121
+ "messages": conversations[conversation_id]
122
+ }
123
+ raise HTTPException(status_code=404, detail="Conversation not found")