summaryrefslogtreecommitdiffstats
path: root/g4f/Provider/Hugchat.py
blob: 80062af1ce3ac247868ac5dd5f523b3f4ddfbc10 (plain) (blame)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
has_module = False
try:
    from hugchat.hugchat import ChatBot
except ImportError:
    has_module = False

from .base_provider import BaseProvider, get_cookies
from g4f.typing     import CreateResult

class Hugchat(BaseProvider):
    url        = "https://huggingface.co/chat/"
    needs_auth = True
    working    = has_module
    llms       = ['OpenAssistant/oasst-sft-6-llama-30b-xor', 'meta-llama/Llama-2-70b-chat-hf']

    @classmethod
    def create_completion(
        cls,
        model: str,
        messages: list[dict[str, str]],
        stream: bool = False,
        proxy: str = None,
        cookies: str = get_cookies(".huggingface.co"), **kwargs) -> CreateResult:
        
        bot = ChatBot(
            cookies=cookies)
        
        if proxy and "://" not in proxy:
            proxy = f"http://{proxy}"
            bot.session.proxies = {"http": proxy, "https": proxy}

        if model:
            try:
                if not isinstance(model, int):
                    model = cls.llms.index(model)
                bot.switch_llm(model)
            except:
                raise RuntimeError(f"Model are not supported: {model}")

        if len(messages) > 1:
            formatted = "\n".join(
                ["%s: %s" % (message["role"], message["content"]) for message in messages]
            )
            prompt = f"{formatted}\nAssistant:"
        else:
            prompt = messages.pop()["content"]

        try:
            yield bot.chat(prompt, **kwargs)
        finally:
            bot.delete_conversation(bot.current_conversation)
            bot.current_conversation = ""
            pass

    @classmethod
    @property
    def params(cls):
        params = [
            ("model", "str"),
            ("messages", "list[dict[str, str]]"),
            ("stream", "bool"),
            ("proxy", "str"),
        ]
        param = ", ".join([": ".join(p) for p in params])
        return f"g4f.provider.{cls.__name__} supports: ({param})"