Skip to content

Commit

Permalink
Merge branch 'backend/challenges'
Browse files Browse the repository at this point in the history
  • Loading branch information
okbrandon committed Nov 14, 2024
2 parents 21e6754 + 3556fb5 commit be67313
Show file tree
Hide file tree
Showing 97 changed files with 3,573 additions and 1,570 deletions.
37 changes: 37 additions & 0 deletions backend/api/consumers/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,23 @@ async def receive(self, text_data):
raise Exception("Missing conversation ID")
if content is None:
raise Exception("Missing content")
if len(content) > 256:
raise Exception("Message content exceeds 256 characters")

logger.info(f"[{self.__class__.__name__}] Received message from {self.user.username}: {json_data}")
message = await self.add_message_to_conversation(conversation_id, self.user, content)
await self.notify_new_message(conversation_id, self.user, message)

# Check if the message is for the AI user
conversation = await sync_to_async(Conversation.objects.get)(conversationID=conversation_id)
participants = await sync_to_async(list)(conversation.participants.all())
ai_user = next((user for user in participants if user.userID == "user_ai"), None)

if ai_user:
ai_response = await self.get_ai_response(content, conversation_id)
ai_message = await self.add_message_to_conversation(conversation_id, ai_user, ai_response)
await self.notify_new_message(conversation_id, ai_user, ai_message)

case _:
raise Exception(f"Invalid message type: {message_type}")
except Exception as err:
Expand Down Expand Up @@ -162,6 +174,15 @@ async def friend_request(self, event):
except Exception as _:
pass

async def challenge_update(self, event):
try:
await self.send(json.dumps({
"type": "challenge_update",
"invite": event["invite"]
}))
except Exception as _:
pass

@sync_to_async
def add_message_to_conversation(self, conversation_id, user, content):
conversation = Conversation.objects.get(conversationID=conversation_id)
Expand Down Expand Up @@ -206,3 +227,19 @@ def ensure_conversations_exist(self, user):
new_conversation.receipientID = user.userID
new_conversation.participants.add(user, friend)
new_conversation.save()

async def get_ai_response(self, prompt, conversation_id):
url = "https://ai.evan.sh/api/completion"
headers = {
"Authorization": f"Bearer {os.environ.get('CHAT_COMPLETION_TOKEN')}",
"Content-Type": "application/json"
}
data = {
"prompt": prompt,
"conversation_id": conversation_id
}

async with httpx.AsyncClient() as client:
response = await client.post(url, json=data, headers=headers)
response.raise_for_status()
return response.json()["completion"]
291 changes: 178 additions & 113 deletions backend/api/consumers/match.py

Large diffs are not rendered by default.

Loading

0 comments on commit be67313

Please sign in to comment.