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

feat: add history api in server #23

Merged
merged 2 commits into from
Feb 17, 2024
Merged
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
2 changes: 1 addition & 1 deletion src/server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ lint:
python -m ruff check .

test:
python -m pytest ./tests
python -m pytest ./tests -n auto -vv
14 changes: 13 additions & 1 deletion src/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
import logging

import uvicorn
from fastapi import FastAPI, WebSocket
from fastapi import Depends, FastAPI, WebSocket

from api.model import MessageResponse, MessageResponseData, MicoMessage
from api.persona import HISTORY_TEACHER
from audio.asr import audio_to_text
from audio.vad import SpeechDetector
from common.config import load_config
from common.constants import SESSION_TIMEOUT_SECONDS
from db.history_service import HistoryService, get_history_svc
from llm.instance import get_llm

logging.basicConfig(level=logging.DEBUG)
Expand All @@ -31,6 +32,10 @@ def create_app() -> FastAPI:
last_message_time: int = 0


def get_hv() -> HistoryService:
return get_history_svc(config.db)


# api for automatic speech recognition, accepts audio stream
@app.websocket("/ws/audio")
async def audio(websocket: WebSocket):
Expand Down Expand Up @@ -77,6 +82,13 @@ async def message(body: MicoMessage) -> MessageResponse:
return MessageResponse(code=0, data=MessageResponseData(action="tts", tts=text))


@app.get("/history")
async def history(
limit: int = 10, offset: int = 0, history_svc: HistoryService = Depends(get_hv)
) -> list[dict]:
return [h.to_dict() for h in history_svc.get(limit, offset)]


async def act(text: str) -> None:
"""
do something with the text, e.g. send it to a chatbot
Expand Down
3 changes: 1 addition & 2 deletions src/server/db/history_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,13 @@ def save(
def get(self, limit: int = 10, offset: int = 0) -> list[History]:
return list(
History.select()
.where(History.provider == self.provider)
.order_by(History.timestamp.desc())
.limit(limit)
.offset(offset)
)


def get_history_svc(config: DataBaseConfig | None) -> HistoryService:
def get_history_svc(config: DataBaseConfig | None = None) -> HistoryService:
if config and config.url:
init_db(config)
return HistorySvcDB("moonshot")
Expand Down
4 changes: 4 additions & 0 deletions src/server/db/models/history.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from peewee import AutoField, CharField, IntegerField, TextField
from playhouse.shortcuts import model_to_dict # type:ignore

from db.models import BaseModel

Expand All @@ -10,3 +11,6 @@ class History(BaseModel):
timestamp = IntegerField()
# xiaomi, github-co-pilot, moonshot, etc
provider = CharField()

def to_dict(self) -> dict:
return model_to_dict(self)
1 change: 1 addition & 0 deletions src/server/requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ black
mypy
isort
pytest
pytest-xdist

types-requests
types-peewee
Expand Down
29 changes: 29 additions & 0 deletions src/server/tests/test_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from unittest.mock import MagicMock, patch

from fastapi.testclient import TestClient

from app import app as main_app
from db.history_service import MessageRole
from db.models.history import History


@patch("app.get_history_svc")
def test_history(mock_get_history_svc: MagicMock):
client = TestClient(main_app)
mock_hv = MagicMock()
mock_hv.get.return_value = [
History(
id=1,
message="foo",
role=MessageRole.USER,
timestamp=2,
provider="bar",
)
]
mock_get_history_svc.return_value = mock_hv
resp = client.get("/history")
assert resp.status_code == 200
history = resp.json()
assert history == [
{"id": 1, "message": "foo", "role": "user", "timestamp": 2, "provider": "bar"}
]
15 changes: 14 additions & 1 deletion src/server/tests/test_history_service.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
from pathlib import Path
from unittest import TestCase

from common.config import DataBaseConfig
from db.history_service import HistorySvcDummy, MessageRole, get_history_svc


class TestHistorySvcDB(TestCase):
def setUp(self):
# make sure db not exits
self.db_file = f"{self.__class__.__name__}.sqlite3"
self.remove_file(self.db_file)

def tearDown(self):
self.remove_file(self.db_file)

@staticmethod
def remove_file(file: str) -> None:
Path(file).unlink(missing_ok=True)

def test_save(self):
svc = get_history_svc(None)
assert isinstance(svc, HistorySvcDummy)

config: DataBaseConfig = DataBaseConfig(url="sqlite:///:memory:")
config = DataBaseConfig(url=f"sqlite:///{self.db_file}")
svc = get_history_svc(config)
svc.save("message", MessageRole.USER, "moonshot")

Expand Down
Loading