summaryrefslogtreecommitdiff
path: root/rag/generator/cohere.py
blob: 16dfe88f9e980108a4a8ee86dea68ea30e870691 (plain)
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
43
44
45
46
47
import os
from dataclasses import asdict
from typing import Any, Dict, Generator, List

import cohere
from loguru import logger as log

from .abstract import AbstractGenerator
from .prompt import ANSWER_INSTRUCTION, Prompt


class Cohere(metaclass=AbstractGenerator):
    def __init__(self) -> None:
        self.client = cohere.Client(os.environ["COHERE_API_KEY"])

    def generate(self, prompt: Prompt) -> Generator[Any, Any, Any]:
        log.debug("Generating answer from cohere...")
        query = f"{prompt.query}\n\n{ANSWER_INSTRUCTION}"
        for event in self.client.chat_stream(
            message=query,
            documents=[asdict(d) for d in prompt.documents],
            prompt_truncation="AUTO",
        ):
            if event.event_type == "text-generation":
                yield event.text
            elif event.event_type == "citation-generation":
                yield event.citations
            elif event.event_type == "stream-end":
                yield event.finish_reason

    def chat(
        self, prompt: Prompt, messages: List[Dict[str, str]]
    ) -> Generator[Any, Any, Any]:
        log.debug("Generating answer from cohere...")
        query = f"{prompt.query}\n\n{ANSWER_INSTRUCTION}"
        for event in self.client.chat_stream(
            message=query,
            documents=[asdict(d) for d in prompt.documents],
            chat_history=messages,
            prompt_truncation="AUTO",
        ):
            if event.event_type == "text-generation":
                yield event.text
            # elif event.event_type == "citation-generation":
            #     yield event.citations
            elif event.event_type == "stream-end":
                yield event.finish_reason