├── .gitignore ├── LICENSE ├── README.md ├── grok_client ├── __init__.py └── client.py ├── pyproject.toml └── setup.cfg /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # PyPI configuration file 171 | .pypirc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Mem0 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Grok3 API 2 | 3 | Grok3 is cool, smart, and useful, but there is no official API available. This is an **unofficial Python client** for interacting with the Grok 3 API. It leverages cookies from browser requests to authenticate and access the API endpoints. 4 | 5 | --- 6 | 7 | ## Setup 8 | 9 | Follow these steps to get started with the Grok3 API client. 10 | 11 | ### 1. Clone the Repository 12 | 13 | Clone this repository to your local machine: 14 | 15 | ```bash 16 | git clone https://github.com/mem0ai/grok3-api.git 17 | ``` 18 | 19 | ### 2. Install the Package 20 | Navigate to the project directory, create a virtual environment, and install the package: 21 | 22 | ``` 23 | cd grok3-api 24 | virtualenv pyenv 25 | source pyenv/bin/activate 26 | pip install . 27 | ``` 28 | 29 | ### 3. Obtain Cookie Values 30 | 31 | To use this client, you need to extract authentication cookies from a browser session: 32 | 33 | * Open grok.com in your browser. 34 | * Log in if you aren't already logged in. 35 | * Open the browser's developer tools (e.g., F12 or right-click > Inspect). 36 | * Go to the "Network" tab and filter for requests containing the new-chat endpoint (e.g., https://grok.com/rest/app-chat/conversations/new). 37 | * Right-click the request, select "Copy as cURL," and paste it somewhere. 38 | From the curl command, extract the following cookie values from the -H 'cookie: ...' header: 39 | * x-anonuserid 40 | * x-challenge 41 | * x-signature 42 | * sso 43 | * sso-rw 44 | 45 | Example cookie string from a curl command: 46 | ``` 47 | -H 'cookie: x-anonuserid=ffdd32e1; x-challenge=TkC4D...; x-signature=fJ0U00...; sso=eyJhbGci...; sso-rw=eyJhbGci...' 48 | ``` 49 | 50 | ### 4. Use the Client 51 | 52 | Pass the extracted cookie values to the GrokClient and send a message: 53 | 54 | ``` 55 | from grok_client import GrokClient 56 | 57 | # Your cookie values 58 | cookies = { 59 | "x-anonuserid": "ffdd32e1", 60 | "x-challenge": "TkC4D..", 61 | "x-signature": "fJ0...", 62 | "sso": "ey...", 63 | "sso-rw": "ey..." 64 | } 65 | 66 | # Initialize the client 67 | client = GrokClient(cookies) 68 | 69 | # Send a message and get response 70 | response = client.send_message("write a poem") 71 | print(response) 72 | ``` 73 | 74 | ### 5. Optional: Add Memory with Mem0 75 | 76 | If you want Grok to remember conversations, you can integrate it with Mem0. Mem0 provides a memory layer for AI applications. 77 | 78 | #### 5.1 Install Mem0 79 | 80 | ```bash 81 | pip install mem0ai 82 | ``` 83 | 84 | #### 5.2 Add & Retrieve Memory 85 | 86 | ``` 87 | from mem0 import Memory 88 | 89 | memory = Memory() 90 | 91 | # for user alice 92 | result = memory.add("I like to take long walks on weekends.", user_id="alice") 93 | 94 | # Retrieve memories 95 | related_memories = memory.search(, user_id="alice") 96 | print(related_memories) 97 | ``` 98 | 99 | 100 | # Disclaimer 101 | This is an unofficial API client for Grok3 and is not affiliated with or endorsed by xAI, the creators of Grok. It relies on reverse-engineering browser requests and may break if the underlying API changes. Use at your own risk. The authors are not responsible for any consequences arising from its use, including but not limited to account suspension, data loss, or legal issues. Ensure you comply with Grok's terms of service and applicable laws when using this client -------------------------------------------------------------------------------- /grok_client/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import GrokClient 2 | 3 | __version__ = "0.1.0" 4 | __all__ = ['GrokClient'] -------------------------------------------------------------------------------- /grok_client/client.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | class GrokClient: 5 | def __init__(self, cookies): 6 | """ 7 | Initialize the Grok client with cookie values 8 | 9 | Args: 10 | cookies (dict): Dictionary containing cookie values 11 | - x-anonuserid 12 | - x-challenge 13 | - x-signature 14 | - sso 15 | - sso-rw 16 | """ 17 | self.base_url = "https://grok.com/rest/app-chat/conversations/new" 18 | self.cookies = cookies 19 | self.headers = { 20 | "accept": "*/*", 21 | "accept-language": "en-GB,en;q=0.9", 22 | "content-type": "application/json", 23 | "origin": "https://grok.com", 24 | "priority": "u=1, i", 25 | "referer": "https://grok.com/", 26 | "sec-ch-ua": '"Not/A)Brand";v="8", "Chromium";v="126", "Brave";v="126"', 27 | "sec-ch-ua-mobile": "?0", 28 | "sec-ch-ua-platform": '"macOS"', 29 | "sec-fetch-dest": "empty", 30 | "sec-fetch-mode": "cors", 31 | "sec-fetch-site": "same-origin", 32 | "sec-gpc": "1", 33 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" 34 | } 35 | 36 | def _prepare_payload(self, message): 37 | """Prepare the default payload with the user's message""" 38 | return { 39 | "temporary": False, 40 | "modelName": "grok-3", 41 | "message": message, 42 | "fileAttachments": [], 43 | "imageAttachments": [], 44 | "disableSearch": False, 45 | "enableImageGeneration": True, 46 | "returnImageBytes": False, 47 | "returnRawGrokInXaiRequest": False, 48 | "enableImageStreaming": True, 49 | "imageGenerationCount": 2, 50 | "forceConcise": False, 51 | "toolOverrides": {}, 52 | "enableSideBySide": True, 53 | "isPreset": False, 54 | "sendFinalMetadata": True, 55 | "customInstructions": "", 56 | "deepsearchPreset": "", 57 | "isReasoning": False 58 | } 59 | 60 | def send_message(self, message): 61 | """ 62 | Send a message to Grok and collect the streaming response 63 | 64 | Args: 65 | message (str): The user's input message 66 | 67 | Returns: 68 | str: The complete response from Grok 69 | """ 70 | payload = self._prepare_payload(message) 71 | response = requests.post( 72 | self.base_url, 73 | headers=self.headers, 74 | cookies=self.cookies, 75 | json=payload, 76 | stream=True 77 | ) 78 | 79 | full_response = "" 80 | 81 | for line in response.iter_lines(): 82 | if line: 83 | decoded_line = line.decode('utf-8') 84 | try: 85 | json_data = json.loads(decoded_line) 86 | result = json_data.get("result", {}) 87 | response_data = result.get("response", {}) 88 | 89 | if "modelResponse" in response_data: 90 | return response_data["modelResponse"]["message"] 91 | 92 | token = response_data.get("token", "") 93 | if token: 94 | full_response += token 95 | 96 | except json.JSONDecodeError: 97 | continue 98 | 99 | return full_response.strip() -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "grokapi" 7 | version = "0.1.0" 8 | authors = [ 9 | { name="Mem0 Team", email="taranjeet@mem0.ai" }, 10 | ] 11 | description = "A Python client for the Grok API" 12 | readme = "README.md" 13 | requires-python = ">=3.8" 14 | classifiers = [ 15 | "Programming Language :: Python :: 3", 16 | "License :: OSI Approved :: MIT License", 17 | "Operating System :: OS Independent", 18 | ] 19 | dependencies = [ 20 | "requests>=2.28.0", 21 | ] 22 | license = {file = "LICENSE"} 23 | 24 | [project.urls] 25 | "Homepage" = "https://github.com/mem0ai/grok3-api" 26 | "Bug Tracker" = "https://github.com/mem0ai/grok3-api/issues" -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | license = MIT 3 | license_files = LICENSE 4 | 5 | [options] 6 | package_dir = 7 | = . 8 | packages = find: 9 | install_requires = 10 | requests>=2.28.0 11 | 12 | [options.packages.find] 13 | where = . --------------------------------------------------------------------------------