Skip to content

Commit

Permalink
Add chat_history
Browse files Browse the repository at this point in the history
  • Loading branch information
epoz committed Dec 18, 2023
1 parent cfdc897 commit f6c7f24
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 0 deletions.
78 changes: 78 additions & 0 deletions src/app/chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import os, json, random, httpx, logging, sqlite3
from markdown_it import MarkdownIt
from jinja2 import Markup
from fastapi import Depends, FastAPI, Request, HTTPException, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from .main import app, templates
from .config import (
CHATDB_FILEPATH,
DEBUG,
)

if DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig()

CHATDB = sqlite3.connect(CHATDB_FILEPATH)


def format_history(history: dict):
md = MarkdownIt()
# We would like to modify the messages, so we need to make a copy
new_history = []
for m in history.get("messages", []):
try:
if type(m) == str:
m = {"role": "assistant", "content": m}
if m.get("role") == "assistant" and m.get("content"):
m["content_html"] = Markup(md.render(m.get("content", "")))
if m.get("role") == "function" and m.get("content"):
try:
m["content_json"] = json.loads(m["content"])
except:
logging.exception(f"Exception decoding {m['content']}")
new_history.append(m)
except:
logging.exception(f"Exception decoding {m}")
history["messages"] = new_history
return history


def get_chat(chat_id: str):
tmp = CHATDB.execute(
"select user, history from user_chat_history where id = ?",
(chat_id,),
).fetchone()
if not tmp:
raise HTTPException(404, f"Conversation {chat_id} not found")
huser, history = tmp
history = format_history(json.loads(history))

return history


@app.get("/chat/{chat_id}.json")
async def chat_json(request: Request, chat_id: str):
history = get_chat(chat_id)
return JSONResponse(history)


@app.get("/chat/{chat_id}")
async def chat_history_id(request: Request, chat_id: str):
if chat_id != "history":
history = get_chat(chat_id)
else:
history = None

histories = [
json.loads(h[0])
for h in CHATDB.execute("select history from user_chat_history").fetchall()
]
histories.sort(key=lambda x: x["date_created"])
histories.reverse()

return templates.TemplateResponse(
"chat_history.html",
{"request": request, "histories": histories, "history": history},
)
2 changes: 2 additions & 0 deletions src/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,5 @@
a sd:Graph ;
]
] ."""

CHATDB_FILEPATH = os.environ.get("CHATDB_FILEPATH")
1 change: 1 addition & 0 deletions src/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,4 +493,5 @@ def rec_usage(request: Request, path: str):
from .am import *
from .show import *
from .lode import update
from .chat import *
from .schpiel import *
62 changes: 62 additions & 0 deletions src/templates/chat_history.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{% extends "base.html" %}

{% block content %}



<div class="container" style="display: flex; height: 100vh; width: 100%">

<div class="left-column" style="flex: 1; background-color: #e0e0e0; padding: 20px;">
<h4>Conversations</h4>
<div style="max-height: 90vh; overflow-y: scroll">{% for history in histories %}
<div style="margin-top: 0.75vh; font-size: 75%">
<a href="/chat/{{history.id}}">{{history.date_created}}</a>
</div>
<div>
{% if history.messages|length > 1 %}
<a href="/chat/{{history.id}}.json">{{history.messages[1]['content']}}</a>
{% else %}
Empty conversation
{% endif %}
</div>
{% endfor %}</div>
</div>

<div class="right-column" style="flex: 2; padding: 20px; max-height: 90vh; overflow-y: scroll">
<h1>Chat History</h1>
{% if history %}
<div style="margin-bottom: 1vh">
{{history.date_created}}
<a href="/chat/{{history.id}}.json">JSON</a>
</div>

<div style="max-height: 85vh; overflow-y: scroll" id="messages">
{% for msg in history.messages %}
{% if msg.role == 'assistant' and msg.content %}
<div>{{msg.content_html}}</div>
{% endif %}
{% if msg.role == 'user' and msg.content %}
<div style="font-size: 120%">{{msg.content}}</div>
{% endif %}
{% if msg.role == 'function' and msg.content_json %}
{% for obj in msg.content_json %}
{% if obj.IIIF %}
<a title="{{obj.TITLE or obj.TITLE_NL or obj.TITLE_DE}}" href="{{obj.URL}}" target="_new"><img src="{{obj.IIIF.replace('info.json', 'full/,200/0/default.jpg')}}"></a>
{% endif %}
{% endfor %}


{% endif %}
{% endfor %}
</div>


{% endif %}
</div>
</div>





{% endblock content %}

0 comments on commit f6c7f24

Please sign in to comment.