├── examples ├── deepseek_api ├── simple_app.py ├── synchronous_cli.py └── cli.py ├── .env.example ├── deepseek_api ├── __init__.py ├── errors.py ├── constants.py └── deepseek_api.py ├── .gitignore ├── requirements.txt ├── setup.py ├── README.md └── LICENSE /examples/deepseek_api: -------------------------------------------------------------------------------- 1 | ../deepseek_api -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | DEEPSEEK_EMAIL= 2 | DEEPSEEK_PASSWORD= -------------------------------------------------------------------------------- /deepseek_api/__init__.py: -------------------------------------------------------------------------------- 1 | from .deepseek_api import DeepseekAPI, SyncDeepseekAPI 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *.pyc 3 | __pycache__/ 4 | *.egg-info/ 5 | dist/ 6 | build/ 7 | 8 | login.json 9 | .env 10 | .venv -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2023.11.17 2 | charset-normalizer==3.3.2 3 | idna==3.6 4 | python-dotenv==1.0.0 5 | requests==2.31.0 6 | urllib3==2.1.0 7 | PyJWT==2.3.0 8 | aiofiles==23.2.1 9 | aiohttp==3.9.1 10 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | def read_requirements(): 4 | with open('requirements.txt') as req: 5 | content = req.read() 6 | requirements = content.split('\n') 7 | return requirements 8 | 9 | 10 | setup( 11 | name='deepseek_api', 12 | version='0.5.3', 13 | packages=find_packages(), 14 | install_requires=read_requirements(), 15 | description='An unofficial Python API wrapper for chat.Deepseek.com', 16 | ) -------------------------------------------------------------------------------- /deepseek_api/errors.py: -------------------------------------------------------------------------------- 1 | class NotLoggedInError(Exception): 2 | """Exception raised when the user is not logged in.""" 3 | def __init__(self, message="You are not logged in. Please login first"): 4 | self.message = message 5 | super().__init__(self.message) 6 | 7 | class EmptyEmailOrPasswordError(Exception): 8 | """Exception raised when the email or password is empty.""" 9 | def __init__(self, message="Email or password cannot be empty"): 10 | self.message = message 11 | super().__init__(self.message) -------------------------------------------------------------------------------- /examples/simple_app.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | from deepseek_api import DeepseekAPI 4 | from dotenv import load_dotenv 5 | 6 | load_dotenv() 7 | 8 | 9 | async def main(): 10 | email = os.environ.get("DEEPSEEK_EMAIL") 11 | password = os.environ.get("DEEPSEEK_PASSWORD") 12 | 13 | app = await DeepseekAPI.create(email=email, password=password, model_class="deepseek_code", save_login=True) 14 | 15 | async for chunk in app.chat("hi"): 16 | print(chunk["choices"][0]["delta"]["content"], end="") 17 | 18 | print() 19 | await app.close() 20 | 21 | 22 | if __name__ == "__main__": 23 | asyncio.run(main()) 24 | -------------------------------------------------------------------------------- /deepseek_api/constants.py: -------------------------------------------------------------------------------- 1 | class API_URL: 2 | """Deepseek API URL constants""" 3 | 4 | BASE_URL = "https://coder.deepseek.com/api/v0" 5 | LOGIN = BASE_URL + "/users/login" 6 | CLEAR_CONTEXT = BASE_URL + "/chat/clear_context" 7 | CHAT = BASE_URL + "/chat/completions" 8 | 9 | 10 | class DeepseekConstants: 11 | """Deepseek constants""" 12 | 13 | BASE_HEADERS = { 14 | "Accept-Language": "en-IN,en;q=0.9", 15 | "Cache-Control": "no-cache", 16 | "Connection": "keep-alive", 17 | "DNT": "1", 18 | "Origin": "https://coder.deepseek.com", 19 | "Pragma": "no-cache", 20 | "Referer": "https://coder.deepseek.com/", 21 | "Sec-Fetch-Dest": "empty", 22 | "Sec-Fetch-Mode": "cors", 23 | "Sec-Fetch-Site": "same-origin", 24 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome", 25 | "accept": "*/*", 26 | "content-type": "application/json", 27 | "sec-ch-ua": '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"', 28 | "sec-ch-ua-mobile": "?0", 29 | "sec-ch-ua-platform": '"Linux"', 30 | "x-app-version": "20240105.0", 31 | } 32 | -------------------------------------------------------------------------------- /examples/synchronous_cli.py: -------------------------------------------------------------------------------- 1 | import os 2 | from deepseek_api import SyncDeepseekAPI 3 | from dotenv import load_dotenv 4 | 5 | load_dotenv() 6 | 7 | 8 | def main(): 9 | email = os.environ.get("DEEPSEEK_EMAIL") 10 | password = os.environ.get("DEEPSEEK_PASSWORD") 11 | 12 | app = SyncDeepseekAPI( 13 | email=email, 14 | password=password, 15 | save_login=True, # save login credentials to login.json 16 | model_class="deepseek_code", # Choose from "deepseek_chat" or "deepseek_code" 17 | ) 18 | 19 | print( 20 | """ 21 | Usage: 22 | - Type 'new' to start a new chat. 23 | - Type 'exit' to exit. 24 | 25 | Start chatting! 26 | """ 27 | ) 28 | 29 | while True: 30 | message = input("> ") 31 | 32 | if message == "exit": 33 | # close the app 34 | app.close() 35 | break 36 | elif message == "new": 37 | app.new_chat() 38 | continue 39 | 40 | response = app.chat(message) 41 | 42 | for chunk in response: 43 | try: 44 | # keep printing in one line 45 | print(chunk["choices"][0]["delta"]["content"], end="") 46 | except KeyError as ke: 47 | print(ke) 48 | print() 49 | 50 | 51 | if __name__ == "__main__": 52 | main() 53 | -------------------------------------------------------------------------------- /examples/cli.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | from deepseek_api import DeepseekAPI 4 | from dotenv import load_dotenv 5 | 6 | load_dotenv() 7 | 8 | 9 | async def main(): 10 | email = os.environ.get("DEEPSEEK_EMAIL") 11 | password = os.environ.get("DEEPSEEK_PASSWORD") 12 | 13 | async with DeepseekAPI( 14 | email=email, 15 | password=password, 16 | save_login=True, # save login credentials to login.json 17 | model_class="deepseek_code", # Choose from "deepseek_chat" or "deepseek_code" 18 | ) as app: 19 | print( 20 | """ 21 | Usage: 22 | - Type 'new' to start a new chat. 23 | - Type 'exit' to exit. 24 | 25 | Start chatting! 26 | """ 27 | ) 28 | 29 | while True: 30 | message = input("> ") 31 | 32 | if message == "exit": 33 | break 34 | elif message == "new": 35 | await app.new_chat() 36 | continue 37 | 38 | async for chunk in app.chat(message): 39 | try: 40 | # keep printing in one line 41 | print(chunk["choices"][0]["delta"]["content"], end="") 42 | except KeyError as ke: 43 | print(ke) 44 | print() 45 | 46 | 47 | if __name__ == "__main__": 48 | asyncio.run(main()) 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deepseek coder Reverse Engineered API Wrapper 2 | 3 | Unofficial API Wrapper for Deepseek (chat.deepseek.com) in Python. This is a reverse-engineered API for the Deepseek coder and Deepseek code chatbots. This API is not affiliated with Deepseek in any way. 4 | 5 | ## Installation 6 | 7 | ```bash 8 | pip install git+https://github.com/rabilrbl/deepseek-api.git 9 | ``` 10 | 11 | ## Usage 12 | 13 | ### Asynchronous CLI Example 14 | 15 | ```python 16 | import asyncio 17 | import os 18 | from deepseek_api import DeepseekAPI 19 | from dotenv import load_dotenv 20 | 21 | load_dotenv() 22 | 23 | 24 | async def main(): 25 | email = os.environ.get("DEEPSEEK_EMAIL") 26 | password = os.environ.get("DEEPSEEK_PASSWORD") 27 | 28 | async with DeepseekAPI( 29 | email=email, 30 | password=password, 31 | save_login=True, # save login credentials to login.json 32 | model_class="deepseek_code", # Choose from "deepseek_chat" or "deepseek_code" 33 | ) as app: 34 | print( 35 | """ 36 | Usage: 37 | - Type 'new' to start a new chat. 38 | - Type 'exit' to exit. 39 | 40 | Start chatting! 41 | """ 42 | ) 43 | 44 | while True: 45 | message = input("> ") 46 | 47 | if message == "exit": 48 | break 49 | elif message == "new": 50 | await app.new_chat() 51 | continue 52 | 53 | async for chunk in app.chat(message): 54 | try: 55 | # keep printing in one line 56 | print(chunk["choices"][0]["delta"]["content"], end="") 57 | except KeyError as ke: 58 | print(ke) 59 | print() 60 | 61 | 62 | if __name__ == "__main__": 63 | if sys.platform == 'win32': 64 | asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 65 | asyncio.run(main()) 66 | ``` 67 | 68 | ### Synchonous CLI Example 69 | 70 | ```python 71 | import os 72 | from deepseek_api import SyncDeepseekAPI 73 | from dotenv import load_dotenv 74 | 75 | load_dotenv() 76 | 77 | 78 | def main(): 79 | email = os.environ.get("DEEPSEEK_EMAIL") 80 | password = os.environ.get("DEEPSEEK_PASSWORD") 81 | 82 | app = SyncDeepseekAPI( 83 | email=email, 84 | password=password, 85 | save_login=True, # save login credentials to login.json 86 | model_class="deepseek_code", # Choose from "deepseek_chat" or "deepseek_code" 87 | ) 88 | 89 | print( 90 | """ 91 | Usage: 92 | - Type 'new' to start a new chat. 93 | - Type 'exit' to exit. 94 | 95 | Start chatting! 96 | """ 97 | ) 98 | 99 | while True: 100 | message = input("> ") 101 | 102 | if message == "exit": 103 | # close the app 104 | app.close() 105 | break 106 | elif message == "new": 107 | app.new_chat() 108 | continue 109 | 110 | response = app.chat(message) 111 | 112 | for chunk in response: 113 | try: 114 | # keep printing in one line 115 | print(chunk["choices"][0]["delta"]["content"], end="") 116 | except KeyError as ke: 117 | print(ke) 118 | print() 119 | 120 | 121 | if __name__ == "__main__": 122 | main() 123 | ``` 124 | 125 | ## License 126 | 127 | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) 128 | 129 | ## Disclaimer 130 | 131 | This project is not affiliated with Deepseek in any way. Use at your own risk. This project was created for educational purposes only. 132 | 133 | ## Contributing 134 | 135 | Contributions are welcome! Please feel free to submit a Pull Request. 136 | -------------------------------------------------------------------------------- /deepseek_api/deepseek_api.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import aiohttp 3 | import aiofiles 4 | import threading 5 | import json 6 | import jwt 7 | import datetime 8 | from abc import ABC, abstractmethod 9 | from deepseek_api.constants import API_URL, DeepseekConstants 10 | from deepseek_api.errors import EmptyEmailOrPasswordError, NotLoggedInError 11 | 12 | 13 | class DeepseekBase(ABC): 14 | """ 15 | A base class to create DeepseekAPI instances. 16 | """ 17 | 18 | def __init__( 19 | self, 20 | email: str, 21 | password: str, 22 | model_class: str = "deepseek_code", 23 | save_login: bool = False, 24 | ): 25 | """ 26 | Constructor method for DeepseekAPI class. 27 | 28 | Initializes a DeepseekAPI instance with provided credentials and settings. 29 | 30 | Parameters: 31 | email (str): User's email for Deepseek account 32 | password (str): Password for user's Deepseek account 33 | model_class (str): Deepseek model to use, either 'deepseek_chat' or 'deepseek_code' 34 | save_login (bool): Whether to save credentials to login.json to avoid re-login 35 | 36 | """ 37 | self.email = email 38 | self.password = password 39 | self.model_class = model_class 40 | self.save_login = save_login 41 | self.headers = DeepseekConstants.BASE_HEADERS 42 | self.credentials = {} 43 | self._thread_timer = None # Initialized in the _schedule_update_token method 44 | self.session = None 45 | 46 | def set_authorization_header(self): 47 | """Sets the authorization header to a JWT token. 48 | 49 | Gets the JWT token by calling get_token() and prepends 'Bearer ' 50 | to set the authorization header. 51 | """ 52 | self.headers["authorization"] = "Bearer " + self.get_token() 53 | 54 | def get_token(self): 55 | """Get token 56 | 57 | Returns: 58 | str: JWT Authorization token 59 | """ 60 | return self.get_credentials()["data"]["user"]["token"] 61 | 62 | def get_credentials(self): 63 | """Get credentials 64 | 65 | Returns: 66 | dict: Credentials JSON data from login response 67 | """ 68 | return self.credentials 69 | 70 | def _schedule_update_token(self): 71 | """Schedules a timer to refresh the JWT token before it expires. 72 | 73 | Decodes the current JWT token to get the 'exp' expiration time. 74 | Subtracts 1 hour from the 'exp' time to refresh the token early. 75 | Starts a Timer thread to call the _login() method when the expiration 76 | time is reached. This will refresh the token and update the authorization 77 | header with the new token. 78 | """ 79 | # Decode the JWT token 80 | token = self.get_token() 81 | decoded_token = jwt.decode(token, options={"verify_signature": False}) 82 | 83 | # Fetch the 'exp' value and subtract 1 hour (to be safe) 84 | exp_time = datetime.datetime.fromtimestamp( 85 | decoded_token["exp"] 86 | ) - datetime.timedelta(hours=1) 87 | 88 | self._thread_timer = threading.Timer( 89 | (exp_time - datetime.datetime.now()).total_seconds(), self._login 90 | ) 91 | self._thread_timer.start() 92 | 93 | def is_logged_in(self): 94 | """Check if user is logged in 95 | 96 | Returns: 97 | bool: True if logged in, False otherwise 98 | """ 99 | if self.credentials: 100 | return True 101 | else: 102 | return False 103 | 104 | def raise_for_not_logged_in(self): 105 | """Raise NotLoggedInError if user is not logged in 106 | 107 | Raises: 108 | NotLoggedInError: If user is not logged in 109 | """ 110 | if not self.is_logged_in(): 111 | raise NotLoggedInError 112 | 113 | @abstractmethod 114 | def login(self): 115 | """Logs the user in by loading credentials from file or calling login API. 116 | 117 | If save_login is True, tries to load credentials from the login.json file. 118 | If file not found, calls _login() to login via API. 119 | 120 | If save_login is False, calls _login() to always login via API. 121 | 122 | Schedules an update token callback to refresh the token periodically. 123 | """ 124 | pass 125 | 126 | @abstractmethod 127 | def close(self): 128 | """Call destructor method""" 129 | pass 130 | 131 | @abstractmethod 132 | def new_chat(self): 133 | """Start a new chat""" 134 | pass 135 | 136 | @abstractmethod 137 | def chat(self, message: str): 138 | """Chat with the Deepseek API. 139 | 140 | Sends a chat message to the Deepseek API and yields the response. 141 | 142 | Args: 143 | message (str): The chat message to send. 144 | 145 | Yields: 146 | dict: The JSON response from the API for each chat message. 147 | """ 148 | pass 149 | 150 | @abstractmethod 151 | def _login(self): 152 | """Logs in the user by sending a POST request to the login API endpoint. 153 | 154 | Sends the login request with email, password and other required fields. 155 | Saves the credentials to a file if save_login is True. 156 | Returns the JSON response from the API. 157 | 158 | Raises: 159 | EmptyEmailOrPasswordError: If the email or password is not provided. 160 | HTTP Error: If the login request fails. 161 | 162 | Returns: 163 | dict: Credentials JSON data from login response 164 | """ 165 | pass 166 | 167 | 168 | 169 | class DeepseekAPI(DeepseekBase): 170 | """ 171 | An asynchronous class to interact with the Deepseek API. 172 | """ 173 | 174 | async def __aenter__(self): 175 | """Initializes an aiohttp ClientSession and logs in. 176 | 177 | This method is called when entering an async context manager. 178 | It creates the aiohttp ClientSession used for making requests. 179 | It also calls the login() method to authenticate with Deepseek. 180 | 181 | Returns: 182 | Self - Returns itself to enable use as an async context manager. 183 | """ 184 | self.session = aiohttp.ClientSession() 185 | await self.login() 186 | return self 187 | 188 | async def __aexit__(self, exc_type, exc, tb): 189 | """Closes the aiohttp ClientSession and cancels the scheduled token update. 190 | 191 | This method is called when exiting the async context manager. It closes 192 | the aiohttp ClientSession that was used for making requests to the API. 193 | 194 | It also cancels the scheduled token update that was created in 195 | __schedule_update_token() to periodically refresh the auth token. 196 | """ 197 | await self.session.close() 198 | if self._thread_timer: 199 | self._thread_timer.cancel() 200 | 201 | @staticmethod 202 | async def create(*args, **kwargs): 203 | """Creates a new DeepseekAPI instance and enters the context manager. 204 | 205 | This static method initializes a new DeepseekAPI instance with the given 206 | arguments and enters the async context manager by calling __aenter__(). 207 | 208 | Args: 209 | *args: Positional arguments to pass to DeepseekAPI constructor. 210 | **kwargs: Keyword arguments to pass to DeepseekAPI constructor. 211 | 212 | Returns: 213 | DeepseekAPI instance that has entered the context manager. 214 | """ 215 | self = DeepseekAPI(*args, **kwargs) 216 | await self.__aenter__() 217 | return self 218 | 219 | async def close(self): 220 | """Closes the DeepseekAPI instance by exiting the context manager. 221 | 222 | Calls __aexit__ to close the aiohttp session and cancel the token update. 223 | """ 224 | await self.__aexit__(None, None, None) 225 | 226 | async def _login(self): 227 | if self.email == "" or self.password == "": 228 | raise EmptyEmailOrPasswordError 229 | 230 | json_data = { 231 | "email": self.email, 232 | "mobile": "", 233 | "password": self.password, 234 | "area_code": "", 235 | } 236 | 237 | async with self.session.post( 238 | API_URL.LOGIN, headers=self.headers, json=json_data 239 | ) as response: 240 | self.credentials = await response.json() 241 | self.headers["authorization"] = "Bearer " + self.get_token() 242 | 243 | if self.save_login: 244 | async with aiofiles.open("login.json", "w") as file: 245 | await file.write(json.dumps(self.credentials)) 246 | 247 | return await response.json() 248 | 249 | async def login(self): 250 | """Logs the user in by loading credentials from file or calling login API. 251 | 252 | If save_login is True, tries to load credentials from the login.json file. 253 | If file not found, calls _login() to login via API. 254 | 255 | If save_login is False, calls _login() to always login via API. 256 | 257 | Schedules an update token callback to refresh the token periodically. 258 | """ 259 | if self.save_login: 260 | try: 261 | async with aiofiles.open("login.json", "r") as file: 262 | content = await file.read() 263 | self.credentials = json.loads(content) 264 | 265 | self.set_authorization_header() 266 | except FileNotFoundError: 267 | await self._login() 268 | else: 269 | await self._login() 270 | # Schedule a callback to update the token periodically 271 | self._schedule_update_token() 272 | 273 | async def new_chat(self): 274 | """Start a new chat asynchronously""" 275 | 276 | params = { 277 | "session_id": "1", 278 | } 279 | 280 | json_data = { 281 | "model_class": self.model_class, 282 | "append_welcome_message": False, 283 | } 284 | 285 | async with self.session.post( 286 | API_URL.CLEAR_CONTEXT, params=params, headers=self.headers, json=json_data 287 | ) as response: 288 | return await response.json() 289 | 290 | async def chat(self, message: str): 291 | """Chat asynchronously with the Deepseek API. 292 | 293 | Sends a chat message to the Deepseek API and yields the response. 294 | 295 | Args: 296 | message (str): The chat message to send. 297 | 298 | Yields: 299 | dict: The JSON response from the API for each chat message. 300 | """ 301 | 302 | json_data = { 303 | "message": message, 304 | "stream": True, 305 | "model_class": self.model_class, 306 | "model_preference": None, 307 | "temperature": 0, 308 | } 309 | 310 | async with self.session.post( 311 | API_URL.CHAT, headers=self.headers, json=json_data 312 | ) as response: 313 | # Check if the request was successful (status code 200) 314 | response.raise_for_status() 315 | 316 | # Iterate over the content asynchronously 317 | async for data in response.content: 318 | line = data.decode().strip().replace("data: ", "") 319 | if line: 320 | line = json.loads(line) 321 | if line.get("payload", None) is None: 322 | line["choices"][0]["delta"]["content"] = "" 323 | yield line 324 | 325 | 326 | class SyncDeepseekAPI(DeepseekBase): 327 | """ 328 | A synchronous class to interact with the Deepseek API. 329 | """ 330 | 331 | def __init__( 332 | self, 333 | email: str, 334 | password: str, 335 | model_class: str = "deepseek_code", 336 | save_login: bool = False, 337 | *args, 338 | **kwargs, 339 | ): 340 | super().__init__(email, password, model_class, save_login, *args, **kwargs) 341 | self.session = requests.Session() 342 | self.login() 343 | 344 | def __del__(self): 345 | """Destructor method for DeepseekAPI class. 346 | 347 | Closes the requests Session that was used for making requests to the API. 348 | """ 349 | self.session.close() 350 | if self._thread_timer is not None: 351 | self._thread_timer.cancel() 352 | 353 | def close(self): 354 | """Call destructor method""" 355 | self.__del__() 356 | 357 | def _login(self): 358 | """Logs in the user by sending a POST request to the login API endpoint. 359 | 360 | Sends the login request with email, password and other required fields. 361 | Saves the credentials to a file if save_login is True. 362 | Returns the JSON response from the API. 363 | 364 | Raises: 365 | EmptyEmailOrPasswordError: If the email or password is not provided. 366 | requests.exceptions.RequestException: If the login request fails. 367 | 368 | Returns: 369 | dict: Credentials JSON data from login response 370 | """ 371 | if self.email == "" or self.password == "": 372 | raise EmptyEmailOrPasswordError 373 | 374 | json_data = { 375 | "email": self.email, 376 | "mobile": "", 377 | "password": self.password, 378 | "area_code": "", 379 | } 380 | 381 | response = self.session.post( 382 | API_URL.LOGIN, headers=self.headers, json=json_data 383 | ) 384 | self.credentials = response.json() 385 | self.headers["authorization"] = "Bearer " + self.get_token() 386 | 387 | if self.save_login: 388 | with open("login.json", "w") as file: 389 | file.write(json.dumps(self.credentials)) 390 | 391 | return response.json() 392 | 393 | def login(self): 394 | """Logs the user in by loading credentials from file or calling login API. 395 | 396 | If save_login is True, tries to load credentials from the login.json file. 397 | If file not found, calls _login() to login via API. 398 | 399 | If save_login is False, calls _login() to always login via API. 400 | 401 | Schedules an update token callback to refresh the token periodically. 402 | """ 403 | if self.save_login: 404 | try: 405 | with open("login.json", "r") as file: 406 | content = file.read() 407 | self.credentials = json.loads(content) 408 | 409 | self.set_authorization_header() 410 | except FileNotFoundError: 411 | self._login() 412 | else: 413 | self._login() 414 | # Schedule a callback to update the token periodically 415 | self._schedule_update_token() 416 | 417 | def new_chat(self): 418 | """Start a new chat synchronously""" 419 | 420 | params = { 421 | "session_id": "1", 422 | } 423 | 424 | json_data = { 425 | "model_class": self.model_class, 426 | "append_welcome_message": False, 427 | } 428 | 429 | response = self.session.post( 430 | API_URL.CLEAR_CONTEXT, params=params, headers=self.headers, json=json_data 431 | ) 432 | return response.json() 433 | 434 | def chat(self, message: str): 435 | """Chat synchronously with the Deepseek API. 436 | 437 | Sends a chat message to the Deepseek API and yields the response. 438 | 439 | Args: 440 | message (str): The chat message to send. 441 | 442 | Yields: 443 | dict: The JSON response from the API for each chat message. 444 | """ 445 | 446 | json_data = { 447 | "message": message, 448 | "stream": True, 449 | "model_class": self.model_class, 450 | "model_preference": None, 451 | "temperature": 0, 452 | } 453 | 454 | with self.session.post( 455 | API_URL.CHAT, headers=self.headers, json=json_data, stream=True 456 | ) as response: 457 | # Check if the request was successful (status code 200) 458 | response.raise_for_status() 459 | 460 | # Iterate over the content in chunks 461 | for line in response.iter_lines(decode_unicode=True): 462 | if line: 463 | line = line.strip().replace("data: ", "") 464 | line: dict = json.loads(line) 465 | if ( 466 | line.get("payload", None) is None 467 | ): # Hack to fix initial empty payload 468 | line["choices"][0]["delta"]["content"] = "" 469 | yield line 470 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. 438 | --------------------------------------------------------------------------------