├── src ├── __init__.py ├── hugchat │ ├── __init__.py │ ├── types │ │ ├── assistant.py │ │ ├── tool.py │ │ ├── file.py │ │ ├── message.py │ │ └── model.py │ ├── exceptions.py │ ├── login.py │ ├── message.py │ ├── cli.py │ └── hugchat.py ├── unit_test.py └── integration_test.py ├── .gitignore ├── .github ├── workflows │ ├── greetings.yml │ ├── stale.yml │ ├── python-publish.yml │ ├── lint-pull-requests.yml │ ├── hugchat_unit_test.yml │ └── hugchat_integration_test.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── setup.py ├── README_cn.md ├── README.md └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/hugchat/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .venv 3 | cookies.json 4 | test.py 5 | dist/* 6 | *.egg-info 7 | 8 | .idea/ 9 | usercookies/ 10 | fortest/ 11 | .mypy_cache 12 | .vscode/ 13 | build/ 14 | venv -------------------------------------------------------------------------------- /src/hugchat/types/assistant.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | @dataclass 4 | class Assistant: 5 | assistant_id: str 6 | author: str 7 | name: str 8 | model_name: str 9 | pre_prompt: str 10 | description: str 11 | -------------------------------------------------------------------------------- /src/hugchat/types/tool.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Tool: 6 | ''' 7 | Class used to represent tools used by the model 8 | ''' 9 | 10 | uuid: str 11 | result: str 12 | 13 | def __str__(self) -> str: 14 | return f"Tool(uuid={self.uuid}, result={self.result})" 15 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | if: github.repository == 'Soulter/hugging-chat-api' 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | issue-message: "Hi! Thanks for your issue, we will deal with your issue as soon as possible." 17 | pr-message: "Hi! Thanks for your PR, we will deal with your PR as soon as possible.🤗" 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for hugchat 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Help hugchat to improve via a bug report 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | How can we reproduce this bug via code? If possible, please provide the portion of your code showcasing this bug. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Screenshots** 20 | If applicable, add screenshots to help explain your problem. 21 | 22 | **Additional context** 23 | What Operating System are you using? 24 | What Python version are you using? (Found using `python3 --version` or `python --version`) 25 | What version of hugchat are you using? (Found using `pip3 show hugchat` or `pip show hugchat`) 26 | -------------------------------------------------------------------------------- /src/hugchat/types/file.py: -------------------------------------------------------------------------------- 1 | from .message import Conversation 2 | 3 | 4 | class File: 5 | ''' 6 | Class used to represent files created by the model 7 | ''' 8 | 9 | def __init__(self, sha: str, name: str, mime: str, conversation: Conversation): 10 | self.sha = sha 11 | self.name = name 12 | self.mime = mime 13 | 14 | self.conversation = conversation 15 | self.url = self.get_url() 16 | 17 | def get_url(self) -> str: 18 | """ 19 | Gets the url for the given file 20 | """ 21 | 22 | return f"https://huggingface.co/chat/conversation/{self.conversation.id}/output/{self.sha}" 23 | 24 | def download_file(self, chatBot) -> bytes: 25 | """ 26 | Downloads the given file 27 | """ 28 | 29 | r = chatBot.session.get(self.url) 30 | return r.content 31 | 32 | def __str__(self) -> str: 33 | return f"File(url={self.url}, sha={self.sha}, name={self.name}, mime={self.mime})" 34 | -------------------------------------------------------------------------------- /src/hugchat/exceptions.py: -------------------------------------------------------------------------------- 1 | class ModelOverloadedError(Exception): 2 | """ 3 | HF Model Overloaded Error 4 | 5 | Raised when hf return response `{"error":"Model is overloaded", "error_type":"overloaded"}` 6 | """ 7 | pass 8 | 9 | 10 | class ChatBotInitError(Exception): 11 | """ 12 | ChatBot Init Error 13 | 14 | Raised when chatbot init failed 15 | """ 16 | pass 17 | 18 | 19 | class CreateConversationError(Exception): 20 | """ 21 | Create Conversation Error 22 | 23 | Raised when create conversation failed 24 | """ 25 | pass 26 | 27 | 28 | class InvalidConversationIDError(Exception): 29 | """ 30 | Invalid Conversation ID Error 31 | 32 | Raised when using a invalid conversation id 33 | """ 34 | pass 35 | 36 | 37 | class DeleteConversationError(Exception): 38 | """ 39 | Delete Conversation Error 40 | 41 | Raised when delete conversation failed 42 | """ 43 | pass 44 | 45 | 46 | class ChatError(Exception): 47 | """ 48 | Chat Error 49 | 50 | Raised when chat failed 51 | """ 52 | pass 53 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. 2 | # 3 | # You can adjust the behavior by modifying this file. 4 | # For more information, see: 5 | # https://github.com/actions/stale 6 | name: Mark stale issues and pull requests 7 | 8 | on: 9 | schedule: 10 | - cron: '18 0 * * *' 11 | 12 | jobs: 13 | stale: 14 | 15 | runs-on: ubuntu-latest 16 | permissions: 17 | issues: write 18 | pull-requests: write 19 | 20 | steps: 21 | - uses: actions/stale@v5 22 | if: github.repository == 'Soulter/hugging-chat-api' 23 | with: 24 | repo-token: ${{ secrets.GITHUB_TOKEN }} 25 | stale-issue-message: 'This issue was marked as stale because of inactivity.' 26 | close-issue-message: 'This issue was closed because of inactivity.' 27 | stale-pr-message: 'This pull request was marked as stale because of inactivity.' 28 | close-pr-message: 'This pull request was closed because of inactivity.' 29 | stale-issue-label: 'no-issue-activity' 30 | stale-pr-label: 'no-pr-activity' 31 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-pypi 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deploy: 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.x' 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Build package 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/lint-pull-requests.yml: -------------------------------------------------------------------------------- 1 | name: Lints pull requests 2 | 3 | on: 4 | push: 5 | branches: ["master"] 6 | pull_request: 7 | branches: ["master"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Set up Python 3.10 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: "3.10" 23 | 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | pip install flake8 pytest 28 | pip install requests-toolbelt requests 29 | # if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 30 | 31 | - name: Lint with flake8 32 | run: | 33 | # stop the build if there are Python syntax errors or undefined names 34 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 35 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 36 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 37 | 38 | # - name: Test with pytest 39 | # run: | 40 | # pytest 41 | -------------------------------------------------------------------------------- /src/hugchat/types/message.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import List 3 | from .model import Model 4 | 5 | @dataclass 6 | class MessageNode: 7 | ''' 8 | huggingchat message node, currently only maintain id, role, date and content. 9 | ''' 10 | id: str 11 | role: str # "user", "system", or "assistant" 12 | content: str 13 | ancestors: List[str] 14 | children: List[str] 15 | created_at: float # timestamp 16 | updated_at: float # timestamp 17 | 18 | def __str__(self) -> str: 19 | return f"MessageNode(id={self.id}, role={self.role}, content={self.content}, created_at={self.created_at}, updated_at={self.updated_at})" 20 | 21 | 22 | class Conversation: 23 | def __init__( 24 | self, 25 | id: str = None, 26 | title: str = None, 27 | model: Model = None, 28 | system_prompt: str = None, 29 | history: list = [] 30 | ): 31 | """ 32 | Returns a conversation object 33 | """ 34 | 35 | self.id: str = id 36 | self.title: str = title 37 | self.model = model 38 | self.system_prompt: str = system_prompt 39 | self.history: List[MessageNode] = history 40 | 41 | def __str__(self) -> str: 42 | return self.id 43 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_namespace_packages 2 | from setuptools import setup 3 | 4 | setup( 5 | name="hugchat", 6 | version="0.5.1", 7 | description="A huggingchat python api.", 8 | long_description=open("README.md", "rt", encoding="utf-8").read(), 9 | long_description_content_type="text/markdown", 10 | url="https://github.com/Soulter/hugging-chat-api", 11 | project_urls={ 12 | "Bug Report": "https://github.com/Soulter/hugging-chat-api/issues" 13 | }, 14 | author="Soulter", 15 | author_email="905617992@qq.com", 16 | license="GNU Affero General Public License v3.0", 17 | packages=find_namespace_packages("src"), 18 | package_dir={"": "src"}, 19 | py_modules=["hugchat"], 20 | package_data={"": ["*.json"]}, 21 | install_requires=[ 22 | "requests", 23 | "requests_toolbelt", 24 | ], 25 | classifiers=[ 26 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 27 | "Intended Audience :: Developers", 28 | "Intended Audience :: End Users/Desktop", 29 | "Natural Language :: English", 30 | "Topic :: Software Development :: Libraries :: Python Modules", 31 | "Programming Language :: Python :: 3 :: Only", 32 | "Programming Language :: Python :: 3.6", 33 | "Programming Language :: Python :: 3.7", 34 | "Programming Language :: Python :: 3.8", 35 | "Programming Language :: Python :: 3.9", 36 | "Programming Language :: Python :: 3.10", 37 | "Programming Language :: Python :: 3.11", 38 | ], 39 | ) 40 | -------------------------------------------------------------------------------- /.github/workflows/hugchat_unit_test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: hugchat unit test 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] 20 | max-parallel: 1 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | python -m pip install pytest requests pytest-rerunfailures 32 | pip uninstall hugchat 33 | # - name: Lint with flake8 34 | # run: | 35 | # # stop the build if there are Python syntax errors or undefined names 36 | # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | cd src 42 | pytest unit_test.py -s --reruns 3 --reruns-delay 5 43 | -------------------------------------------------------------------------------- /.github/workflows/hugchat_integration_test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: hugchat integration test 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] 20 | max-parallel: 1 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | python -m pip install pytest requests pytest-rerunfailures 32 | pip uninstall hugchat 33 | # - name: Lint with flake8 34 | # run: | 35 | # # stop the build if there are Python syntax errors or undefined names 36 | # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | cd src 42 | pytest integration_test.py -s --reruns 3 --reruns-delay 5 43 | -------------------------------------------------------------------------------- /src/hugchat/types/model.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | class Model: 5 | def __init__( 6 | self, 7 | id: str = None, 8 | name: str = None, 9 | displayName: str = None, 10 | preprompt: str = None, 11 | promptExamples: list = None, 12 | websiteUrl: str = None, 13 | description: str = None, 14 | datasetName: str = None, 15 | datasetUrl: str = None, 16 | modelUrl: str = None, 17 | parameters: dict = None, 18 | unlisted: bool = None, 19 | logoUrl: str = None, 20 | reasoning: bool = None, 21 | multimodal: bool = None, 22 | tools: bool = None, 23 | hasInferenceAPI: bool = None, 24 | ): 25 | """ 26 | Returns a model object 27 | """ 28 | 29 | self.id: str = id 30 | self.name: str = name 31 | self.displayName: str = displayName 32 | 33 | self.preprompt: str = preprompt 34 | self.promptExamples: list = promptExamples 35 | self.websiteUrl: str = websiteUrl 36 | self.description: str = description 37 | 38 | self.datasetName: str = datasetName 39 | self.datasetUrl: str = datasetUrl 40 | self.modelUrl: str = modelUrl 41 | self.parameters: dict = parameters 42 | 43 | self.unlisted: bool = unlisted 44 | self.logoUrl: str = logoUrl 45 | self.reasoning: bool = reasoning 46 | self.multimodal: bool = multimodal 47 | self.tools: bool = tools 48 | self.hasInferenceAPI: bool = hasInferenceAPI 49 | 50 | def __str__(self) -> str: 51 | return self.id 52 | 53 | def display(self): 54 | return f"id: {self.id}\nname:{self.name}\ndisplayName: {self.displayName}\npreprompt: {self.preprompt}\nwebsiteUrl: {self.websiteUrl}\ndescription: {self.description}\nmodelUrl: {self.modelUrl}\nparameters: {self.parameters}" 55 | -------------------------------------------------------------------------------- /src/unit_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | For test hugchat 3 | """ 4 | 5 | # import os 6 | import logging 7 | 8 | from .hugchat.message import MessageStatus, ResponseTypes, Message, MSGTYPE_ERROR 9 | import sys 10 | 11 | logging.basicConfig(level=logging.DEBUG) 12 | 13 | 14 | class MockResponse(): 15 | """ 16 | mock a respone from hugchat api 17 | """ 18 | 19 | def __init__(self, response_list): 20 | self.index = 0 21 | self.response_list = response_list 22 | 23 | def __iter__(self): 24 | return self 25 | 26 | def __next__(self): 27 | if self.index >= len(self.response_list): 28 | raise StopIteration 29 | result = self.response_list[self.index] 30 | self.index += 1 31 | return result 32 | 33 | 34 | class Test(object): 35 | """ 36 | test hugchat api 37 | """ 38 | 39 | def test_web_search_failed_results(self): 40 | response_list = [{ 41 | "type": 42 | ResponseTypes.WEB, 43 | "messageType": 44 | MSGTYPE_ERROR, 45 | "message": 46 | "Failed to parse webpage", 47 | "args": [ 48 | "This operation was aborted", 49 | "https://www.accuweather.com/en/gb/london/ec4a-2/weather-forecast/328328" 50 | ] 51 | }, { 52 | "type": 53 | ResponseTypes.WEB, 54 | "messageType": 55 | ResponseTypes.WEB, 56 | "sources": [{ 57 | "title": "1", 58 | "link": "2", 59 | "hostname": "3" 60 | }] 61 | }, { 62 | "type": 63 | ResponseTypes.WEB, 64 | "messageType": 65 | MSGTYPE_ERROR, 66 | "message": 67 | "Failed to parse webpage", 68 | "args": [ 69 | "This operation was aborted", 70 | "https://www.accuweather.com/en/gb/london/ec4a-2/weather-forecast/328328" 71 | ] 72 | }, { 73 | "type": ResponseTypes.FINAL, 74 | "messageType": "answer", 75 | "text": "Funny joke" 76 | }] 77 | 78 | mock = MockResponse(response_list) 79 | response = Message(mock, web_search=True) 80 | while True: 81 | try: 82 | print(response) 83 | response = next(response) 84 | except StopIteration: 85 | break 86 | assert len(response.web_search_sources 87 | ) == 1 # only the second web search response is valid. 88 | assert response.text == "Funny joke" 89 | -------------------------------------------------------------------------------- /src/integration_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | For test hugchat 3 | """ 4 | 5 | # import os 6 | import logging 7 | 8 | import pytest 9 | 10 | from .hugchat import hugchat, cli 11 | from .hugchat.login import Login 12 | import sys 13 | from unittest.mock import patch 14 | 15 | logging.basicConfig(level=logging.DEBUG) 16 | 17 | EMAIL = "just_a_temp_email@iubridge.com" 18 | PASSWORD = "FOR_TEST_DO_NOT_LOGIN_a1" 19 | 20 | 21 | @pytest.fixture(scope="session") 22 | def login_to_chatbot(): 23 | sign = Login(EMAIL, PASSWORD) 24 | cookies = sign.login() 25 | sign.saveCookiesToDir("./fortest") 26 | assert cookies is not None 27 | chatbot = hugchat.ChatBot(cookies=cookies.get_dict(), default_llm=0) 28 | yield chatbot 29 | chatbot.session.close() 30 | 31 | 32 | class TestAPI: 33 | """ 34 | test hugchat api 35 | """ 36 | 37 | @pytest.fixture(autouse=True) 38 | def setup(self, login_to_chatbot): 39 | """ 40 | setup 41 | """ 42 | self.chatbot = login_to_chatbot 43 | 44 | def test_create_conversation(self): 45 | """ 46 | test create conversation module 47 | """ 48 | global my_conversation 49 | res = self.chatbot.new_conversation() 50 | assert res is not None 51 | self.chatbot.change_conversation(res) 52 | my_conversation = res 53 | print("Test create conversation:", str(res)) 54 | 55 | def test_chat_without_web_search(self): 56 | """ 57 | test chat module without web search 58 | """ 59 | res = str(self.chatbot.chat("Just reply me `test_ok`")) 60 | assert res is not None 61 | 62 | def test_chat_web_search(self): 63 | """ 64 | test chat module with web search 65 | """ 66 | res = str( 67 | self.chatbot.chat( 68 | "What's the weather like in London today? Reply length limited within 20 words.", 69 | web_search=True)) 70 | assert res is not None 71 | 72 | def test_generator(self): 73 | """ 74 | test generator module 75 | """ 76 | res = self.chatbot.chat("Just reply me `test_ok`", 77 | _stream_yield_all=True) 78 | for i in res: 79 | print(i, flush=True) 80 | 81 | assert res is not None 82 | 83 | # def test_delete_conversation(self): 84 | # """ 85 | # test delete conversation module 86 | # """ 87 | # chatbot.delete_conversation(my_conversation) 88 | 89 | def test_delete_all_conversations(self): 90 | """ 91 | test delete all conversations module 92 | """ 93 | self.chatbot.delete_all_conversations() 94 | 95 | def test_cli(self): 96 | global times_run 97 | times_run = -1 98 | 99 | # many not enabled because the CLI is currently very broken 100 | return_strings = [ 101 | "/help", 102 | "Hello!", 103 | # "/new", 104 | # "/ids", 105 | # "/sharewithauthor off" 106 | "/exit" 107 | ] 108 | 109 | def input_callback(_): 110 | global times_run 111 | times_run += 1 112 | 113 | return return_strings[times_run] 114 | 115 | sys.argv = [sys.argv[0]] 116 | 117 | sys.argv.append("-u") 118 | sys.argv.append(EMAIL) 119 | 120 | with patch("getpass.getpass", side_effect=lambda _: PASSWORD): 121 | with patch('builtins.input', side_effect=input_callback): 122 | cli.cli() 123 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 | # hugging-chat-api 2 | 3 | [English](README.md) | 简体中文 4 | 5 | 为聊天机器人等程序打造的非官方的 HuggingChat Python API。 6 | 7 | [![PyPi](https://img.shields.io/pypi/v/hugchat.svg?logo=pypi&logoColor=white)](https://pypi.python.org/pypi/hugchat) 8 | [![Support_Platform](https://img.shields.io/badge/3.6+-%234ea94b.svg?logo=python&logoColor=white)](https://pypi.python.org/pypi/hugchat) 9 | [![DownloadsPW](https://img.shields.io/pypi/dw/hugchat?logo=download&logoColor=white)](https://pypi.python.org/pypi/hugchat) 10 | [![Status](https://img.shields.io/badge/status-operational-%234ea94b.svg?logo=ok&logoColor=white)](https://pypi.python.org/pypi/hugchat) 11 | [![Downloads](https://static.pepy.tech/badge/hugchat?logo=download&logoColor=white)](https://www.pepy.tech/projects/hugchat) 12 | 13 | > **Note** 14 | > 15 | > 某些较新的版本可能包含不向后兼容的更新,建议在出现问题时查看此 README 或 issues。 16 | > 17 | > 近期更新 18 | > - 联网搜索 19 | > - 上下文记忆 20 | > - 支持更改所使用的模型,见[#56](https://github.com/Soulter/hugging-chat-api/issues/56) (v0.0.9) 21 | 22 | ## 安装 23 | 24 | ```bash 25 | pip install hugchat 26 | ``` 27 | 或 28 | ```bash 29 | pip3 install hugchat 30 | ``` 31 | 32 | ## 用法 33 | 34 | ### API 35 | 36 | 以下展示了本库的常见用法,您不一定需要全部使用,可以根据需要添加或删除一些 :) 37 | 38 | ```py 39 | from hugchat import hugchat 40 | from hugchat.login import Login 41 | 42 | # 登录到 huggingface 并为 huggingchat 授权 43 | sign = Login(email, passwd) 44 | cookies = sign.login() 45 | 46 | # 保存 cookies 到本地目录 47 | cookie_path_dir = "./cookies_snapshot" 48 | sign.saveCookiesToDir(cookie_path_dir) 49 | 50 | # 在启动程序时加载 cookies: 51 | # sign = login(email, None) 52 | # cookies = sign.loadCookiesFromDir(cookie_path_dir) # 此步骤将检查指定的文件是否存在,若存在则返回cookies,不存在则报错 53 | 54 | # 创建 ChatBot 对象 55 | chatbot = hugchat.ChatBot(cookies=cookies.get_dict()) # or cookie_path="usercookies/.json" 56 | 57 | # 非流式响应 58 | query_result = chatbot.query("Hi!") 59 | print(query_result) # 纯文本为 query_result["text"] 60 | 61 | # 流式响应 62 | for resp in chatbot.query( 63 | "Hello", 64 | stream=True 65 | ): 66 | print(resp) 67 | 68 | # 使用联网搜索功能 69 | query_result = chatbot.query("Hi!", web_search=True) 70 | print(query_result) # or query_result.text or query_result["text"] 71 | for source in query_result.web_search_sources: 72 | print(source.link) 73 | print(source.title) 74 | print(source.hostname) 75 | 76 | # 创建新的对话 77 | id = chatbot.new_conversation() 78 | chatbot.change_conversation(id) 79 | 80 | # 获取对话列表 81 | conversation_list = chatbot.get_conversation_list() 82 | 83 | # 获取可用的模型列表 84 | models = chatbot.get_available_llm_models() 85 | 86 | # 切换模型 87 | chatbot.switch_llm(0) # 切换到第一个模型 88 | chatbot.switch_llm(1) # 切换到第二个模型 89 | 90 | # 从服务器获取所有回话列表 91 | chatbot.get_remote_conversations(replace_conversation_list=True) 92 | 93 | # [慎用]删除所有回话 94 | chatbot.delete_all_conversations() 95 | ``` 96 | 97 | 98 | `query()` 函数接受以下参数: 99 | 100 | - `text`: Required[str]. 101 | - `retry_count`: 重试次数. Optional[int]. Default is 5 102 | - `web_search` : 是否使用联网搜索. Optional[bool] 103 | 104 | ### CLI 105 | 106 | > `version 0.0.5.2` or newer 107 | 108 | 直接在终端执行以下命令将进入 HugChat 的命令行交互模式: 109 | 110 | ```bash 111 | python -m hugchat.cli 112 | ``` 113 | 114 | CLI模式接受启动参数: 115 | 116 | - `-u ` : 提供账户邮箱以登录。 117 | - `-p` : 重新输入密码,忽略已保存的cookies。 118 | - `-s` : 在CLI模式中启用流式输出。 119 | 120 | CLI模式中的命令: 121 | 122 | - `/new` : 创建并切换到新的对话 123 | - `/ids` : 输出当前会话(Session)中的所有对话ID编号和完整ID字符串 124 | - `/switch ` : 通过对话ID切换到指定的对话 125 | - `/del ` : 删除指定的对话,不会删除活动的对话 126 | - `/clear` : 清除终端内容 127 | - `/llm` : 获取可用的模型列表 128 | - `/llm ` : 通过编号切换到 `/llm` 中可用的某个模型 129 | - `/sharewithauthor ` : 设置是否与模型作者共享对话数据,默认启用 130 | - `/exit`: 退出CLI环境 131 | - `/stream `: 启用或关闭流式输出 132 | - `/web `: 启用或关闭联网搜索 133 | - `/web-hint `: 启用或关闭显示web搜索提示 134 | 135 | - AI是一个活跃的研究领域,存在一些已知问题,例如生成偏见和错误信息。请不要将此应用用于重大决策或咨询。 136 | - 服务器资源宝贵,不建议高频率请求此API。 137 | (`Hugging Face's CTO🤗`点赞了这个建议) 138 |
139 | 140 | ## 声明 141 | 142 | 此仓库不是 [Hugging Face](https://huggingface.co/) 官方产品. 这是一个**个人项目**,与[Hugging Face](https://huggingface.co/)没有任何关联。请不要起诉我们。 143 | 144 | ## Star History 145 | 146 | [![Star History Chart](https://api.star-history.com/svg?repos=Soulter/hugging-chat-api&type=Date)](https://star-history.com/#Soulter/hugging-chat-api&Date) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hugging-chat-api 2 | 3 | English | [简体中文](README_cn.md) 4 | 5 | Unofficial HuggingChat Python API, extensible for chatbots etc. It supports: 6 | 7 | - Basic Chat 8 | - Assistant(Image Generator, [etc.](https://huggingface.co/chat/assistants)) 9 | - Web search 10 | - Memorize context 11 | - [Switch LLMs](https://huggingface.co/chat/models) 12 | - ... 13 | 14 | [![PyPi](https://img.shields.io/pypi/v/hugchat.svg?logo=pypi&logoColor=white)](https://pypi.python.org/pypi/hugchat) 15 | [![Support_Platform](https://img.shields.io/badge/3.6+-%234ea94b.svg?logo=python&logoColor=white)](https://pypi.python.org/pypi/hugchat) 16 | [![DownloadsPW](https://img.shields.io/pypi/dw/hugchat?logo=download&logoColor=white)](https://pypi.python.org/pypi/hugchat) 17 | [![Downloads](https://static.pepy.tech/badge/hugchat?logo=download&logoColor=white)](https://www.pepy.tech/projects/hugchat) 18 | 19 | > **Note** 20 | > 21 | > For the personal reasons, the update of this repo will become slow, and we will ensure that the most basic features can be used normally. Welcome Any PR! 22 | 23 | ## Installation 24 | ```bash 25 | pip3 install hugchat 26 | ``` 27 | 28 | ## Usage 29 | 30 | ### API 31 | 32 | #### Minimal Example 33 | 34 | ```py 35 | from hugchat import hugchat 36 | from hugchat.login import Login 37 | 38 | # Log in to huggingface and grant authorization to huggingchat 39 | # DO NOT EXPOSE YOUR EMAIL AND PASSWORD IN CODES, USE ENVIRONMENT VARIABLES OR CONFIG FILES 40 | EMAIL = "your email" 41 | PASSWD = "your password" 42 | cookie_path_dir = "./cookies/" # NOTE: trailing slash (/) is required to avoid errors 43 | sign = Login(EMAIL, PASSWD) 44 | cookies = sign.login(cookie_dir_path=cookie_path_dir, save_cookies=True) 45 | 46 | chatbot = hugchat.ChatBot(cookies=cookies.get_dict()) 47 | 48 | print(chatbot.chat("Hi!").wait_until_done()) 49 | ``` 50 | 51 | 52 | The following are all common usages of this repo, You may not necessarily use all of them, You can add or delete some as needed :) 53 | 54 | 55 | ```py 56 | from hugchat import hugchat 57 | from hugchat.login import Login 58 | 59 | # Log in to huggingface and grant authorization to huggingchat 60 | EMAIL = "your email" 61 | PASSWD = "your password" 62 | cookie_path_dir = "./cookies/" # NOTE: trailing slash (/) is required to avoid errors 63 | sign = Login(EMAIL, PASSWD) 64 | cookies = sign.login(cookie_dir_path=cookie_path_dir, save_cookies=True) 65 | 66 | # Create your ChatBot 67 | chatbot = hugchat.ChatBot(cookies=cookies.get_dict()) # or cookie_path="usercookies/.json" 68 | 69 | message_result = chatbot.chat("Hi!") # note: message_result is a generator, the method will return immediately. 70 | 71 | # Option 1: Non stream 72 | message_str: str = message_result.wait_until_done() 73 | # get files(such as images) 74 | file_list = message_result.get_files_created() # must call wait_until_done() first! 75 | 76 | # Option 2: Stream response 77 | for resp in chatbot.chat( 78 | "Hello", 79 | stream=True 80 | ): 81 | print(resp) 82 | 83 | # Web search 84 | query_result = chatbot.chat("How many models stored in huggingface?", web_search=True).wait_until_done() 85 | print(query_result) 86 | # You can get the web search results from the query result 87 | for source in query_result.get_search_sources(): 88 | print(source.link, source.title) 89 | 90 | # Create a new conversation 91 | chatbot.new_conversation(switch_to = True) # switch to the new conversation 92 | 93 | # Get conversations on the server that are not from the current session (all your conversations in huggingchat) 94 | conversation_list = chatbot.get_remote_conversations(replace_conversation_list=True) 95 | # Get conversation list(local) 96 | conversation_list = chatbot.get_conversation_list() 97 | 98 | # Get the available models 99 | models = chatbot.get_available_llm_models() 100 | # Switch model with given index 101 | chatbot.switch_llm(0) # Switch to the first model 102 | chatbot.switch_llm(1) # Switch to the second model 103 | 104 | # Get information about the current conversation 105 | info = chatbot.get_conversation_info() 106 | print(info.id, info.title, info.model, info.system_prompt, info.history) 107 | 108 | # Assistant 109 | ASSISTANT_ID = "66017fca58d60bd7d5c5c26c" # get the assistant id from https://huggingface.co/chat/assistants 110 | chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True) # create a new conversation with assistant 111 | 112 | # [DANGER] Delete all the conversations for the logged in user 113 | chatbot.delete_all_conversations() 114 | ``` 115 | 116 | ### CLI 117 | 118 | Simply run the following command in your terminal to start the CLI mode 119 | 120 | ```bash 121 | python -m hugchat.cli 122 | ``` 123 | 124 | CLI params: 125 | 126 | - `-u ` : Provide account email to login. 127 | - `-p` : Force request password to login, ignores saved cookies. 128 | - `-s` : Enable streaming mode output in CLI. 129 | - `-c` : Continue previous conversation in CLI ". 130 | 131 | Commands in cli mode: 132 | 133 | - `/new` : Create and switch to a new conversation. 134 | - `/ids` : Shows a list of all ID numbers and ID strings in *current session*. 135 | - `/switch` : Shows a list of all conversations' info in *current session*. Then you can choose one to switch to. 136 | - `/switch all` : Shows a list of all conversations' info in *your account*. Then you can choose one to switch to. (not recommended if your account has a lot of conversations) 137 | - `/del ` : Deletes the conversation linked with the index passed. Will not delete active session. 138 | - `/delete-all` : Deletes all the conversations for the logged in user. 139 | - `/clear` : Clear the terminal. 140 | - `/llm` : Get available models you can switch to. 141 | - `/llm ` : Switches model to given model index based on `/llm`. 142 | - `/share` : Toggles settings for sharing data with model author. On by default. 143 | - `/exit` : Closes CLI environment. 144 | - `/stream` : Toggles streaming the response. 145 | - `/web` : Toggles web search. 146 | - `/web-hint` : Toggles display web search hint. 147 | 148 | - AI is an area of active research with known problems such as biased generation and misinformation. Do not use this application for high-stakes decisions or advice. 149 | - Server resources are precious, it is not recommended to request this API in a high frequency. 150 | 151 | ## Donations 152 | ❤ 153 | 154 | Buy Me A Coffee 155 | 156 | ## Disclaimers 157 | 158 | This is not an official [Hugging Face](https://huggingface.co/) product. This is a **personal project** and is not affiliated with [Hugging Face](https://huggingface.co/) in any way. Don't sue us. 159 | 160 | ## Star History 161 | 162 | [![Star History Chart](https://api.star-history.com/svg?repos=Soulter/hugging-chat-api&type=Date)](https://star-history.com/#Soulter/hugging-chat-api&Date) 163 | -------------------------------------------------------------------------------- /src/hugchat/login.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | import logging 5 | import re 6 | 7 | 8 | class Login: 9 | 10 | def __init__(self, email: str, passwd: str = "") -> None: 11 | self.DEFAULT_PATH_DIR = os.path.join( 12 | os.path.dirname(os.path.abspath(__file__)), "usercookies") 13 | self.DEFAULT_COOKIE_PATH = self.DEFAULT_PATH_DIR + \ 14 | os.path.join(f"{email}.json") 15 | 16 | self.email: str = email 17 | self.passwd: str = passwd 18 | self.headers = { 19 | "Referer": "https://huggingface.co/", 20 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64", 21 | } 22 | self.cookies = requests.sessions.RequestsCookieJar() 23 | 24 | def login(self, cookie_dir_path: str = None, save_cookies: bool = False) -> requests.sessions.RequestsCookieJar: 25 | ''' 26 | Login to huggingface.co with given email and password. 27 | - If cookie_dir_path is given, load cookies from the path. If path is not exist, raise an exception. 28 | - If save_cookies is True, save cookies to the givev path (if cookie_dir_path is not given, save to default path `./usercookies`). 29 | - Return cookies if login success, otherwise raise an exception. 30 | ''' 31 | 32 | if not cookie_dir_path: 33 | cookie_dir_path = self.DEFAULT_PATH_DIR 34 | 35 | # validate cookies content before use 36 | if os.path.exists(cookie_dir_path) and os.path.exists(self._get_cookie_path(cookie_dir_path)): 37 | with open(self._get_cookie_path(cookie_dir_path), 'r+') as f_cookies: 38 | cookies = json.load(f_cookies) 39 | try: 40 | list(cookies.keys()).index('token') 41 | list(cookies.keys()).index('hf-chat') 42 | return self.load_cookies(cookie_dir_path) 43 | except Exception as e: 44 | print('error during validating cookies') 45 | 46 | self._sign_in_with_email() 47 | location = self._get_auth_url() 48 | if self._grant_auth(location): 49 | if save_cookies: 50 | self.save_cookies(cookie_dir_path) 51 | return self.cookies 52 | else: 53 | raise Exception( 54 | f"Grant auth fatal, please check your email or password\ncookies gained: \n{self.cookies}") 55 | 56 | def save_cookies(self, cookie_dir_path: str = './usercookies') -> str: 57 | ''' 58 | cookies will be saved into: cookie_dir_path/.json 59 | ''' 60 | return self.saveCookiesToDir(cookie_dir_path) 61 | 62 | def saveCookiesToDir(self, cookie_dir_path: str = './usercookies') -> str: 63 | """ 64 | alias of save_cookies 65 | """ 66 | cookie_dir_path = self.DEFAULT_PATH_DIR if not cookie_dir_path else cookie_dir_path 67 | if not cookie_dir_path.endswith("/"): 68 | cookie_dir_path += "/" 69 | cookie_path = cookie_dir_path + f"{self.email}.json" 70 | if not os.path.exists(cookie_dir_path): 71 | logging.info("Cookie directory not exist, creating...") 72 | os.makedirs(cookie_dir_path) 73 | logging.info(f"Cookie store path: {cookie_path}") 74 | 75 | with open(cookie_path, "w", encoding="utf-8") as f: 76 | f.write(json.dumps(self.cookies.get_dict())) 77 | return cookie_path 78 | 79 | def load_cookies(self, cookie_dir_path: str = './usercookies') -> requests.sessions.RequestsCookieJar: 80 | ''' 81 | cookies will be loaded from: cookie_dir_path/.json 82 | ''' 83 | return self.loadCookiesFromDir(cookie_dir_path) 84 | 85 | def loadCookiesFromDir(self, cookie_dir_path: str = './usercookies') -> requests.sessions.RequestsCookieJar: 86 | """ 87 | alias of load_cookies 88 | """ 89 | cookie_dir_path = self.DEFAULT_PATH_DIR if not cookie_dir_path else cookie_dir_path 90 | cookie_path = self._get_cookie_path(cookie_dir_path) 91 | if not cookie_path: 92 | raise Exception(f"Cookie not found. please check the path given: {cookie_dir_path}.\n" + 93 | f"Cookie file must be named like this: 'your_email'+'.json': '{self.email}.json'") 94 | 95 | with open(cookie_path, "r", encoding="utf-8") as f: 96 | try: 97 | js = json.loads(f.read()) 98 | for i in js.keys(): 99 | self.cookies.set(i, js[i]) 100 | logging.info(f"{i} loaded") 101 | return self.cookies 102 | except: 103 | raise Exception( 104 | "load cookies from files fatal. Please check the format") 105 | 106 | def _request_get(self, url: str, params=None, allow_redirects=True) -> requests.Response: 107 | res = requests.get( 108 | url, 109 | params=params, 110 | headers=self.headers, 111 | cookies=self.cookies, 112 | allow_redirects=allow_redirects, 113 | ) 114 | self._refresh_cookies(res.cookies) 115 | return res 116 | 117 | def _request_post(self, url: str, headers=None, params=None, data=None, stream=False, 118 | allow_redirects=True) -> requests.Response: 119 | res = requests.post( 120 | url, 121 | stream=stream, 122 | params=params, 123 | data=data, 124 | headers=self.headers if headers is None else headers, 125 | cookies=self.cookies, 126 | allow_redirects=allow_redirects 127 | ) 128 | self._refresh_cookies(res.cookies) 129 | return res 130 | 131 | def _refresh_cookies(self, cookies: requests.sessions.RequestsCookieJar): 132 | dic = cookies.get_dict() 133 | for i in dic: 134 | self.cookies.set(i, dic[i]) 135 | 136 | def _sign_in_with_email(self): 137 | """ 138 | Login through your email and password. 139 | PS: I found that it doesn't have any type of encryption till now, 140 | which could expose your password to the internet. 141 | """ 142 | url = "https://huggingface.co/login" 143 | data = { 144 | "username": self.email, 145 | "password": self.passwd, 146 | } 147 | res = self._request_post(url=url, data=data, allow_redirects=False) 148 | if res.status_code == 400: 149 | raise Exception("wrong username or password") 150 | 151 | def _get_auth_url(self): 152 | url = "https://huggingface.co/chat/login" 153 | headers = { 154 | "Referer": "https://huggingface.co/chat/login", 155 | "User-Agent": self.headers["User-Agent"], 156 | "Content-Type": "application/x-www-form-urlencoded", 157 | "Origin": "https://huggingface.co/chat" 158 | } 159 | res = self._request_post(url, headers=headers, allow_redirects=False) 160 | if res.status_code == 200: 161 | # location = res.headers.get("Location", None) 162 | location = res.json()["location"] 163 | if location: 164 | return location 165 | else: 166 | raise Exception( 167 | "No authorize url found, please check your email or password.") 168 | elif res.status_code == 303: 169 | location = res.headers.get("Location") 170 | if location: 171 | return location 172 | else: 173 | raise Exception( 174 | "No authorize url found, please check your email or password.") 175 | else: 176 | raise Exception("Something went wrong!") 177 | 178 | def _grant_auth(self, url: str) -> int: 179 | res = self._request_get(url, allow_redirects=False) 180 | if res.headers.__contains__("location"): 181 | location = res.headers["location"] 182 | res = self._request_get(location, allow_redirects=False) 183 | if res.cookies.__contains__("hf-chat"): 184 | return 1 185 | # raise Exception("grantAuth fatal") 186 | if res.status_code != 200: 187 | raise Exception("grant auth fatal!") 188 | csrf = re.findall( 189 | '/oauth/authorize.*?name="csrf" value="(.*?)"', res.text) 190 | if len(csrf) == 0: 191 | raise Exception("No csrf found!") 192 | data = { 193 | "csrf": csrf[0] 194 | } 195 | 196 | res = self._request_post(url, data=data, allow_redirects=False) 197 | if res.status_code != 303: 198 | raise Exception(f"get hf-chat cookies fatal! - {res.status_code}") 199 | else: 200 | location = res.headers.get("Location") 201 | res = self._request_get(location, allow_redirects=False) 202 | if res.status_code != 302: 203 | raise Exception(f"get hf-chat cookie fatal! - {res.status_code}") 204 | else: 205 | return 1 206 | 207 | def _get_cookie_path(self, cookie_dir_path) -> str: 208 | if not cookie_dir_path.endswith("/"): 209 | cookie_dir_path += "/" 210 | if not os.path.exists(cookie_dir_path): 211 | return "" 212 | files = os.listdir(cookie_dir_path) 213 | for i in files: 214 | if i == f"{self.email}.json": 215 | return cookie_dir_path + i 216 | return "" 217 | -------------------------------------------------------------------------------- /src/hugchat/message.py: -------------------------------------------------------------------------------- 1 | from typing import Generator, Union, List 2 | 3 | from .types.tool import Tool 4 | from .types.file import File 5 | from .types.message import Conversation 6 | from .exceptions import ChatError, ModelOverloadedError 7 | import json 8 | 9 | 10 | class ResponseTypes: 11 | FINAL = "finalAnswer" 12 | STREAM = "stream" 13 | TOOL = "tool" 14 | FILE = "file" 15 | WEB = "webSearch" 16 | STATUS = "status" 17 | 18 | 19 | class MessageStatus: 20 | PENDING = 0 21 | RESOLVED = 1 22 | REJECTED = 2 23 | 24 | 25 | MSGTYPE_ERROR = "error" 26 | 27 | 28 | class WebSearchSource: 29 | title: str 30 | link: str 31 | 32 | def __str__(self): 33 | return json.dumps({ 34 | "title": self.title, 35 | "link": self.link, 36 | }) 37 | 38 | 39 | class Message(Generator): 40 | """ 41 | :Args: 42 | * g: Generator 43 | * _stream_yield_all: bool = False 44 | * web_search: bool = False 45 | - web_search_sources: list[WebSearchSource] = list() 46 | - text: str = "" 47 | - web_search_done: bool = not web_search 48 | - msg_status: int = MessageStatus.PENDING 49 | - error: Union[Exception, None] = None 50 | 51 | A wrapper of `Generator` that receives and process the response 52 | 53 | :Example: 54 | .. code-block:: python 55 | 56 | msg = bot.chat(...) 57 | 58 | # stream process 59 | for res in msg: 60 | ... # process 61 | else: 62 | if msg.done() == MessageStatus.REJECTED: 63 | raise msg.error 64 | 65 | # or simply use: 66 | final = msg.wait_until_done() 67 | """ 68 | 69 | _stream_yield_all: bool = False 70 | _result_text: str = "" 71 | 72 | gen: Generator 73 | 74 | web_search: bool = False 75 | web_search_sources: List[WebSearchSource] = [] 76 | web_search_done: bool = not web_search 77 | 78 | tools_used: List[Tool] = [] 79 | files_created: List[File] = [] 80 | 81 | msg_status: int = MessageStatus.PENDING 82 | error: Union[Exception, None] = None 83 | 84 | def __init__( 85 | self, 86 | g: Generator, 87 | _stream_yield_all: bool = False, 88 | web_search: bool = False, 89 | conversation: Conversation = None 90 | ) -> None: 91 | self.gen = g 92 | self._stream_yield_all = _stream_yield_all 93 | self.web_search = web_search 94 | self.conversation = conversation 95 | 96 | @property 97 | def text(self) -> str: 98 | self._result_text = self.wait_until_done() 99 | return self._result_text 100 | 101 | @text.setter 102 | def text(self, v: str) -> None: 103 | self._result_text = v 104 | 105 | def _filterResponse(self, obj: dict): 106 | if not obj.__contains__("type"): 107 | if obj.__contains__("message"): 108 | raise ChatError(f"Server returns an error: {obj['message']}") 109 | else: 110 | raise ChatError(f"No `type` and `message` returned: {obj}") 111 | 112 | def __next__(self) -> dict: 113 | if self.msg_status == MessageStatus.RESOLVED: 114 | raise StopIteration 115 | 116 | elif self.msg_status == MessageStatus.REJECTED: 117 | if self.error is not None: 118 | raise self.error 119 | else: 120 | raise Exception("Message status is `Rejected` but no error found") 121 | 122 | try: 123 | data: dict = next(self.gen) 124 | self._filterResponse(data) 125 | data_type: str = data["type"] 126 | message_type: str = "" 127 | 128 | # set _result_text if this is the final iteration of the chat message 129 | if data_type == ResponseTypes.FINAL: 130 | # self._result_text = data["text"] 131 | self.msg_status = MessageStatus.RESOLVED 132 | 133 | # Handle web response type 134 | elif data_type == ResponseTypes.WEB: 135 | # gracefully pass unparseable webpages 136 | if message_type != MSGTYPE_ERROR and data.__contains__("sources"): 137 | self.web_search_sources.clear() 138 | sources = data["sources"] 139 | for source in sources: 140 | wss = WebSearchSource() 141 | wss.title = source["title"] 142 | wss.link = source["link"] 143 | self.web_search_sources.append(wss) 144 | 145 | # Handle what is done when a tool completes 146 | elif data_type == ResponseTypes.TOOL: 147 | if data["subtype"] == "result": 148 | tool = Tool(data["uuid"], data["result"]) 149 | self.tools_used.append(tool) 150 | 151 | # Handle what is done when a file is created 152 | elif data_type == ResponseTypes.FILE: 153 | file = File(data["sha"], data["name"], data["mime"], self.conversation) 154 | self.files_created.append(file) 155 | 156 | # replace null characters with an empty string 157 | elif data_type == ResponseTypes.STREAM: 158 | data["token"] = data["token"].replace('\u0000', '') 159 | self._result_text += data["token"] 160 | 161 | elif "messageType" in data: 162 | message_type: str = data["messageType"] 163 | if message_type == MSGTYPE_ERROR: 164 | self.error = ChatError(data["message"]) 165 | self.msg_status = MessageStatus.REJECTED 166 | 167 | if data_type == ResponseTypes.STREAM: 168 | self.web_search_done = True 169 | 170 | elif data_type == ResponseTypes.STATUS: 171 | pass 172 | 173 | else: 174 | if "Model is overloaded" in str(data): 175 | self.error = ModelOverloadedError( 176 | "Model is overloaded, please try again later or switch to another model." 177 | ) 178 | self.msg_status = MessageStatus.REJECTED 179 | elif data.__contains__(MSGTYPE_ERROR): 180 | self.error = ChatError(data[MSGTYPE_ERROR]) 181 | self.msg_status = MessageStatus.REJECTED 182 | else: 183 | self.error = ChatError(f"Unknown json response: {data}") 184 | 185 | # If _stream_yield_all is True, yield all responses from the server. 186 | if self._stream_yield_all or data_type == ResponseTypes.STREAM: 187 | return data 188 | else: 189 | return self.__next__() 190 | except StopIteration: 191 | if self.msg_status == MessageStatus.PENDING: 192 | self.error = ChatError( 193 | "Stream of responses has abruptly ended (final answer has not been received)." 194 | ) 195 | raise self.error 196 | pass 197 | except Exception as e: 198 | # print("meet error: ", str(e)) 199 | self.error = e 200 | self.msg_status = MessageStatus.REJECTED 201 | raise self.error 202 | 203 | def __iter__(self): 204 | return self 205 | 206 | def throw( 207 | self, 208 | __typ, 209 | __val=None, 210 | __tb=None, 211 | ): 212 | return self.gen.throw(__typ, __val, __tb) 213 | 214 | def send(self, __value): 215 | return self.gen.send(__value) 216 | 217 | def get_final_text(self) -> str: 218 | """ 219 | :Return: 220 | - self.text 221 | """ 222 | return self.text 223 | 224 | def get_search_sources(self) -> list: 225 | """ 226 | :Return: 227 | - self.web_search_sources 228 | """ 229 | return self.web_search_sources 230 | 231 | def get_tools_used(self) -> list: 232 | """ 233 | :Return: 234 | - self.tools_used 235 | """ 236 | return self.tools_used 237 | 238 | def get_files_created(self) -> list: 239 | """ 240 | :Return: 241 | - self.files_created 242 | """ 243 | return self.files_created 244 | 245 | def search_enabled(self) -> bool: 246 | """ 247 | :Return: 248 | - self.web_search 249 | """ 250 | return self.web_search 251 | 252 | def wait_until_done(self) -> str: 253 | """ 254 | :Return: 255 | - self.text if resolved else raise error 256 | 257 | wait until every response is resolved 258 | """ 259 | while not self.is_done(): 260 | self.__next__() 261 | 262 | if self.is_done() == MessageStatus.RESOLVED: 263 | return self._result_text 264 | 265 | elif self.error is not None: 266 | raise self.error 267 | 268 | else: 269 | raise Exception("Rejected but no error captured!") 270 | 271 | def is_done(self): 272 | """ 273 | :Return: 274 | - self.msg_status 275 | 276 | 3 status: 277 | - MessageStatus.PENDING = 0 # running 278 | - MessageStatus.RESOLVED = 1 # done with no error(maybe?) 279 | - MessageStatus.REJECTED = 2 # error raised 280 | """ 281 | return self.msg_status 282 | 283 | def is_done_search(self): 284 | """ 285 | :Return: 286 | - self.web_search_done 287 | 288 | web search result will be set to `done` once the token is received 289 | """ 290 | return self.web_search_done 291 | 292 | def __str__(self): 293 | return self.wait_until_done() 294 | 295 | def __getitem__(self, key: str) -> str: 296 | print("_getitem_") 297 | self.wait_until_done() 298 | 299 | if key == "text": 300 | return self.text 301 | 302 | elif key == "web_search": 303 | return self.web_search 304 | 305 | elif key == "web_search_sources": 306 | return self.web_search_sources 307 | 308 | def __add__(self, other: str) -> str: 309 | self.wait_until_done() 310 | return self.text + other 311 | 312 | def __radd__(self, other: str) -> str: 313 | self.wait_until_done() 314 | return other + self.text 315 | 316 | def __iadd__(self, other: str) -> str: 317 | self.wait_until_done() 318 | self.text += other 319 | return self.text 320 | -------------------------------------------------------------------------------- /src/hugchat/cli.py: -------------------------------------------------------------------------------- 1 | """Entry for the hugchat command line interface. 2 | 3 | simply type 4 | ```bash 5 | python -m hugchat.cli 6 | ``` 7 | to start cli. 8 | """ 9 | 10 | from .hugchat import ChatBot 11 | from .login import Login 12 | import getpass 13 | import argparse 14 | import os 15 | import traceback 16 | 17 | ENVIRONMENT_EMAIL = os.getenv("EMAIL") 18 | ENVIRONMENT_PASSWORD = os.getenv("PASSWD") 19 | stream_output = False 20 | is_web_search = False 21 | web_search_hint = False 22 | continued_conv = False 23 | 24 | EXIT_COMMANDS = [ 25 | "/exit", 26 | "/quit", 27 | "/stop", 28 | "/close" 29 | ] 30 | 31 | # COOKIE_PATH_DIR = os.path.abspath(os.path.dirname(__file__)) + "/usercookies" 32 | 33 | 34 | def handle_command(chatbot: ChatBot, userInput: str) -> None: 35 | global stream_output, is_web_search, web_search_hint , continued_conv 36 | 37 | arguments = userInput.lower().split(" ") 38 | command = arguments[0][1:] # Remove the '/' at the start of the input 39 | arguments = arguments[1:] 40 | 41 | if command == "help" or command == "commands": 42 | print(""" 43 | /new : Create and switch to a new conversation. 44 | /ids : Shows a list of all ID numbers and ID strings in *current session*. 45 | /switch : Shows a list of all conversations' info in *current session*. Then you can choose one to switch to. 46 | /switch all : Shows a list of all conversations' info in *your account*. Then you can choose one to switch to. (not recommended if your account has a lot of conversations) 47 | /del : Deletes the conversation linked with the index passed. Will not delete active session. 48 | /delete-all : Deletes all the conversations for the logged in user. 49 | /clear : Clear the terminal. 50 | /llm : Get available models you can switch to. 51 | /llm : Switches model to given model index based on /llm. 52 | /share : Toggles settings for sharing data with model author. On by default. 53 | /exit : Closes CLI environment. 54 | /stream : Toggles streaming the response. 55 | /web : Toggles web search. 56 | /web-hint : Toggles display web search hint. 57 | """) 58 | 59 | elif command == "new": 60 | new_conversation = chatbot.new_conversation(switch_to=True) 61 | conversation_index = len(chatbot.get_conversation_list()) 62 | print(f"# Created and switched to a new conversation\n# New conversation ID: {new_conversation.id}\n# New conversation index: {conversation_index}") 63 | 64 | elif command == "ids": 65 | print(f"# Conversations: ") 66 | for i, conversation in enumerate(chatbot.get_conversation_list()): 67 | print(f"# {i+1}.) {conversation.id}{' (acitve)' if chatbot.get_conversation_info().id == conversation.id else ''}") 68 | 69 | elif command == "switch": 70 | try: 71 | if arguments and arguments[0] == "all": 72 | id = chatbot.get_remote_conversations(replace_conversation_list=True) 73 | elif not arguments: 74 | id = chatbot.get_conversation_list() 75 | else: 76 | print("# Invalid argument(s).") 77 | return 78 | conversation_dict = {i+1: id_string for i, id_string in enumerate(id)} 79 | 80 | for i, id_string in conversation_dict.items(): 81 | info = chatbot.get_conversation_info(id_string) 82 | print(f"# {i}: ID: {info.id}\n# Title: {info.title[:43]}...\n# Model: {info.model}.\n# System Prompt: {info.system_prompt}\n# --------------------------------------------------------") 83 | 84 | index_value = int(input("# Choose conversation ID(input the index): ")) 85 | target_id = conversation_dict.get(index_value) 86 | 87 | if target_id: 88 | chatbot.change_conversation(target_id) 89 | print(f"# Switched to conversation with ID: {target_id}\n") 90 | else: 91 | print("# Invalid conversation ID") 92 | except Exception as e: 93 | if isinstance(e, ValueError): 94 | print(f"# Invlid argument.") 95 | else: 96 | print(f"# Error: {e}") 97 | 98 | elif command == "del" or command == "delete": 99 | try: 100 | if not arguments: 101 | print("# No argument for index provided.") 102 | return 103 | 104 | conversation_index = int(arguments[0]) 105 | if conversation_index < 1: 106 | raise IndexError() 107 | selected_conversation = chatbot.get_conversation_list()[conversation_index-1].id 108 | current_conversation_id = chatbot.get_conversation_info().id 109 | 110 | if selected_conversation == current_conversation_id: 111 | print("# Cannot delete active chat.") 112 | return 113 | 114 | to_delete_conversation = chatbot.get_conversation_from_id(selected_conversation) 115 | except Exception as e: 116 | if isinstance(e, ValueError): 117 | print("# Invalid argument for index.") 118 | else: 119 | print("# Invalid index.") 120 | return 121 | 122 | if not to_delete_conversation is None: 123 | chatbot.delete_conversation(to_delete_conversation) 124 | print("# Deleted conversation successfully.") 125 | return 126 | print("# Error") 127 | 128 | elif command == "delete-all" or command == "deleteall": 129 | if input("# WARNING: This will delete all conversations linked with this account. Continue? (y/n) : ").lower() == 'y': 130 | chatbot.delete_all_conversations() 131 | print("# Deleted all conversations successfully") 132 | 133 | new_conversation = chatbot.new_conversation(switch_to=True) 134 | print(f"# Created and switched to a new conversation\n# New conversation ID: {new_conversation.id}") 135 | 136 | elif command == "clear" or command == "cls": 137 | os.system('cls' if os.name == 'nt' else 'clear') 138 | 139 | elif command == "llm": 140 | if len(arguments) == 0: 141 | print(f"# Available Models: ") 142 | for i, model in enumerate(chatbot.get_available_llm_models()): 143 | print(f"# {i+1}.) {model.id}") 144 | return 145 | 146 | try: 147 | chatbot.switch_llm(int(arguments[0])-1) 148 | except Exception as e: 149 | if isinstance(e, ValueError): 150 | print("# Not a valid argument") 151 | elif isinstance(e, IndexError): 152 | print("# Invalid LLM index") 153 | else: 154 | print(e) 155 | return 156 | 157 | print(f"# Switched to LLM {chatbot.active_model.id}\n# Please note that you have to create a new conversation for this to take effect") 158 | 159 | elif command == "share": 160 | if arguments: 161 | chatbot.sharing = arguments[0] == "on" 162 | else: 163 | chatbot.sharing = not chatbot.sharing 164 | try: 165 | chatbot.set_share_conversations(chatbot.sharing) 166 | print(f"# {'Now sharing conversations with model author' if chatbot.sharing else 'No longer sharing conversations with model author'}") 167 | except Exception as e: 168 | print(f"# Error: {e}\n") 169 | 170 | elif command == "stream" or command == "streamoutput": 171 | if arguments: 172 | stream_output = arguments[0] == "on" 173 | else: 174 | stream_output = not stream_output 175 | print(f"# {'Now streaming responses' if stream_output else 'No longer streaming responses'}") 176 | 177 | elif command == "web" or command == "websearch": 178 | if arguments: 179 | is_web_search = arguments[0] == "on" 180 | else: 181 | is_web_search = not is_web_search 182 | print(f"# {'Web searching activated' if is_web_search else 'We searching deactivated'}") 183 | 184 | elif command == "web-hint" or command == "webhint": 185 | if arguments: 186 | web_search_hint = arguments[0] == "on" 187 | else: 188 | web_search_hint = not web_search_hint 189 | print(f"# {'Enabled web hint' if web_search_hint else 'Disabled web hint'}") 190 | 191 | else: 192 | print("# Unrecognized command") 193 | 194 | 195 | def stream_response(generator) -> None: 196 | print("<", end="", flush=True) 197 | 198 | for chunk in generator: 199 | if chunk is None: 200 | continue 201 | print(chunk["token"], end="", flush=True) 202 | 203 | print() 204 | 205 | 206 | def web_search(generator) -> None: 207 | print("<", end="", flush=True) 208 | 209 | sources = [] 210 | for chunk in generator: 211 | if web_search_hint and chunk['type'] == 'webSearch' and chunk['messageType'] == 'update': 212 | args = chunk['args'][0] if 'args' in chunk else "" 213 | print(f"🌍 Web Searching | {chunk['message']} {args}") 214 | 215 | elif web_search_hint and chunk['type'] == 'webSearch' and chunk['messageType'] == 'sources' and "sources" in chunk: 216 | sources = chunk['sources'] 217 | 218 | elif chunk['type'] == 'stream': 219 | print(chunk['token'], end="", flush=True) 220 | 221 | if web_search_hint and len(sources) > 0: 222 | print("\n# Sources:") 223 | for i in range(len(sources)): 224 | print(f" {i+1}. {sources[i]['title']} - {sources[i]['link']}") 225 | 226 | print() 227 | 228 | 229 | def get_arguments() -> tuple: 230 | parser = argparse.ArgumentParser() 231 | parser.add_argument( 232 | "-u", 233 | type=str, 234 | help="Your huggingface account's email" 235 | ) 236 | parser.add_argument( 237 | "-p", 238 | action="store_true", 239 | help="Require Password to login" 240 | ) 241 | parser.add_argument( 242 | "-s", 243 | action="store_true", 244 | help="Option to enable streaming mode output" 245 | ) 246 | parser.add_argument( 247 | "-c", 248 | action="store_true", 249 | help="Continue the previous conversation" 250 | ) 251 | args = parser.parse_args() 252 | return args.u, args.p, args.s, args.c 253 | 254 | # ... 255 | 256 | 257 | def cli(): 258 | global stream_output, is_web_search, web_search_hint , continued_conv 259 | 260 | print(""" 261 | -------HuggingChat------- 262 | Official Site: https://huggingface.co/chat 263 | 1. AI is an area of active research with known problems such as biased generation and misinformation. 264 | 2. Do not use this application for high-stakes decisions or advice. 265 | Continuing to use means that you accept the above point(s) 266 | """) 267 | 268 | EMAIL, FORCE_INPUT_PASSWORD, stream_output, continued_conv = get_arguments() 269 | 270 | # Check if the email is in the environment variables or given as an argument 271 | if EMAIL is None: 272 | EMAIL = os.getenv("EMAIL") 273 | 274 | if EMAIL is None: 275 | raise Exception("No email specified. Please use '-u' or set the EMAIL environment variable.") 276 | 277 | # Attempt to load cookies from directory 278 | try: 279 | cookies = Login(EMAIL).loadCookiesFromDir() 280 | except Exception: 281 | cookies = None 282 | 283 | # If we could not find cookies or the "inputpass" argument is true 284 | # then ask for the password 285 | if cookies is None or FORCE_INPUT_PASSWORD: 286 | if ENVIRONMENT_PASSWORD is not None and not FORCE_INPUT_PASSWORD: 287 | PASSWORD = ENVIRONMENT_PASSWORD 288 | else: 289 | PASSWORD = getpass.getpass("Password: ") 290 | 291 | print("Logging in...") 292 | sign = Login(EMAIL, PASSWORD) 293 | cookies = sign.login() 294 | sign.saveCookiesToDir() 295 | 296 | print(f"Signed in as {EMAIL} .. attempting to login") 297 | 298 | chatbot = ChatBot(cookies=cookies) 299 | 300 | print("Login successfully! 🎉\nYou can input `/help` to open the command menu.\n") 301 | 302 | if continued_conv: 303 | ids = chatbot.get_remote_conversations(replace_conversation_list=True) 304 | 305 | conversation_dict = dict(enumerate(ids, start=1)) 306 | 307 | # delete the conversation that was initially created on chatbot init 308 | target_id = conversation_dict[1] 309 | chatbot.delete_conversation(target_id) 310 | 311 | # switch to the most recent remote conversation 312 | target_id = conversation_dict[2] 313 | chatbot.change_conversation(target_id) 314 | 315 | print(f"Switched to Previous conversation with ID: {target_id}\n") 316 | 317 | while True: 318 | userInput = input("> ").strip() 319 | 320 | if len(userInput) == 0: 321 | continue 322 | if userInput.lower() in EXIT_COMMANDS: 323 | break 324 | 325 | # If the input starts with a slash then we know it is a command 326 | if userInput.startswith("/"): 327 | try: 328 | handle_command(chatbot, userInput) 329 | except Exception as e: 330 | print("An error occurred while processing your command: " + str(e)) 331 | traceback.print_exc() 332 | 333 | continue 334 | 335 | # either start a web search or a normal response 336 | if is_web_search: 337 | res = chatbot.chat(userInput, stream=True, _stream_yield_all=True, web_search=is_web_search) 338 | web_search(res) 339 | 340 | else: 341 | if stream_output: 342 | res = chatbot.chat(userInput) 343 | stream_response(res) 344 | else: 345 | print("< " + chatbot.chat(userInput).wait_until_done().strip()) 346 | 347 | if __name__ == '__main__': 348 | cli() 349 | -------------------------------------------------------------------------------- /src/hugchat/hugchat.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import os 4 | import datetime 5 | import logging 6 | import time 7 | import typing 8 | import traceback 9 | 10 | from typing import Union, List 11 | from requests import Session 12 | from requests.sessions import RequestsCookieJar 13 | 14 | from .message import Message 15 | from . import exceptions 16 | from .types.assistant import Assistant 17 | from .types.model import Model 18 | from .types.message import MessageNode, Conversation 19 | 20 | 21 | conversation = Conversation 22 | model = Model 23 | 24 | 25 | class ChatBot: 26 | cookies: dict 27 | """Cookies for authentication""" 28 | 29 | session: Session 30 | """HuggingChat session""" 31 | 32 | def __init__( 33 | self, 34 | cookies: Union[dict, None, RequestsCookieJar] = None, 35 | cookie_path: str = "", 36 | default_llm: Union[int, str] = 0, 37 | system_prompt: str = "", 38 | ) -> None: 39 | """ 40 | Returns a ChatBot object 41 | default_llm: name or index 42 | """ 43 | if cookies is None and cookie_path == "": 44 | raise exceptions.ChatBotInitError( 45 | "Authentication is required now, but no cookies provided. See tutorial at https://github.com/Soulter/hugging-chat-api" 46 | ) 47 | elif cookies is not None and cookie_path != "": 48 | raise exceptions.ChatBotInitError( 49 | "Both cookies and cookie_path provided") 50 | 51 | if cookies is None and cookie_path != "": 52 | # read cookies from path 53 | if not os.path.exists(cookie_path): 54 | raise exceptions.ChatBotInitError( 55 | f"Cookie file {cookie_path} not found. Note: The file must be in JSON format and must contain a list of cookies. See more at https://github.com/Soulter/hugging-chat-api" 56 | ) 57 | with open(cookie_path, "r", encoding="utf-8") as f: 58 | cookies = json.load(f) 59 | 60 | # convert cookies to KV format 61 | if isinstance(cookies, list): 62 | cookies = {cookie["name"]: cookie["value"] for cookie in cookies} 63 | 64 | self.cookies = cookies 65 | 66 | self.hf_base_url = "https://huggingface.co" 67 | self.json_header = {"Content-Type": "application/json"} 68 | self.session = self.get_hc_session() 69 | self.conversation_list = [] 70 | self.sharing = True 71 | self.accepted_welcome_modal = ( 72 | False # It is no longer required to accept the welcome modal 73 | ) 74 | 75 | self.llms = self.get_remote_llms() 76 | 77 | if isinstance(default_llm, str): 78 | self.active_model = self.get_llm_from_name(default_llm) 79 | if self.active_model is None: 80 | raise Exception( 81 | f"Given model is not in llms list. LLM list: {[model.id for model in self.llms]}" 82 | ) 83 | else: 84 | self.active_model = self.llms[default_llm] 85 | 86 | self.current_conversation = self.new_conversation( 87 | system_prompt=system_prompt) 88 | 89 | def get_hc_session(self) -> Session: 90 | session = Session() 91 | # set cookies 92 | session.cookies.update(self.cookies) 93 | session.get(self.hf_base_url + "/chat") 94 | return session 95 | 96 | def get_headers(self, ref=True, ref_cid: Conversation = None) -> dict: 97 | _h = { 98 | "Accept": "*/*", 99 | "Connection": "keep-alive", 100 | "Host": "huggingface.co", 101 | "Origin": "https://huggingface.co", 102 | "Sec-Fetch-Site": "same-origin", 103 | "Content-Type": "application/json", 104 | "Sec-Ch-Ua-Platform": "Windows", 105 | "Sec-Ch-Ua": 'Chromium";v="116", "Not)A;Brand";v="24", "Microsoft Edge";v="116', 106 | "Sec-Ch-Ua-Mobile": "?0", 107 | "Sec-Fetch-Mode": "cors", 108 | "Sec-Fetch-Dest": "empty", 109 | "Accept-Encoding": "gzip, deflate, br", 110 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36", 111 | } 112 | 113 | if ref: 114 | if ref_cid is None: 115 | ref_cid = self.current_conversation 116 | _h["Referer"] = f"https://huggingface.co/chat/conversation/{ref_cid}" 117 | return _h 118 | 119 | def get_cookies(self) -> dict: 120 | return self.session.cookies.get_dict() 121 | 122 | # NOTE: To create a copy when calling this, call it inside of list(). 123 | # If not, when updating or altering the values in the variable will 124 | # also be applied to this class's variable. 125 | # This behavior is with any function returning self.. It 126 | # acts as a pointer to the data in the object. 127 | # 128 | # Returns a pointer to this objects list that contains id of conversations. 129 | def get_conversation_list(self) -> list: 130 | return list(self.conversation_list) 131 | 132 | def get_active_llm_index(self) -> int: 133 | return self.llms.index(self.active_model) 134 | 135 | def accept_ethics_modal(self): 136 | """ 137 | [Deprecated Method] 138 | """ 139 | response = self.session.post( 140 | self.hf_base_url + "/chat/settings", 141 | headers=self.get_headers(ref=False), 142 | cookies=self.get_cookies(), 143 | allow_redirects=True, 144 | data={ 145 | "ethicsModalAccepted": "true", 146 | "shareConversationsWithModelAuthors": "true", 147 | "ethicsModalAcceptedAt": "", 148 | "activeModel": str(self.active_model), 149 | }, 150 | ) 151 | 152 | if response.status_code != 200: 153 | raise Exception( 154 | f"Failed to accept ethics modal with status code: {response.status_code}. {response.content.decode()}" 155 | ) 156 | 157 | return True 158 | 159 | def new_conversation( 160 | self, 161 | modelIndex: int = None, 162 | system_prompt: str = "", 163 | switch_to: bool = False, 164 | assistant: Union[str, Assistant] = None, 165 | ) -> Conversation: 166 | """ 167 | Create a new conversation. Return a conversation object. 168 | 169 | modelIndex: int, get it from get_available_llm_models(). If None, use the default model. 170 | assistant: str or Assistant, the assistant **id**. Assistant id can be found in the assistant url, such as https://huggingface.co/chat/assistant/65bf2ddbf4017c8048ae43a3, the id is `65bf2ddbf4017c8048ae43a3`. 171 | 172 | - You should change the conversation by calling change_conversation() after calling this method. Or set param switch_to to True. 173 | - if you use assistant, the parameter `system_prompt` will be ignored. 174 | 175 | """ 176 | err_count = 0 177 | 178 | if modelIndex is None: 179 | model = self.active_model 180 | else: 181 | if modelIndex < 0 or modelIndex >= len(self.llms): 182 | raise IndexError("Out of range of llm index") 183 | 184 | model = self.llms[modelIndex] 185 | 186 | # Accept the welcome modal when init. 187 | # 17/5/2023: This is not required anymore. 188 | # if not self.accepted_welcome_modal: 189 | # self.accept_ethics_modal() 190 | 191 | # Create new conversation and get a conversation id. 192 | 193 | _header = self.get_headers(ref=False) 194 | _header["Referer"] = "https://huggingface.co/chat" 195 | 196 | request = { 197 | "model": model.id, 198 | } 199 | 200 | # get assistant id 201 | if assistant is not None: 202 | assistant_id = None 203 | if isinstance(assistant, str): 204 | assistant_id = assistant 205 | elif isinstance(assistant, Assistant): 206 | assistant_id = assistant.assistant_id 207 | else: 208 | raise ValueError( 209 | "param assistant must be a string or Assistant object.") 210 | request["assistantId"] = assistant_id 211 | else: 212 | request["preprompt"] = system_prompt if system_prompt != "" else model.preprompt 213 | 214 | while True: 215 | try: 216 | resp = self.session.post( 217 | self.hf_base_url + "/chat/conversation", 218 | json=request, 219 | headers=_header, 220 | cookies=self.get_cookies(), 221 | ) 222 | 223 | logging.debug(resp.text) 224 | cid = json.loads(resp.text)["conversationId"] 225 | 226 | c = Conversation( 227 | id=cid, system_prompt=system_prompt, model=model) 228 | 229 | self.conversation_list.append(c) 230 | if switch_to: 231 | self.change_conversation(c) 232 | 233 | # we need know the root message id (a.k.a system prompt message id). 234 | self.get_conversation_info(c) 235 | 236 | return c 237 | 238 | except BaseException as e: 239 | err_count += 1 240 | logging.debug( 241 | f" Failed to create new conversation ({e}). Retrying... ({err_count})" 242 | ) 243 | if err_count > 5: 244 | raise exceptions.CreateConversationError( 245 | f"Failed to create new conversation with status code: {resp.status_code}. Error: {e}. Retries: {err_count}." 246 | ) 247 | continue 248 | 249 | def change_conversation(self, conversation_object: Conversation): 250 | """ 251 | Change the current conversation to another one. 252 | """ 253 | 254 | local_conversation = self.get_conversation_from_id( 255 | conversation_object.id) 256 | 257 | if local_conversation is None: 258 | raise exceptions.InvalidConversationIDError( 259 | "Invalid conversation id, not in conversation list." 260 | ) 261 | 262 | self.get_conversation_info(local_conversation) 263 | 264 | self.current_conversation = local_conversation 265 | 266 | return self.current_conversation 267 | 268 | def share_conversation(self, conversation_object: Conversation = None) -> str: 269 | """ 270 | Return a share link of the conversation. 271 | """ 272 | if conversation_object is None: 273 | conversation_object = self.current_conversation 274 | 275 | headers = self.get_headers() 276 | 277 | r = self.session.post( 278 | f"{self.hf_base_url}/chat/conversation/{conversation_object}/share", 279 | headers=headers, 280 | cookies=self.get_cookies(), 281 | ) 282 | 283 | if r.status_code != 200: 284 | raise Exception( 285 | f"Failed to share conversation with status code: {r.status_code}" 286 | ) 287 | 288 | response = r.json() 289 | if "url" in response: 290 | return response["url"] 291 | 292 | raise Exception(f"Unknown server response: {response}") 293 | 294 | def delete_all_conversations(self) -> None: 295 | """ 296 | Deletes ALL conversations on the HuggingFace account 297 | """ 298 | 299 | settings = {"": ("", "")} 300 | 301 | r = self.session.delete( 302 | f"{self.hf_base_url}/chat/api/conversations/", 303 | headers={"Referer": "https://huggingface.co/chat", "Origin": "https://huggingface.co", "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarywrIEW0Ame78HYisT"}, 304 | cookies=self.get_cookies(), 305 | allow_redirects=True, 306 | files=settings, 307 | ) 308 | 309 | if r.status_code != 200: 310 | raise exceptions.DeleteConversationError( 311 | f"Failed to delete ALL conversations with status code: {r.status_code}" 312 | ) 313 | 314 | self.conversation_list = [] 315 | self.current_conversation = None 316 | 317 | def delete_conversation(self, conversation_object: Conversation = None) -> None: 318 | """ 319 | Delete a HuggingChat conversation by conversation. 320 | """ 321 | 322 | if conversation_object is None: 323 | conversation_object = self.current_conversation 324 | 325 | headers = self.get_headers() 326 | 327 | r = self.session.delete( 328 | f"{self.hf_base_url}/chat/conversation/{conversation_object}", 329 | headers=headers, 330 | cookies=self.get_cookies(), 331 | ) 332 | 333 | if r.status_code != 200: 334 | raise exceptions.DeleteConversationError( 335 | f"Failed to delete conversation with status code: {r.status_code}" 336 | ) 337 | else: 338 | self.conversation_list.pop( 339 | self.get_conversation_from_id( 340 | conversation_object.id, return_index=True) 341 | ) 342 | 343 | if conversation_object is self.current_conversation: 344 | self.current_conversation = None 345 | 346 | def get_available_llm_models(self) -> list: 347 | """ 348 | Get all available models that are available in huggingface.co/chat. 349 | """ 350 | return self.llms 351 | 352 | def set_share_conversations(self, val: bool = True): 353 | """ 354 | Sets the "Share Conversation with Model Authors setting" to the given val variable 355 | """ 356 | settings = {"shareConversationsWithModelAuthors": ( 357 | "", "on" if val else "")} 358 | 359 | r = self.session.post( 360 | self.hf_base_url + "/chat/settings", 361 | headers={"Referer": "https://huggingface.co/chat", "Origin":"https://huggingface.co"}, 362 | cookies=self.get_cookies(), 363 | allow_redirects=True, 364 | files=settings, 365 | ) 366 | 367 | if r.status_code != 200: 368 | raise Exception( 369 | f"Failed to set share conversation with status code: {r.status_code}" 370 | ) 371 | 372 | def switch_llm(self, index: int) -> bool: 373 | """ 374 | Attempts to change current conversation's Large Language Model. 375 | Requires an index to indicate the model you want to switch. 376 | See self.llms for available models. 377 | 378 | Note: 1. The effect of switch is limited to the current conversation, 379 | You can manually switch the llm when you start a new conversation. 380 | 381 | 2. Only works *after creating a new conversation.* 382 | :) 383 | """ 384 | # TODO: I will work on making it have a model for each conversation that is changeable. - @Zekaroni 385 | 386 | if index < len(self.llms) and index >= 0: 387 | self.active_model = self.llms[index] 388 | return True 389 | else: 390 | raise IndexError("Out of range of llm index") 391 | 392 | def get_llm_from_name(self, name: str) -> Union[Model, None]: 393 | for model in self.llms: 394 | if model.name == name: 395 | return model 396 | 397 | # Gives information such as name, websiteUrl, description, displayName, parameters, etc. 398 | # We can use it in the future if we need to get information about models 399 | def get_remote_llms(self) -> list: 400 | """ 401 | Fetches all possible LLMs that could be used. Returns the LLMs in a list 402 | """ 403 | 404 | r = self.session.get( 405 | self.hf_base_url + "/chat/api/v2/models", 406 | headers=self.get_headers(ref=False), 407 | cookies=self.get_cookies(), 408 | ) 409 | 410 | if r.status_code != 200: 411 | raise Exception( 412 | f"Failed to get remote LLMs with status code: {r.status_code}" 413 | ) 414 | 415 | 416 | try: 417 | models_data_list = json.loads(r.text)['json'] 418 | except json.JSONDecodeError as e: 419 | logging.error(f"Error decoding JSON: {e}") 420 | models_data_list = [] 421 | 422 | model_list = [] 423 | 424 | for model_data_dict in models_data_list: 425 | if model_data_dict.get("unlisted", False): # Default to False if 'unlisted' key is missing 426 | print(f"Skipping unlisted model: {model_data_dict.get('id', 'Unknown ID')}") 427 | continue 428 | m = Model( 429 | id=model_data_dict.get("id"), 430 | name=model_data_dict.get("name"), 431 | displayName=model_data_dict.get("displayName"), 432 | preprompt=model_data_dict.get("preprompt", ""), 433 | websiteUrl=model_data_dict.get("websiteUrl"), 434 | description=model_data_dict.get("description"), 435 | modelUrl=model_data_dict.get("modelUrl"), 436 | unlisted=model_data_dict.get("unlisted", False), # Also store this if needed 437 | logoUrl=model_data_dict.get("logoUrl"), 438 | reasoning=model_data_dict.get("reasoning"), 439 | multimodal=model_data_dict.get("multimodal"), 440 | tools=model_data_dict.get("tools"), 441 | hasInferenceAPI=model_data_dict.get("hasInferenceAPI") 442 | ) 443 | 444 | prompt_examples_list = model_data_dict.get("promptExamples") 445 | if prompt_examples_list: 446 | m.promptExamples = prompt_examples_list 447 | else: 448 | m.promptExamples = [] 449 | 450 | parameters_dict = model_data_dict.get("parameters") 451 | if parameters_dict: 452 | m.parameters = parameters_dict 453 | else: 454 | m.parameters = {} 455 | 456 | 457 | model_list.append(m) 458 | return model_list 459 | 460 | def get_remote_conversations(self, replace_conversation_list=True): 461 | """ 462 | Returns all the remote conversations for the active account. Returns the conversations in a list. 463 | """ 464 | 465 | r = self.session.post( 466 | self.hf_base_url + "/chat/__data.json", 467 | headers=self.get_headers(ref=False), 468 | cookies=self.get_cookies(), 469 | ) 470 | 471 | if r.status_code != 200: 472 | raise Exception( 473 | f"Failed to get remote conversations with status code: {r.status_code}" 474 | ) 475 | 476 | # temporary workaround for #267 477 | line_ = r.text.splitlines()[0] 478 | data = json.loads(line_)["nodes"][0]["data"] 479 | 480 | conversationIndices = data[data[0]["conversations"]] 481 | 482 | conversations = [] 483 | 484 | for index in conversationIndices: 485 | conversation_data = data[index] 486 | 487 | c = Conversation( 488 | id=data[conversation_data["id"]], 489 | title=data[conversation_data["title"]], 490 | model=data[conversation_data["model"]], 491 | ) 492 | 493 | conversations.append(c) 494 | 495 | if replace_conversation_list: 496 | self.conversation_list = conversations 497 | 498 | return conversations 499 | 500 | def parse_datetime_to_timestamp(self, datetime_str): 501 | if not datetime_str: 502 | return None 503 | try: 504 | # Python 3.7+ can often handle 'Z' directly, but for older or more robust parsing: 505 | if datetime_str.endswith('Z'): 506 | datetime_str = datetime_str[:-1] + '+00:00' # Replace Z with UTC offset 507 | dt_obj = datetime.datetime.fromisoformat(datetime_str) 508 | # If it's timezone-naive, assume UTC. If timezone-aware, convert to UTC then get timestamp. 509 | if dt_obj.tzinfo is None or dt_obj.tzinfo.utcoffset(dt_obj) is None: 510 | dt_obj = dt_obj.replace(tzinfo=datetime.timezone.utc) # Assume UTC if naive 511 | else: 512 | dt_obj = dt_obj.astimezone(datetime.timezone.utc) 513 | return dt_obj.timestamp() 514 | except ValueError as e: 515 | print(f"Error parsing datetime string '{datetime_str}': {e}") 516 | return None 517 | 518 | def get_conversation_info(self, conversation: Union[Conversation, str] = None) -> Conversation: 519 | """ 520 | Fetches information related to the specified conversation. Returns the conversation object. 521 | conversation: Conversation object that has the conversation id Or None to use the current conversation. 522 | """ 523 | 524 | if conversation is None: 525 | conversation = self.current_conversation 526 | 527 | if isinstance(conversation, str): 528 | conversation = Conversation(id=conversation) 529 | 530 | r = self.session.get( 531 | self.hf_base_url + 532 | f"/chat/api/v2/conversations/{conversation.id}", 533 | headers=self.get_headers(ref=False), 534 | cookies=self.get_cookies(), 535 | ) 536 | 537 | if r.status_code != 200: 538 | raise Exception( 539 | f"Failed to get conversation info with status code: {r.status_code}" 540 | ) 541 | 542 | # you'll never understand the following codes until you try to debug huggingchat in person. 543 | try: 544 | data = r.json()['json'] 545 | except json.JSONDecodeError as e: 546 | logging.error(f"Failed to decode JSON: {e}") 547 | return None 548 | 549 | conversation.model = data.get("model") 550 | conversation.system_prompt = data.get("preprompt") 551 | conversation.title = data.get("title") 552 | 553 | messages_data_list = data.get("messages", []) 554 | conversation.history = [] 555 | 556 | for msg_data_dict in messages_data_list: 557 | created_at_ts = self.parse_datetime_to_timestamp(msg_data_dict.get("createdAt")) 558 | updated_at_ts = self.parse_datetime_to_timestamp(msg_data_dict.get("updatedAt")) 559 | ancestor_ids = msg_data_dict.get("ancestors", []) 560 | children_ids = msg_data_dict.get("children", []) 561 | 562 | conversation.history.append(MessageNode( 563 | id=msg_data_dict.get("id"), 564 | role=msg_data_dict.get("from"), 565 | content=msg_data_dict.get("content"), 566 | ancestors=ancestor_ids, # Storing IDs 567 | children=children_ids, # Storing IDs 568 | created_at=created_at_ts, 569 | updated_at=updated_at_ts 570 | )) 571 | 572 | logging.debug(f"Conversation {conversation.id} history (count): {len(conversation.history)}") 573 | if conversation.history: 574 | logging.debug(f"First message in history: {conversation.history[0]}") 575 | 576 | return conversation 577 | 578 | def get_conversation_from_id(self, conversation_id: str, return_index=False) -> Conversation: 579 | """ 580 | Returns a conversation object that is already in the conversation list. 581 | """ 582 | 583 | for i, conversation in enumerate(self.conversation_list): 584 | if conversation.id == conversation_id: 585 | if return_index: 586 | return i 587 | return conversation 588 | 589 | def _parse_assistants(self, nodes_data: list) -> List[Assistant]: 590 | ''' 591 | parse the assistants data from the response. 592 | ''' 593 | index = nodes_data[1] 594 | ret = [] 595 | for i in index: 596 | attribute_map: dict = nodes_data[i] 597 | assistant_id = nodes_data[attribute_map['_id']] 598 | author = nodes_data[attribute_map['createdByName']] 599 | name = nodes_data[attribute_map['name']].strip() 600 | model_name = nodes_data[attribute_map['modelId']] 601 | pre_prompt = nodes_data[attribute_map['preprompt']] 602 | description = nodes_data[attribute_map['description']] 603 | ret.append(Assistant( 604 | assistant_id, 605 | author, 606 | name, 607 | model_name, 608 | pre_prompt, 609 | description 610 | )) 611 | return ret 612 | 613 | def get_assistant_list_by_page(self, page: int) -> List[Assistant]: 614 | ''' 615 | get assistant list by page number. 616 | if page < 0 or page > max_page then return `None`. 617 | ''' 618 | url = f"https://huggingface.co/chat/assistants/__data.json?p={page}&x-sveltekit-invalidated=01" 619 | res = self.session.get(url, timeout=10) 620 | res = res.json() 621 | if res['nodes'][1]['type'] == 'error': 622 | return None 623 | # here we parse the result 624 | return self._parse_assistants(res['nodes'][1]['data']) 625 | 626 | def search_assistant(self, assistant_name: str = None, assistant_id: str = None) -> Assistant: 627 | ''' 628 | [DEPRECATED] 629 | - If you created an assistant by your own, you should pass the assistant_id here but not the assistant_name. You can pass your assistant_id into the new_conversation() directly. 630 | - Search an available assistant by assistant name or assistant id. 631 | - Will search on api.soulter.top/hugchat because offifial api doesn't support search. 632 | - Return the `Assistant` object if found, return None if not found. 633 | ''' 634 | if not assistant_name and not assistant_id: 635 | raise ValueError( 636 | "assistant_name and assistant_id can not be both None.") 637 | if assistant_name: 638 | url = f"https://api.soulter.top/hugchat/assistant?name={assistant_name}" 639 | else: 640 | url = f"https://api.soulter.top/hugchat/assistant?id={assistant_id}" 641 | res = requests.get(url, timeout=10) 642 | if res.status_code != 200: 643 | raise Exception( 644 | f"Failed to search assistant with status code: {res.status_code}, please commit an issue to https://github.com/Soulter/hugging-chat-api/issues") 645 | res = res.json() 646 | if not res['data']: 647 | # empty dict 648 | return None 649 | if res['code'] != 0: 650 | raise Exception( 651 | f"Failed to search assistant with server's error: {res['message']}, please commit an issue to https://github.com/Soulter/hugging-chat-api/issues") 652 | return Assistant(**res['data']) 653 | 654 | def _stream_query( 655 | self, 656 | text: str, 657 | web_search: bool = False, 658 | is_retry: bool = False, 659 | retry_count: int = 5, 660 | conversation: Conversation = None, 661 | message_id: str = None, 662 | ) -> typing.Generator[dict, None, None]: 663 | if conversation is None: 664 | conversation = self.current_conversation 665 | 666 | if retry_count <= 0: 667 | raise Exception( 668 | "the parameter retry_count must be greater than 0.") 669 | if len(conversation.history) == 0: 670 | raise Exception( 671 | "conversation history is empty, but we need the root message id of this conversation to continue.") 672 | 673 | if not message_id: 674 | # get last message id 675 | message_id = conversation.history[-1].id 676 | 677 | logging.debug(f'message_id: {message_id}') 678 | 679 | req_json = { 680 | "id": message_id, 681 | "inputs": text, 682 | "is_continue": False, 683 | "is_retry": is_retry, 684 | "web_search": web_search, 685 | "tools": [] 686 | } 687 | headers = { 688 | 'authority': 'huggingface.co', 689 | 'accept': '*/*', 690 | 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,en-GB;q=0.6', 691 | 'origin': 'https://huggingface.co', 692 | 'sec-ch-ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"', 693 | 'sec-ch-ua-mobile': '?0', 694 | 'sec-ch-ua-platform': '"macOS"', 695 | 'sec-fetch-dest': 'empty', 696 | 'sec-fetch-mode': 'cors', 697 | 'sec-fetch-site': 'same-origin', 698 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0', 699 | } 700 | obj = {} 701 | break_flag = False 702 | has_started = False 703 | 704 | initial_retry_count = retry_count # Track initial retry count 705 | 706 | while retry_count > 0: 707 | # Update is_retry flag for subsequent attempts 708 | if retry_count < initial_retry_count: 709 | req_json["is_retry"] = True 710 | 711 | resp = self.session.post( 712 | self.hf_base_url + f"/chat/conversation/{conversation}", 713 | files={ "data": (None, json.dumps(req_json)) }, 714 | stream=True, 715 | headers=headers, 716 | cookies=self.session.cookies.get_dict(), 717 | ) 718 | resp.encoding = 'utf-8' 719 | 720 | if resp.status_code != 200: 721 | retry_count -= 1 722 | if retry_count <= 0: 723 | raise exceptions.ChatError( 724 | f"Failed to chat. ({resp.status_code})") 725 | continue # Skip processing on non-200 status 726 | 727 | try: 728 | for line in resp.iter_lines(decode_unicode=True): 729 | if not line: 730 | continue 731 | res = line 732 | obj = json.loads(res) 733 | if "type" in obj: 734 | _type = obj["type"] 735 | 736 | if _type == "finalAnswer": 737 | break_flag = True 738 | break 739 | 740 | if _type == "status" and obj["status"] == "started": 741 | if has_started: 742 | obj = { 743 | "type": "finalAnswer", 744 | "text": "" 745 | } 746 | break_flag = True 747 | break 748 | has_started = True 749 | 750 | else: 751 | logging.error(f"No `type` found in response: {obj}") 752 | yield obj 753 | # After processing all lines, mark completion 754 | break_flag = True 755 | except requests.exceptions.ChunkedEncodingError: 756 | pass 757 | except BaseException as e: 758 | traceback.print_exc() 759 | if "Model is overloaded" in str(e): 760 | raise exceptions.ModelOverloadedError( 761 | "Model is overloaded, please try again later or switch to another model." 762 | ) 763 | logging.debug(resp.headers) 764 | if "Conversation not found" in str(res): 765 | raise exceptions.InvalidConversationIDError("Conversation id invalid") 766 | raise exceptions.ChatError(f"Failed to parse response: {res}") 767 | if break_flag: 768 | break 769 | 770 | # Update the history of current conversation 771 | self.get_conversation_info(conversation) 772 | yield obj 773 | 774 | def query(self) -> Message: 775 | """ 776 | **Deprecated** 777 | Please use `chat()`. The function will raise an error immediately. 778 | """ 779 | raise Exception("The function is deprecated. Please use `chat()`") 780 | 781 | def get_message_node(self, conversation: Conversation, message_id: str): 782 | for node in conversation.history: 783 | if node.id == message_id: 784 | return node 785 | raise Exception(f"no node found which id is {message_id}") 786 | 787 | def chat( 788 | self, 789 | text: str, 790 | web_search: bool = False, 791 | # For stream mode, yield all responses from the server. 792 | _stream_yield_all: bool = False, 793 | retry_count: int = 5, 794 | conversation: Conversation = None, 795 | edit_user_node: MessageNode = None, 796 | *args, 797 | **kvargs, 798 | ) -> Message: 799 | """ 800 | - Send a message to the current conversation. Return a Message object. 801 | 802 | - You can turn on the web search by set the parameter `web_search` to True. 803 | 804 | - Stream is now the default mode, you can call Message.wait_until_done() to get the result text. 805 | 806 | - `Edit history`: pass `edit_user_node`. The history can be retrieved from `conversation.history`. 807 | 808 | - About class `Message`: 809 | - `wait_until_done()`: Block until the response done processing or an error raised. 810 | - `__iter__()`: For loop call this Generator and get response. 811 | - `get_search_sources()`: The web search results. It is a list of WebSearchSource objects. 812 | 813 | - For more detail please see Message documentation(Message.__doc__) 814 | """ 815 | if conversation is None: 816 | conversation = self.current_conversation 817 | 818 | if not text: 819 | raise Exception("don't support an empty string(I'm sure LLM cannot understand it)") 820 | if edit_user_node and edit_user_node.role != 'user': 821 | raise Exception("you must pass a user's message node to edit message") 822 | 823 | is_retry = True if edit_user_node else False 824 | edit_message_id = edit_user_node.id if is_retry else None 825 | 826 | msg = Message( 827 | g=self._stream_query( 828 | text=text, 829 | web_search=web_search, 830 | retry_count=retry_count, 831 | conversation=conversation, 832 | is_retry=is_retry, 833 | message_id=edit_message_id 834 | ), 835 | _stream_yield_all=_stream_yield_all, 836 | web_search=web_search, 837 | conversation=conversation 838 | ) 839 | return msg 840 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------