File size: 1,802 Bytes
0e4a27a
5a55b5b
0e4a27a
5a55b5b
5b7d0e6
0e4a27a
 
 
5b7d0e6
0e4a27a
 
5b7d0e6
0e4a27a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6dd20e
0e4a27a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import html
from dataclasses import dataclass
from typing import Iterable

from buster.formatter.base import Response, ResponseFormatter, Source


@dataclass
class HTMLResponseFormatter(ResponseFormatter):
    """Format the answer in HTML."""

    source_template: str = """<li><a href='{source.url}'>πŸ”— {source.source}</a></li>"""
    error_msg_template: str = """<div class="error">Something went wrong:\n<p>{response.error_msg}</p></div>"""
    error_fallback_template: str = """<div class="error">Something went very wrong.</div>"""
    sourced_answer_template: str = (
        """<div class="answer"><p>{response.text}</p></div>\n"""
        """<div class="sources>πŸ“ Here are the sources I used to answer your question:\n"""
        """<ol>\n{sources}</ol></div>\n"""
        """<div class="footer">I'm a chatbot, bleep bloop.</div>"""
    )
    unsourced_answer_template: str = (
        """<div class="answer">{response.text}</div>\n<div class="footer">I'm a chatbot, bleep bloop.</div>"""
    )

    def sources_list(self, sources: Iterable[Source]) -> str | None:
        """Format sources into a list."""
        items = [self.source_item(source) for source in sources]
        if not items:
            return None  # No list needed.

        return "\n".join(items)

    def __call__(self, response: Response, sources: Iterable[Source]) -> str:
        # Escape any html in the text.
        response = Response(
            html.escape(response.text) if response.text else response.text,
            response.error,
            html.escape(response.error_msg) if response.error_msg else response.error_msg,
        )
        sources = (Source(html.escape(source.title), source.url, source.question_similarity) for source in sources)
        return super().__call__(response, sources)