Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discord endpoint #133

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

api.add_router("/", "documents.views.router")
api.add_router("/", "chunks.views.router")
api.add_router("/", "bot.views.router")

urlpatterns = [
path("api/", api.urls),
Expand Down
1 change: 1 addition & 0 deletions api/api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"django.contrib.staticfiles",
"chunks.apps.ChunksConfig",
"documents.apps.DocumentsConfig",
"bot.apps.BotConfig",
]

MIDDLEWARE = [
Expand Down
Empty file added api/bot/__init__.py
Empty file.
4 changes: 4 additions & 0 deletions api/bot/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from django.contrib import admin
from .models import Bot

admin.site.register(Bot)
6 changes: 6 additions & 0 deletions api/bot/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class BotConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "bot"
9 changes: 9 additions & 0 deletions api/bot/controllers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from http import HTTPStatus

from bot.models import Bot
from bot.schemas import BotIn, BotOut


def query_llm_controller(payload: BotIn) -> tuple[HTTPStatus, BotOut]:
bot = Bot(**payload.dict())
return HTTPStatus.CREATED, bot
Empty file added api/bot/migrations/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions api/bot/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.db import models


class Bot(models.Model):
text = models.TextField[str, str]()
9 changes: 9 additions & 0 deletions api/bot/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from ninja import Schema


class BotIn(Schema):
text: str


class BotOut(Schema):
text: str
14 changes: 14 additions & 0 deletions api/bot/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest
from django.test import TestCase
from .models import Bot


def create_query():
return Bot.objects.create(text="example")


class BotModelTests(TestCase):
@pytest.mark.django_db
def test_post_method(self):
create_query()
assert Bot.objects.filter(text="example").exists(), "Can't create bot object"
17 changes: 17 additions & 0 deletions api/bot/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import requests

from http import HTTPStatus
from django.http import HttpRequest

from bot.schemas import BotIn, BotOut
from bot.controllers import query_llm_controller

from ninja import Router

router = Router(tags=["Bot"])


@router.post("/bot/", response={HTTPStatus.CREATED: BotOut})
def query_llm(request: HttpRequest, payload: BotIn):
response = requests.post("0.0.0.0:9000/v1/completions", data=payload)
return query_llm_controller(response)
1 change: 1 addition & 0 deletions api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ django-environ = "^0.11.2"
django-ninja = "^1.0.1"
pgvector = "^0.2.4"
django-stubs-ext = "^4.2.7"
requests = "^2.32.2"


[tool.poetry.group.dev.dependencies]
Expand Down
42 changes: 40 additions & 2 deletions discord_bot/discord_bot/bot.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Sets up discord bot."""

import json
import os
from collections import defaultdict
from http import HTTPStatus
from typing import Self

import discord
import requests
from discord.ext import commands

from discord_bot import config
Expand Down Expand Up @@ -40,8 +43,30 @@ async def bad_button(
)


@bot.command()
@commands.has_any_role("Admins", "Moderators")
async def sync(ctx) -> None:
"""Call to Discord API to update slash commands."""
await ctx.send("Synchronizing commands...")
await bot.tree.sync()


def query_llm(prompt, stop_signs):
"""Returns llm's response."""
url = "http://0.0.0.0:9000/v1/completions"
headers = {"Content-Type": "application/json"}
data = {"prompt": prompt, "stop": stop_signs}

response = requests.post(url, headers=headers, data=json.dumps(data), timeout=5)

if response.status_code == HTTPStatus.CREATED:
return response.json()

return response.text


async def get_chats_history():
"""Taking chat conversation from all chanells."""
"""Taking chat conversation from all channels."""
chats_history = defaultdict(list)
for guild in bot.guilds:
readable_channels = filter(
Expand All @@ -58,7 +83,7 @@ async def get_chats_history():

@bot.command()
async def show(ctx: commands.Context, limit: int = 100):
"""Shows what get_chats_history gets."""
"""Shows the results of get_chats_history."""
last_messages = await get_chats_history()
channel_id = ctx.channel.id
if last_messages[channel_id]:
Expand All @@ -68,6 +93,19 @@ async def show(ctx: commands.Context, limit: int = 100):
await ctx.send("Brak ostatnich wiadomości.")


@bot.tree.command(name="chatknml", description="Porozmawiaj z chatbotem")
async def chatknml(interaction: discord.Interaction, *, prompt: str):
"""Passes the prompt to the llm and returns the answer."""
await interaction.response.defer()

query = f"\n\n### Instructions:\n {prompt} \n\n### Response:\n"
stop_signs = ["\n", "###"]

result = query_llm(query, stop_signs)

await interaction.followup.send(result["choices"][0]["text"])


def main():
"""Entrypoint."""
bot.run(os.environ["TOKEN"])
Expand Down
938 changes: 559 additions & 379 deletions discord_bot/poetry.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions discord_bot/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ black = "^24.3.0"
ruff = "^0.1.6"
pytest = "^7.4.3"
pyright = "^1.1.338"
requests = "^2.31.0"

[build-system]
requires = ["poetry-core"]
Expand Down
Loading