Matt300209 commited on
Commit
33477e4
·
verified ·
1 Parent(s): f5d01e5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. venv/lib/python3.10/site-packages/fastapi_cli/__init__.py +1 -0
  2. venv/lib/python3.10/site-packages/fastapi_cli/__main__.py +3 -0
  3. venv/lib/python3.10/site-packages/fastapi_cli/cli.py +358 -0
  4. venv/lib/python3.10/site-packages/fastapi_cli/discover.py +132 -0
  5. venv/lib/python3.10/site-packages/fastapi_cli/utils/__init__.py +0 -0
  6. venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/cli.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/fastapi_cli/utils/cli.py +76 -0
  9. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/INSTALLER +1 -0
  10. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/METADATA +68 -0
  11. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/RECORD +45 -0
  12. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/WHEEL +4 -0
  13. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt +4 -0
  14. venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE +21 -0
  15. venv/lib/python3.10/site-packages/mistral_common/__pycache__/__init__.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/mistral_common/__pycache__/audio.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/mistral_common/__pycache__/base.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/mistral_common/__pycache__/exceptions.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/mistral_common/__pycache__/image.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/mistral_common/__pycache__/multimodal.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/mistral_common/experimental/__init__.py +0 -0
  22. venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/__init__.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/think.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/tools.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/utils.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/mistral_common/experimental/app/__init__.py +0 -0
  27. venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/__init__.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/main.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/models.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/routers.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/mistral_common/experimental/app/main.py +137 -0
  32. venv/lib/python3.10/site-packages/mistral_common/experimental/app/models.py +126 -0
  33. venv/lib/python3.10/site-packages/mistral_common/experimental/app/routers.py +203 -0
  34. venv/lib/python3.10/site-packages/mistral_common/experimental/think.py +47 -0
  35. venv/lib/python3.10/site-packages/mistral_common/experimental/tools.py +160 -0
  36. venv/lib/python3.10/site-packages/mistral_common/experimental/utils.py +48 -0
  37. venv/lib/python3.10/site-packages/mistral_common/image.py +100 -0
  38. venv/lib/python3.10/site-packages/mistral_common/multimodal.py +3 -0
  39. venv/lib/python3.10/site-packages/mistral_common/protocol/__init__.py +0 -0
  40. venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/__init__.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/base.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/utils.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/mistral_common/protocol/base.py +42 -0
  44. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__init__.py +0 -0
  45. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/__init__.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/request.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/response.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/request.py +24 -0
  49. venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/response.py +56 -0
  50. venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__init__.py +0 -0
venv/lib/python3.10/site-packages/fastapi_cli/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.0.8"
venv/lib/python3.10/site-packages/fastapi_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cli import main
2
+
3
+ main()
venv/lib/python3.10/site-packages/fastapi_cli/cli.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import Any, List, Union
4
+
5
+ import typer
6
+ from rich import print
7
+ from rich.tree import Tree
8
+ from typing_extensions import Annotated
9
+
10
+ from fastapi_cli.discover import get_import_data
11
+ from fastapi_cli.exceptions import FastAPICLIException
12
+
13
+ from . import __version__
14
+ from .logging import setup_logging
15
+ from .utils.cli import get_rich_toolkit, get_uvicorn_log_config
16
+
17
+ app = typer.Typer(rich_markup_mode="rich")
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ try:
23
+ import uvicorn
24
+ except ImportError: # pragma: no cover
25
+ uvicorn = None # type: ignore[assignment]
26
+
27
+
28
+ try:
29
+ from fastapi_cloud_cli.cli import (
30
+ app as fastapi_cloud_cli,
31
+ )
32
+
33
+ app.add_typer(fastapi_cloud_cli)
34
+ except ImportError: # pragma: no cover
35
+ pass
36
+
37
+
38
+ def version_callback(value: bool) -> None:
39
+ if value:
40
+ print(f"FastAPI CLI version: [green]{__version__}[/green]")
41
+ raise typer.Exit()
42
+
43
+
44
+ @app.callback()
45
+ def callback(
46
+ version: Annotated[
47
+ Union[bool, None],
48
+ typer.Option(
49
+ "--version", help="Show the version and exit.", callback=version_callback
50
+ ),
51
+ ] = None,
52
+ verbose: bool = typer.Option(False, help="Enable verbose output"),
53
+ ) -> None:
54
+ """
55
+ FastAPI CLI - The [bold]fastapi[/bold] command line app. 😎
56
+
57
+ Manage your [bold]FastAPI[/bold] projects, run your FastAPI apps, and more.
58
+
59
+ Read more in the docs: [link=https://fastapi.tiangolo.com/fastapi-cli/]https://fastapi.tiangolo.com/fastapi-cli/[/link].
60
+ """
61
+
62
+ log_level = logging.DEBUG if verbose else logging.INFO
63
+
64
+ setup_logging(level=log_level)
65
+
66
+
67
+ def _get_module_tree(module_paths: List[Path]) -> Tree:
68
+ root = module_paths[0]
69
+ name = f"🐍 {root.name}" if root.is_file() else f"📁 {root.name}"
70
+
71
+ root_tree = Tree(name)
72
+
73
+ if root.is_dir():
74
+ root_tree.add("[dim]🐍 __init__.py[/dim]")
75
+
76
+ tree = root_tree
77
+ for sub_path in module_paths[1:]:
78
+ sub_name = (
79
+ f"🐍 {sub_path.name}" if sub_path.is_file() else f"📁 {sub_path.name}"
80
+ )
81
+ tree = tree.add(sub_name)
82
+ if sub_path.is_dir():
83
+ tree.add("[dim]🐍 __init__.py[/dim]")
84
+
85
+ return root_tree
86
+
87
+
88
+ def _run(
89
+ path: Union[Path, None] = None,
90
+ *,
91
+ host: str = "127.0.0.1",
92
+ port: int = 8000,
93
+ reload: bool = True,
94
+ workers: Union[int, None] = None,
95
+ root_path: str = "",
96
+ command: str,
97
+ app: Union[str, None] = None,
98
+ proxy_headers: bool = False,
99
+ ) -> None:
100
+ with get_rich_toolkit() as toolkit:
101
+ server_type = "development" if command == "dev" else "production"
102
+
103
+ toolkit.print_title(f"Starting {server_type} server 🚀", tag="FastAPI")
104
+ toolkit.print_line()
105
+
106
+ toolkit.print(
107
+ "Searching for package file structure from directories with [blue]__init__.py[/blue] files"
108
+ )
109
+
110
+ try:
111
+ import_data = get_import_data(path=path, app_name=app)
112
+ except FastAPICLIException as e:
113
+ toolkit.print_line()
114
+ toolkit.print(f"[error]{e}")
115
+ raise typer.Exit(code=1) from None
116
+
117
+ logger.debug(f"Importing from {import_data.module_data.extra_sys_path}")
118
+ logger.debug(f"Importing module {import_data.module_data.module_import_str}")
119
+
120
+ module_data = import_data.module_data
121
+ import_string = import_data.import_string
122
+
123
+ toolkit.print(f"Importing from {module_data.extra_sys_path}")
124
+ toolkit.print_line()
125
+
126
+ root_tree = _get_module_tree(module_data.module_paths)
127
+
128
+ toolkit.print(root_tree, tag="module")
129
+ toolkit.print_line()
130
+
131
+ toolkit.print(
132
+ "Importing the FastAPI app object from the module with the following code:",
133
+ tag="code",
134
+ )
135
+ toolkit.print_line()
136
+ toolkit.print(
137
+ f"[underline]from [bold]{module_data.module_import_str}[/bold] import [bold]{import_data.app_name}[/bold]"
138
+ )
139
+ toolkit.print_line()
140
+
141
+ toolkit.print(
142
+ f"Using import string: [blue]{import_string}[/]",
143
+ tag="app",
144
+ )
145
+
146
+ url = f"http://{host}:{port}"
147
+ url_docs = f"{url}/docs"
148
+
149
+ toolkit.print_line()
150
+ toolkit.print(
151
+ f"Server started at [link={url}]{url}[/]",
152
+ f"Documentation at [link={url_docs}]{url_docs}[/]",
153
+ tag="server",
154
+ )
155
+
156
+ if command == "dev":
157
+ toolkit.print_line()
158
+ toolkit.print(
159
+ "Running in development mode, for production use: [bold]fastapi run[/]",
160
+ tag="tip",
161
+ )
162
+
163
+ if not uvicorn:
164
+ raise FastAPICLIException(
165
+ "Could not import Uvicorn, try running 'pip install uvicorn'"
166
+ ) from None
167
+
168
+ toolkit.print_line()
169
+ toolkit.print("Logs:")
170
+ toolkit.print_line()
171
+
172
+ uvicorn.run(
173
+ app=import_string,
174
+ host=host,
175
+ port=port,
176
+ reload=reload,
177
+ workers=workers,
178
+ root_path=root_path,
179
+ proxy_headers=proxy_headers,
180
+ log_config=get_uvicorn_log_config(),
181
+ )
182
+
183
+
184
+ @app.command()
185
+ def dev(
186
+ path: Annotated[
187
+ Union[Path, None],
188
+ typer.Argument(
189
+ help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried."
190
+ ),
191
+ ] = None,
192
+ *,
193
+ host: Annotated[
194
+ str,
195
+ typer.Option(
196
+ help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]."
197
+ ),
198
+ ] = "127.0.0.1",
199
+ port: Annotated[
200
+ int,
201
+ typer.Option(
202
+ help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app."
203
+ ),
204
+ ] = 8000,
205
+ reload: Annotated[
206
+ bool,
207
+ typer.Option(
208
+ help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development."
209
+ ),
210
+ ] = True,
211
+ root_path: Annotated[
212
+ str,
213
+ typer.Option(
214
+ help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar."
215
+ ),
216
+ ] = "",
217
+ app: Annotated[
218
+ Union[str, None],
219
+ typer.Option(
220
+ help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically."
221
+ ),
222
+ ] = None,
223
+ proxy_headers: Annotated[
224
+ bool,
225
+ typer.Option(
226
+ help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info."
227
+ ),
228
+ ] = True,
229
+ ) -> Any:
230
+ """
231
+ Run a [bold]FastAPI[/bold] app in [yellow]development[/yellow] mode. 🧪
232
+
233
+ This is equivalent to [bold]fastapi run[/bold] but with [bold]reload[/bold] enabled and listening on the [blue]127.0.0.1[/blue] address.
234
+
235
+ It automatically detects the Python module or package that needs to be imported based on the file or directory path passed.
236
+
237
+ If no path is passed, it tries with:
238
+
239
+ - [blue]main.py[/blue]
240
+ - [blue]app.py[/blue]
241
+ - [blue]api.py[/blue]
242
+ - [blue]app/main.py[/blue]
243
+ - [blue]app/app.py[/blue]
244
+ - [blue]app/api.py[/blue]
245
+
246
+ It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it.
247
+
248
+ It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named:
249
+
250
+ - [blue]app[/blue]
251
+ - [blue]api[/blue]
252
+
253
+ Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package.
254
+ """
255
+ _run(
256
+ path=path,
257
+ host=host,
258
+ port=port,
259
+ reload=reload,
260
+ root_path=root_path,
261
+ app=app,
262
+ command="dev",
263
+ proxy_headers=proxy_headers,
264
+ )
265
+
266
+
267
+ @app.command()
268
+ def run(
269
+ path: Annotated[
270
+ Union[Path, None],
271
+ typer.Argument(
272
+ help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried."
273
+ ),
274
+ ] = None,
275
+ *,
276
+ host: Annotated[
277
+ str,
278
+ typer.Option(
279
+ help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]."
280
+ ),
281
+ ] = "0.0.0.0",
282
+ port: Annotated[
283
+ int,
284
+ typer.Option(
285
+ help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app."
286
+ ),
287
+ ] = 8000,
288
+ reload: Annotated[
289
+ bool,
290
+ typer.Option(
291
+ help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development."
292
+ ),
293
+ ] = False,
294
+ workers: Annotated[
295
+ Union[int, None],
296
+ typer.Option(
297
+ help="Use multiple worker processes. Mutually exclusive with the --reload flag."
298
+ ),
299
+ ] = None,
300
+ root_path: Annotated[
301
+ str,
302
+ typer.Option(
303
+ help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar."
304
+ ),
305
+ ] = "",
306
+ app: Annotated[
307
+ Union[str, None],
308
+ typer.Option(
309
+ help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically."
310
+ ),
311
+ ] = None,
312
+ proxy_headers: Annotated[
313
+ bool,
314
+ typer.Option(
315
+ help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info."
316
+ ),
317
+ ] = True,
318
+ ) -> Any:
319
+ """
320
+ Run a [bold]FastAPI[/bold] app in [green]production[/green] mode. 🚀
321
+
322
+ This is equivalent to [bold]fastapi dev[/bold] but with [bold]reload[/bold] disabled and listening on the [blue]0.0.0.0[/blue] address.
323
+
324
+ It automatically detects the Python module or package that needs to be imported based on the file or directory path passed.
325
+
326
+ If no path is passed, it tries with:
327
+
328
+ - [blue]main.py[/blue]
329
+ - [blue]app.py[/blue]
330
+ - [blue]api.py[/blue]
331
+ - [blue]app/main.py[/blue]
332
+ - [blue]app/app.py[/blue]
333
+ - [blue]app/api.py[/blue]
334
+
335
+ It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it.
336
+
337
+ It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named:
338
+
339
+ - [blue]app[/blue]
340
+ - [blue]api[/blue]
341
+
342
+ Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package.
343
+ """
344
+ _run(
345
+ path=path,
346
+ host=host,
347
+ port=port,
348
+ reload=reload,
349
+ workers=workers,
350
+ root_path=root_path,
351
+ app=app,
352
+ command="run",
353
+ proxy_headers=proxy_headers,
354
+ )
355
+
356
+
357
+ def main() -> None:
358
+ app()
venv/lib/python3.10/site-packages/fastapi_cli/discover.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import sys
3
+ from dataclasses import dataclass
4
+ from logging import getLogger
5
+ from pathlib import Path
6
+ from typing import List, Union
7
+
8
+ from fastapi_cli.exceptions import FastAPICLIException
9
+
10
+ logger = getLogger(__name__)
11
+
12
+ try:
13
+ from fastapi import FastAPI
14
+ except ImportError: # pragma: no cover
15
+ FastAPI = None # type: ignore[misc, assignment]
16
+
17
+
18
+ def get_default_path() -> Path:
19
+ potential_paths = (
20
+ "main.py",
21
+ "app.py",
22
+ "api.py",
23
+ "app/main.py",
24
+ "app/app.py",
25
+ "app/api.py",
26
+ )
27
+
28
+ for full_path in potential_paths:
29
+ path = Path(full_path)
30
+ if path.is_file():
31
+ return path
32
+
33
+ raise FastAPICLIException(
34
+ "Could not find a default file to run, please provide an explicit path"
35
+ )
36
+
37
+
38
+ @dataclass
39
+ class ModuleData:
40
+ module_import_str: str
41
+ extra_sys_path: Path
42
+ module_paths: List[Path]
43
+
44
+
45
+ def get_module_data_from_path(path: Path) -> ModuleData:
46
+ use_path = path.resolve()
47
+ module_path = use_path
48
+ if use_path.is_file() and use_path.stem == "__init__":
49
+ module_path = use_path.parent
50
+ module_paths = [module_path]
51
+ extra_sys_path = module_path.parent
52
+ for parent in module_path.parents:
53
+ init_path = parent / "__init__.py"
54
+ if init_path.is_file():
55
+ module_paths.insert(0, parent)
56
+ extra_sys_path = parent.parent
57
+ else:
58
+ break
59
+
60
+ module_str = ".".join(p.stem for p in module_paths)
61
+ return ModuleData(
62
+ module_import_str=module_str,
63
+ extra_sys_path=extra_sys_path.resolve(),
64
+ module_paths=module_paths,
65
+ )
66
+
67
+
68
+ def get_app_name(*, mod_data: ModuleData, app_name: Union[str, None] = None) -> str:
69
+ try:
70
+ mod = importlib.import_module(mod_data.module_import_str)
71
+ except (ImportError, ValueError) as e:
72
+ logger.error(f"Import error: {e}")
73
+ logger.warning(
74
+ "Ensure all the package directories have an [blue]__init__.py[/blue] file"
75
+ )
76
+ raise
77
+ if not FastAPI: # type: ignore[truthy-function]
78
+ raise FastAPICLIException(
79
+ "Could not import FastAPI, try running 'pip install fastapi'"
80
+ ) from None
81
+ object_names = dir(mod)
82
+ object_names_set = set(object_names)
83
+ if app_name:
84
+ if app_name not in object_names_set:
85
+ raise FastAPICLIException(
86
+ f"Could not find app name {app_name} in {mod_data.module_import_str}"
87
+ )
88
+ app = getattr(mod, app_name)
89
+ if not isinstance(app, FastAPI):
90
+ raise FastAPICLIException(
91
+ f"The app name {app_name} in {mod_data.module_import_str} doesn't seem to be a FastAPI app"
92
+ )
93
+ return app_name
94
+ for preferred_name in ["app", "api"]:
95
+ if preferred_name in object_names_set:
96
+ obj = getattr(mod, preferred_name)
97
+ if isinstance(obj, FastAPI):
98
+ return preferred_name
99
+ for name in object_names:
100
+ obj = getattr(mod, name)
101
+ if isinstance(obj, FastAPI):
102
+ return name
103
+ raise FastAPICLIException("Could not find FastAPI app in module, try using --app")
104
+
105
+
106
+ @dataclass
107
+ class ImportData:
108
+ app_name: str
109
+ module_data: ModuleData
110
+ import_string: str
111
+
112
+
113
+ def get_import_data(
114
+ *, path: Union[Path, None] = None, app_name: Union[str, None] = None
115
+ ) -> ImportData:
116
+ if not path:
117
+ path = get_default_path()
118
+
119
+ logger.debug(f"Using path [blue]{path}[/blue]")
120
+ logger.debug(f"Resolved absolute path {path.resolve()}")
121
+
122
+ if not path.exists():
123
+ raise FastAPICLIException(f"Path does not exist {path}")
124
+ mod_data = get_module_data_from_path(path)
125
+ sys.path.insert(0, str(mod_data.extra_sys_path))
126
+ use_app_name = get_app_name(mod_data=mod_data, app_name=app_name)
127
+
128
+ import_string = f"{mod_data.module_import_str}:{use_app_name}"
129
+
130
+ return ImportData(
131
+ app_name=use_app_name, module_data=mod_data, import_string=import_string
132
+ )
venv/lib/python3.10/site-packages/fastapi_cli/utils/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (253 Bytes). View file
 
venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/cli.cpython-310.pyc ADDED
Binary file (2.32 kB). View file
 
venv/lib/python3.10/site-packages/fastapi_cli/utils/cli.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Dict
3
+
4
+ from rich_toolkit import RichToolkit, RichToolkitTheme
5
+ from rich_toolkit.styles import TaggedStyle
6
+ from uvicorn.logging import DefaultFormatter
7
+
8
+
9
+ class CustomFormatter(DefaultFormatter):
10
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
11
+ super().__init__(*args, **kwargs)
12
+ self.toolkit = get_rich_toolkit()
13
+
14
+ def formatMessage(self, record: logging.LogRecord) -> str:
15
+ return self.toolkit.print_as_string(record.getMessage(), tag=record.levelname)
16
+
17
+
18
+ def get_uvicorn_log_config() -> Dict[str, Any]:
19
+ return {
20
+ "version": 1,
21
+ "disable_existing_loggers": False,
22
+ "formatters": {
23
+ "default": {
24
+ "()": CustomFormatter,
25
+ "fmt": "%(levelprefix)s %(message)s",
26
+ "use_colors": None,
27
+ },
28
+ "access": {
29
+ "()": CustomFormatter,
30
+ "fmt": "%(levelprefix)s %(client_addr)s - '%(request_line)s' %(status_code)s",
31
+ },
32
+ },
33
+ "handlers": {
34
+ "default": {
35
+ "formatter": "default",
36
+ "class": "logging.StreamHandler",
37
+ "stream": "ext://sys.stderr",
38
+ },
39
+ "access": {
40
+ "formatter": "access",
41
+ "class": "logging.StreamHandler",
42
+ "stream": "ext://sys.stdout",
43
+ },
44
+ },
45
+ "loggers": {
46
+ "uvicorn": {"handlers": ["default"], "level": "INFO"},
47
+ "uvicorn.error": {"level": "INFO"},
48
+ "uvicorn.access": {
49
+ "handlers": ["access"],
50
+ "level": "INFO",
51
+ "propagate": False,
52
+ },
53
+ },
54
+ }
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ def get_rich_toolkit() -> RichToolkit:
61
+ theme = RichToolkitTheme(
62
+ style=TaggedStyle(tag_width=11),
63
+ theme={
64
+ "tag.title": "white on #009485",
65
+ "tag": "white on #007166",
66
+ "placeholder": "grey85",
67
+ "text": "white",
68
+ "selected": "#007166",
69
+ "result": "grey85",
70
+ "progress": "on #007166",
71
+ "error": "red",
72
+ "log.info": "black on blue",
73
+ },
74
+ )
75
+
76
+ return RichToolkit(theme=theme)
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/METADATA ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: fastapi-cloud-cli
3
+ Version: 0.1.5
4
+ Summary: Deploy and manage FastAPI Cloud apps from the command line 🚀
5
+ Author-Email: Patrick Arminio <patrick@fastapilabs.com>
6
+ License: MIT
7
+ Classifier: Intended Audience :: Information Technology
8
+ Classifier: Intended Audience :: System Administrators
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Topic :: Software Development
16
+ Classifier: Typing :: Typed
17
+ Classifier: Development Status :: 4 - Beta
18
+ Classifier: Framework :: FastAPI
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: License :: OSI Approved :: MIT License
29
+ Project-URL: Homepage, https://github.com/fastapilabs/fastapi-cloud-cli
30
+ Project-URL: Documentation, https://fastapi.tiangolo.com/fastapi-cloud-cli/
31
+ Project-URL: Repository, https://github.com/fastapilabs/fastapi-cloud-cli
32
+ Project-URL: Issues, https://github.com/fastapilabs/fastapi-cloud-cli/issues
33
+ Project-URL: Changelog, https://github.com/fastapilabs/fastapi-cloud-cli/blob/main/release-notes.md
34
+ Requires-Python: >=3.8
35
+ Requires-Dist: typer>=0.12.3
36
+ Requires-Dist: uvicorn[standard]>=0.15.0
37
+ Requires-Dist: rignore>=0.5.1
38
+ Requires-Dist: httpx>=0.27.0
39
+ Requires-Dist: rich-toolkit>=0.14.5
40
+ Requires-Dist: pydantic[email]>=1.6.1
41
+ Requires-Dist: sentry-sdk>=2.20.0
42
+ Provides-Extra: standard
43
+ Requires-Dist: uvicorn[standard]>=0.15.0; extra == "standard"
44
+ Description-Content-Type: text/markdown
45
+
46
+ # FastAPI Cloud CLI
47
+
48
+ <a href="https://github.com/fastapilabs/fastapi-cloud-cli/actions/workflows/test.yml" target="_blank">
49
+ <img src="https://github.com/fastapilabs/fastapi-cloud-cli/actions/workflows/test.yml/badge.svg" alt="Test">
50
+ </a>
51
+ <a href="https://github.com/fastapilabs/fastapi-cloud-cli/actions/workflows/publish.yml" target="_blank">
52
+ <img src="https://github.com/fastapilabs/fastapi-cloud-cli/actions/workflows/publish.yml/badge.svg" alt="Publish">
53
+ </a>
54
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapilabs/fastapi-cloud-cli" target="_blank">
55
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapilabs/fastapi-cloud-cli.svg" alt="Coverage">
56
+ <a href="https://pypi.org/project/fastapi-cloud-cli" target="_blank">
57
+ <img src="https://img.shields.io/pypi/v/fastapi-cloud-cli?color=%2334D058&label=pypi%20package" alt="Package version">
58
+ </a>
59
+
60
+ ---
61
+
62
+ **Source Code**: <a href="https://github.com/fastapilabs/fastapi-cloud-cli" target="_blank">https://github.com/fastapilabs/fastapi-cloud-cli</a>
63
+
64
+ ---
65
+
66
+ ## License
67
+
68
+ This project is licensed under the terms of the MIT license.
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/RECORD ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi_cloud_cli-0.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ fastapi_cloud_cli-0.1.5.dist-info/METADATA,sha256=hy3DjoOv-y01dnY4o3ECBiL7ymffxOqe-l_QCMGtgx0,3227
3
+ fastapi_cloud_cli-0.1.5.dist-info/RECORD,,
4
+ fastapi_cloud_cli-0.1.5.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
5
+ fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
6
+ fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE,sha256=FqD5B4VbXJnefprQseE0U8llL6FxojC-i8muZy7YmSU,1086
7
+ fastapi_cloud_cli/__init__.py,sha256=rPSfWgIeq2YWVPyESOAwCBt8vftsTpIkuLAGDEzyRQc,22
8
+ fastapi_cloud_cli/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
9
+ fastapi_cloud_cli/__pycache__/__init__.cpython-310.pyc,,
10
+ fastapi_cloud_cli/__pycache__/__main__.cpython-310.pyc,,
11
+ fastapi_cloud_cli/__pycache__/cli.cpython-310.pyc,,
12
+ fastapi_cloud_cli/__pycache__/config.cpython-310.pyc,,
13
+ fastapi_cloud_cli/__pycache__/logging.cpython-310.pyc,,
14
+ fastapi_cloud_cli/cli.py,sha256=qZjMCm3455tgX8HSLM84LFKSPQgVztF6MPzYcgXSmnY,552
15
+ fastapi_cloud_cli/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ fastapi_cloud_cli/commands/__pycache__/__init__.cpython-310.pyc,,
17
+ fastapi_cloud_cli/commands/__pycache__/deploy.cpython-310.pyc,,
18
+ fastapi_cloud_cli/commands/__pycache__/env.cpython-310.pyc,,
19
+ fastapi_cloud_cli/commands/__pycache__/login.cpython-310.pyc,,
20
+ fastapi_cloud_cli/commands/__pycache__/logout.cpython-310.pyc,,
21
+ fastapi_cloud_cli/commands/__pycache__/whoami.cpython-310.pyc,,
22
+ fastapi_cloud_cli/commands/deploy.py,sha256=m1k2TB4d7zoLlpB2mpgBg-hFMmNJmg9HsyHWxghjLqM,19272
23
+ fastapi_cloud_cli/commands/env.py,sha256=34wCmz0OCDk_r8CSX3xRs1pO3KtUGY_Ge4GTC6PaUxA,7127
24
+ fastapi_cloud_cli/commands/login.py,sha256=EgN7wW8qrQnAxLYIoS-kCzUMRVAMiXRqpFpSj_9wmCU,2822
25
+ fastapi_cloud_cli/commands/logout.py,sha256=XpZ4RBzJP8PZVoa6RXgy6hq2_KGsDiAfabxJXLOD3es,329
26
+ fastapi_cloud_cli/commands/whoami.py,sha256=6R9c2GAwmCV7fF1KE85tLMzLiuL7dB4y0iIzZLCa4YA,802
27
+ fastapi_cloud_cli/config.py,sha256=Stme6dH1zwk0LH80x4OKUrBH-DjSAaCoY9_zlgcyH6U,686
28
+ fastapi_cloud_cli/logging.py,sha256=GOlwUO9mi0EcSwgnBZTEA-v9_MjKVmVHlNlIKkorHQU,858
29
+ fastapi_cloud_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
30
+ fastapi_cloud_cli/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
+ fastapi_cloud_cli/utils/__pycache__/__init__.cpython-310.pyc,,
32
+ fastapi_cloud_cli/utils/__pycache__/api.cpython-310.pyc,,
33
+ fastapi_cloud_cli/utils/__pycache__/apps.cpython-310.pyc,,
34
+ fastapi_cloud_cli/utils/__pycache__/auth.cpython-310.pyc,,
35
+ fastapi_cloud_cli/utils/__pycache__/cli.cpython-310.pyc,,
36
+ fastapi_cloud_cli/utils/__pycache__/config.cpython-310.pyc,,
37
+ fastapi_cloud_cli/utils/__pycache__/env.cpython-310.pyc,,
38
+ fastapi_cloud_cli/utils/__pycache__/sentry.cpython-310.pyc,,
39
+ fastapi_cloud_cli/utils/api.py,sha256=NWbWvf_rKP-zXkAdpmO9dd7J3u0vHzTapNTMnv4zIto,566
40
+ fastapi_cloud_cli/utils/apps.py,sha256=LbTwRO4zWTBNFB9aiB7nL-v4jkQ1Xh6jP2w4ZpX-lT8,1890
41
+ fastapi_cloud_cli/utils/auth.py,sha256=zpi2h7eMWKzZErXq9zeAd8kZ1mDXsiS0RBr2Z9IWV9s,1613
42
+ fastapi_cloud_cli/utils/cli.py,sha256=IdYlbGRq79DtqHVMldC_f9vvc2Sg76PiUpbeGXWtuoQ,2861
43
+ fastapi_cloud_cli/utils/config.py,sha256=ebwN1RN8NJ3oIcBUyxF48Al0P4zvBnSMMoy779yMBHU,465
44
+ fastapi_cloud_cli/utils/env.py,sha256=a9S6ehNGxhKbQHXxFVJtjqMEkodKwKa0wOvRVh9VBjw,125
45
+ fastapi_cloud_cli/utils/sentry.py,sha256=Vrr4u3O3XvLrOVUUI34JXkEW3jfQEJkDpf274h9KVoE,489
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [console_scripts]
2
+
3
+ [gui_scripts]
4
+
venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Sebastián Ramírez
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
13
+ all 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
21
+ THE SOFTWARE.
venv/lib/python3.10/site-packages/mistral_common/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (353 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/__pycache__/audio.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/__pycache__/base.cpython-310.pyc ADDED
Binary file (699 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (6.17 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/__pycache__/image.cpython-310.pyc ADDED
Binary file (3.2 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/__pycache__/multimodal.cpython-310.pyc ADDED
Binary file (289 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (263 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/think.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/tools.cpython-310.pyc ADDED
Binary file (5.71 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/app/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (267 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/main.cpython-310.pyc ADDED
Binary file (3.63 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/models.cpython-310.pyc ADDED
Binary file (5.29 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/routers.cpython-310.pyc ADDED
Binary file (6.22 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/experimental/app/main.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from pathlib import Path
3
+ from typing import Union
4
+
5
+ import click
6
+ import uvicorn
7
+ from fastapi import FastAPI
8
+
9
+ from mistral_common.experimental.app.models import (
10
+ EngineBackend,
11
+ Settings,
12
+ get_settings,
13
+ )
14
+ from mistral_common.experimental.app.routers import (
15
+ decode_router,
16
+ main_router,
17
+ tokenize_router,
18
+ )
19
+ from mistral_common.protocol.instruct.validator import ValidationMode
20
+ from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
21
+
22
+
23
+ def create_app(
24
+ tokenizer: Union[str, Path, MistralTokenizer],
25
+ validation_mode: ValidationMode = ValidationMode.test,
26
+ engine_url: str = "127.0.0.1",
27
+ engine_backend: EngineBackend = EngineBackend.llama_cpp,
28
+ timeout: int = 60,
29
+ ) -> FastAPI:
30
+ r"""Create a Mistral-common FastAPI app with the given tokenizer and validation mode.
31
+
32
+ Args:
33
+ tokenizer: The tokenizer path or a MistralTokenizer instance.
34
+ validation_mode: The validation mode to use.
35
+ engine_url: The URL of the engine API.
36
+ timeout: The timeout of the engine API.
37
+
38
+ Returns:
39
+ The Mistral-common FastAPI app.
40
+ """
41
+ if not isinstance(tokenizer, (MistralTokenizer, str, Path)):
42
+ raise ValueError("Tokenizer must be a path or a MistralTokenizer instance.")
43
+
44
+ app = FastAPI()
45
+ app.include_router(tokenize_router)
46
+ app.include_router(decode_router)
47
+ app.include_router(main_router)
48
+
49
+ @lru_cache
50
+ def get_settings_override() -> Settings:
51
+ settings = Settings(
52
+ engine_url=engine_url,
53
+ engine_backend=engine_backend,
54
+ timeout=timeout,
55
+ )
56
+ if isinstance(tokenizer, MistralTokenizer):
57
+ settings.tokenizer = tokenizer
58
+ else:
59
+ settings._load_tokenizer(tokenizer, validation_mode)
60
+ return settings
61
+
62
+ get_settings_override()
63
+ app.dependency_overrides[get_settings] = get_settings_override
64
+
65
+ return app
66
+
67
+
68
+ @click.group()
69
+ def cli() -> None:
70
+ r"""Mistral-common CLI."""
71
+ pass
72
+
73
+
74
+ @cli.command(name="serve", context_settings={"auto_envvar_prefix": "UVICORN"})
75
+ @click.argument("tokenizer_path", type=str)
76
+ @click.argument(
77
+ "validation_mode",
78
+ type=click.Choice([mode.value for mode in ValidationMode], case_sensitive=False),
79
+ default=ValidationMode.test.value,
80
+ )
81
+ @click.option(
82
+ "--host",
83
+ type=str,
84
+ default="127.0.0.1",
85
+ help="Mistral-common API host",
86
+ show_default=True,
87
+ )
88
+ @click.option(
89
+ "--port",
90
+ type=int,
91
+ default=0,
92
+ help="Mistral-common API port",
93
+ show_default=True,
94
+ )
95
+ @click.option(
96
+ "--engine-url",
97
+ type=str,
98
+ default="http://127.0.0.1:8080",
99
+ help="Enginge URL",
100
+ show_default=True,
101
+ )
102
+ @click.option(
103
+ "--engine-backend",
104
+ type=click.Choice([mode.value for mode in EngineBackend], case_sensitive=False),
105
+ default=EngineBackend.llama_cpp.value,
106
+ help="Engine API backend",
107
+ show_default=True,
108
+ )
109
+ @click.option(
110
+ "--timeout",
111
+ type=int,
112
+ default=60,
113
+ help="Timeout",
114
+ show_default=True,
115
+ )
116
+ def serve(
117
+ tokenizer_path: Union[str, Path],
118
+ validation_mode: Union[ValidationMode, str] = ValidationMode.test,
119
+ host: str = "127.0.0.1",
120
+ port: int = 0,
121
+ engine_url: str = "http://127.0.0.1:8080",
122
+ engine_backend: str = EngineBackend.llama_cpp.value,
123
+ timeout: int = 60,
124
+ ) -> None:
125
+ r"""Serve the Mistral-common API with the given tokenizer path and validation mode."""
126
+ app = create_app(
127
+ tokenizer=tokenizer_path,
128
+ validation_mode=ValidationMode(validation_mode),
129
+ engine_url=engine_url,
130
+ engine_backend=EngineBackend(engine_backend),
131
+ timeout=timeout,
132
+ )
133
+ uvicorn.run(app, host=host, port=port)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ cli()
venv/lib/python3.10/site-packages/mistral_common/experimental/app/models.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ from enum import Enum
3
+ from pathlib import Path
4
+ from typing import Any, List, Optional, Union
5
+
6
+ from pydantic import BaseModel, ConfigDict, field_validator
7
+ from pydantic_settings import BaseSettings
8
+
9
+ from mistral_common.protocol.instruct.validator import ValidationMode
10
+ from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
11
+
12
+
13
+ class OpenAIChatCompletionRequest(BaseModel):
14
+ r"""OpenAI chat completion request.
15
+
16
+ This class is used to parse the request body for the OpenAI chat completion endpoint.
17
+
18
+ Attributes:
19
+ messages: The messages to use for the chat completion.
20
+ tools: The tools to use for the chat completion.
21
+
22
+ Note:
23
+ This class accepts extra fields that are not validated.
24
+ """
25
+
26
+ messages: List[dict[str, Union[str, List[dict[str, Union[str, dict[str, Any]]]]]]]
27
+ tools: Optional[List[dict[str, Any]]] = None
28
+
29
+ # Allow extra fields as the `from_openai` method will handle them.
30
+ # We never validate the input, so we don't need to worry about the extra fields.
31
+ model_config = ConfigDict(extra="allow")
32
+
33
+ def drop_extra_fields(self) -> dict[str, Any]:
34
+ r"""Drop extra fields from the model.
35
+
36
+ This method is used to drop extra fields from the model, which are not defined in the model fields.
37
+
38
+ Returns:
39
+ The extra fields that were dropped from the model.
40
+ """
41
+ extra_fields = {
42
+ field: value for field, value in self.model_dump().items() if field not in type(self).model_fields
43
+ }
44
+
45
+ self.__dict__ = {k: v for k, v in self.__dict__.items() if k not in extra_fields}
46
+ return extra_fields
47
+
48
+
49
+ class EngineBackend(str, Enum):
50
+ r"""The engine backend to use.
51
+
52
+ Attributes:
53
+ llama_cpp: The llama.cpp backend.
54
+ """
55
+
56
+ llama_cpp = "llama_cpp"
57
+
58
+
59
+ class Settings(BaseSettings):
60
+ r"""Settings for the Mistral-common API.
61
+
62
+ Attributes:
63
+ app_name: The name of the application.
64
+ app_version: The version of the application.
65
+ engine_url: The URL of the engine.
66
+ engine_backend: The backend to use for the engine.
67
+ timeout: The timeout to use for the engine API.
68
+ """
69
+
70
+ app_name: str = "Mistral-common API"
71
+ app_version: str = importlib.metadata.version("mistral-common")
72
+ engine_url: str = "127.0.0.1"
73
+ engine_backend: EngineBackend = EngineBackend.llama_cpp
74
+ api_key: str = ""
75
+ timeout: int = 60
76
+
77
+ @field_validator("engine_url", mode="before")
78
+ @classmethod
79
+ def _validate_engine_url(cls, value: str) -> str:
80
+ if isinstance(value, str) and value.endswith("/"):
81
+ value = value[:-1]
82
+ return value
83
+
84
+ @field_validator("engine_backend", mode="before")
85
+ @classmethod
86
+ def _validate_backend(cls, value: Union[str, EngineBackend]) -> EngineBackend:
87
+ if isinstance(value, str):
88
+ value = EngineBackend(value)
89
+ return value
90
+
91
+ def model_post_init(self, context: Any) -> None:
92
+ super().model_post_init(context)
93
+ self._tokenizer: Optional[MistralTokenizer] = None
94
+
95
+ def _load_tokenizer(self, tokenizer_path: Union[str, Path], validation_mode: ValidationMode) -> None:
96
+ if tokenizer_path == "":
97
+ raise ValueError("Tokenizer path must be set via the environment variable `TOKENIZER_PATH`.")
98
+ elif self._tokenizer is not None:
99
+ raise ValueError("Tokenizer has already been initialized.")
100
+
101
+ if isinstance(tokenizer_path, str):
102
+ candidate_tokenizer_path = Path(tokenizer_path)
103
+ if candidate_tokenizer_path.exists():
104
+ tokenizer_path = candidate_tokenizer_path
105
+
106
+ if isinstance(tokenizer_path, Path) and tokenizer_path.exists():
107
+ self._tokenizer = MistralTokenizer.from_file(tokenizer_path, mode=validation_mode)
108
+ else:
109
+ self._tokenizer = MistralTokenizer.from_hf_hub(str(tokenizer_path), mode=validation_mode)
110
+
111
+ @property
112
+ def tokenizer(self) -> MistralTokenizer:
113
+ if self._tokenizer is None:
114
+ raise ValueError("Tokenizer not initialized.")
115
+ return self._tokenizer
116
+
117
+ @tokenizer.setter
118
+ def tokenizer(self, value: MistralTokenizer) -> None:
119
+ if not isinstance(value, MistralTokenizer):
120
+ raise ValueError("Tokenizer must be an instance of MistralTokenizer.")
121
+ self._tokenizer = value
122
+
123
+
124
+ def get_settings() -> Settings:
125
+ r"""Get the settings for the Mistral-common API."""
126
+ return Settings()
venv/lib/python3.10/site-packages/mistral_common/experimental/app/routers.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Annotated, List, Optional, Union
3
+
4
+ import requests
5
+ from fastapi import APIRouter, Body, Depends, HTTPException
6
+ from fastapi.responses import RedirectResponse
7
+ from pydantic import ValidationError
8
+
9
+ from mistral_common.experimental.app.models import (
10
+ EngineBackend,
11
+ OpenAIChatCompletionRequest,
12
+ Settings,
13
+ get_settings,
14
+ )
15
+ from mistral_common.experimental.think import _split_content_and_think_chunks
16
+ from mistral_common.experimental.tools import _decode_tool_calls, _split_content_and_tool_calls
17
+ from mistral_common.protocol.instruct.messages import AssistantMessage, TextChunk, ThinkChunk
18
+ from mistral_common.protocol.instruct.request import ChatCompletionRequest
19
+ from mistral_common.tokens.tokenizers.base import SpecialTokenPolicy, Tokenized, TokenizerVersion
20
+ from mistral_common.tokens.tokenizers.instruct import InstructTokenizerV13
21
+
22
+ main_router = APIRouter(tags=["app"])
23
+ tokenize_router = APIRouter(prefix="/v1/tokenize", tags=["tokenizer", "tokenize"])
24
+ decode_router = APIRouter(prefix="/v1/detokenize", tags=["tokenizer", "detokenize"])
25
+
26
+
27
+ @main_router.get("/")
28
+ async def redirect_to_docs() -> RedirectResponse:
29
+ r"""Redirect to the documentation."""
30
+ return RedirectResponse(url="docs")
31
+
32
+
33
+ @tokenize_router.post("/")
34
+ async def tokenize_request(
35
+ request: Union[ChatCompletionRequest, OpenAIChatCompletionRequest],
36
+ settings: Annotated[Settings, Depends(get_settings)],
37
+ ) -> list[int]:
38
+ r"""Tokenize a chat completion request."""
39
+ if isinstance(request, OpenAIChatCompletionRequest):
40
+ try:
41
+ request.drop_extra_fields()
42
+ request = ChatCompletionRequest.from_openai(**request.model_dump())
43
+ except (ValidationError, ValueError) as e:
44
+ raise HTTPException(status_code=400, detail=str(e))
45
+
46
+ if request.messages == []:
47
+ raise HTTPException(status_code=400, detail="Messages list cannot be empty.")
48
+
49
+ tokenized = settings.tokenizer.encode_chat_completion(request)
50
+ assert isinstance(tokenized, Tokenized), type(tokenized)
51
+ return tokenized.tokens
52
+
53
+
54
+ @decode_router.post("/string")
55
+ async def detokenize_to_string(
56
+ settings: Annotated[Settings, Depends(get_settings)],
57
+ tokens: list[int] = Body(default_factory=list),
58
+ special_token_policy: SpecialTokenPolicy = Body(default=SpecialTokenPolicy.IGNORE),
59
+ ) -> str:
60
+ r"""Detokenize a list of tokens to a string.
61
+
62
+ Args:
63
+ tokens: The tokens to detokenize.
64
+ special_token_policy: The policy to use for special tokens.
65
+
66
+ Returns:
67
+ The detokenized string or assistant message.
68
+ """
69
+ if len(tokens) == 0:
70
+ raise HTTPException(status_code=400, detail="Tokens list cannot be empty.")
71
+ try:
72
+ return settings.tokenizer.decode(tokens, special_token_policy=special_token_policy)
73
+ except ValueError as e:
74
+ raise HTTPException(status_code=400, detail=str(e))
75
+
76
+
77
+ @decode_router.post("/")
78
+ async def detokenize_to_assistant_message(
79
+ settings: Annotated[Settings, Depends(get_settings)],
80
+ tokens: list[int] = Body(default_factory=list),
81
+ ) -> AssistantMessage:
82
+ r"""Detokenize a list of tokens to an assistant message.
83
+
84
+ Parse tool calls from the tokens and extract content before the first tool call.
85
+
86
+ Args:
87
+ tokens: The tokens to detokenize.
88
+
89
+ Returns:
90
+ The detokenized assistant message.
91
+ """
92
+ if len(tokens) == 0:
93
+ raise HTTPException(status_code=400, detail="Tokens list cannot be empty.")
94
+
95
+ if settings.tokenizer.instruct_tokenizer.tokenizer.version > TokenizerVersion.v1:
96
+ content_tokens, tool_calls_tokens = _split_content_and_tool_calls(
97
+ tokens, settings.tokenizer.instruct_tokenizer.tokenizer.get_control_token("[TOOL_CALLS]")
98
+ )
99
+ else:
100
+ content_tokens, tool_calls_tokens = tokens, ()
101
+
102
+ content: Optional[Union[str, List[Union[TextChunk, ThinkChunk]]]] = None
103
+
104
+ if settings.tokenizer.instruct_tokenizer.tokenizer.version >= TokenizerVersion.v13:
105
+ assert isinstance(settings.tokenizer.instruct_tokenizer, InstructTokenizerV13)
106
+
107
+ begin_think = settings.tokenizer.instruct_tokenizer.BEGIN_THINK
108
+ end_think = settings.tokenizer.instruct_tokenizer.END_THINK
109
+ else:
110
+ begin_think = end_think = None
111
+
112
+ if begin_think is not None and end_think is not None:
113
+ try:
114
+ content_or_think_tokens = _split_content_and_think_chunks(content_tokens, begin_think, end_think)
115
+ except ValueError as e:
116
+ raise HTTPException(status_code=400, detail=str(e))
117
+
118
+ eos = settings.tokenizer.instruct_tokenizer.tokenizer.eos_id
119
+
120
+ if content_or_think_tokens:
121
+ content = [
122
+ TextChunk(text=settings.tokenizer.decode(chunk, special_token_policy=SpecialTokenPolicy.IGNORE))
123
+ if not is_think
124
+ else ThinkChunk(
125
+ thinking=settings.tokenizer.decode(chunk, special_token_policy=SpecialTokenPolicy.IGNORE),
126
+ closed=chunk[-1] == end_think,
127
+ )
128
+ for chunk, is_think in content_or_think_tokens
129
+ if chunk != [eos] # Don't add a TextChunk with just the EOS token
130
+ ]
131
+ if len(content) == 1 and isinstance(content[0], TextChunk):
132
+ content = content[0].text
133
+
134
+ elif content_tokens:
135
+ content = settings.tokenizer.decode(content_tokens, special_token_policy=SpecialTokenPolicy.IGNORE)
136
+
137
+ if tool_calls_tokens:
138
+ try:
139
+ tool_calls = _decode_tool_calls(tool_calls_tokens, settings.tokenizer.instruct_tokenizer.tokenizer)
140
+ except (ValueError, json.JSONDecodeError) as e:
141
+ raise HTTPException(status_code=400, detail=str(e))
142
+ else:
143
+ tool_calls = None
144
+
145
+ has_eos = tokens[-1] == settings.tokenizer.instruct_tokenizer.tokenizer.eos_id
146
+
147
+ return AssistantMessage(content=content, tool_calls=tool_calls, prefix=not has_eos)
148
+
149
+
150
+ @main_router.post("/v1/chat/completions", tags=["chat", "completions"])
151
+ async def generate(
152
+ request: Union[ChatCompletionRequest, OpenAIChatCompletionRequest],
153
+ settings: Annotated[Settings, Depends(get_settings)],
154
+ ) -> AssistantMessage:
155
+ r"""Generate a chat completion.
156
+
157
+ Args:
158
+ request: The chat completion request.
159
+ settings: The settings for the Mistral-common API.
160
+
161
+ Returns:
162
+ The generated chat completion.
163
+ """
164
+ if isinstance(request, OpenAIChatCompletionRequest):
165
+ extra_fields = request.drop_extra_fields()
166
+ request = ChatCompletionRequest.from_openai(**request.model_dump())
167
+ else:
168
+ extra_fields = {}
169
+ tokens_ids = await tokenize_request(request, settings)
170
+
171
+ exclude_fields = {"messages", "tools"}
172
+
173
+ request_json = request.model_dump()
174
+ request_json.update(extra_fields)
175
+
176
+ request_json = {k: v for k, v in request_json.items() if k not in exclude_fields}
177
+
178
+ if request_json.get("stream", False):
179
+ raise HTTPException(status_code=400, detail="Streaming is not supported.")
180
+
181
+ try:
182
+ if settings.engine_backend == EngineBackend.llama_cpp:
183
+ response = requests.post(
184
+ f"{settings.engine_url}/completions",
185
+ json={
186
+ "prompt": tokens_ids,
187
+ "return_tokens": True,
188
+ **request_json,
189
+ },
190
+ timeout=settings.timeout,
191
+ )
192
+ else:
193
+ raise ValueError(f"Unsupported engine backend: {settings.engine_backend}")
194
+ except requests.exceptions.Timeout:
195
+ raise HTTPException(status_code=504, detail="Timeout")
196
+ except requests.exceptions.RequestException as e:
197
+ raise HTTPException(status_code=500, detail=str(e))
198
+
199
+ if response.status_code != 200:
200
+ raise HTTPException(status_code=response.status_code, detail=response.text)
201
+
202
+ response_json = response.json()
203
+ return await detokenize_to_assistant_message(settings, response_json["tokens"])
venv/lib/python3.10/site-packages/mistral_common/experimental/think.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+
4
+ def _split_content_and_think_chunks(
5
+ tokens: List[int], begin_think_token_id: int, end_think_token_id: int
6
+ ) -> List[Tuple[List[int], bool]]:
7
+ r"""Split the content and think chunks from a list of tokens.
8
+
9
+ Args:
10
+ tokens: List of tokens.
11
+ begin_think_token_id: The token id for the begin think token.
12
+ end_think_token_id: The token id for the end think token.
13
+
14
+ Returns:
15
+ List of tuples, where each tuple contains a list of tokens and a boolean indicating if the chunk is a think
16
+ chunk.
17
+ """
18
+ if not tokens:
19
+ return []
20
+
21
+ content_chunks: List[Tuple[List[int], bool]] = []
22
+ current_content: List[int] = []
23
+
24
+ in_think_chunk = False
25
+ for token in tokens:
26
+ if token == begin_think_token_id and in_think_chunk:
27
+ raise ValueError("Nested think chunks are not allowed.")
28
+ elif token == begin_think_token_id:
29
+ if current_content:
30
+ content_chunks.append((current_content, False))
31
+ current_content = []
32
+ in_think_chunk = True
33
+ current_content.append(token)
34
+ elif token == end_think_token_id:
35
+ if not in_think_chunk:
36
+ raise ValueError("End think token found without a begin think token.")
37
+ current_content.append(token)
38
+ content_chunks.append((current_content, True))
39
+ current_content = []
40
+ in_think_chunk = False
41
+ else:
42
+ current_content.append(token)
43
+
44
+ if current_content:
45
+ content_chunks.append((current_content, in_think_chunk))
46
+
47
+ return content_chunks
venv/lib/python3.10/site-packages/mistral_common/experimental/tools.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import List, Sequence, Tuple
3
+
4
+ from mistral_common.experimental.utils import (
5
+ _split_integer_list_by_value,
6
+ _split_tokens_by_one_occurence_control_token,
7
+ )
8
+ from mistral_common.protocol.instruct.tool_calls import FunctionCall, ToolCall
9
+ from mistral_common.tokens.tokenizers.base import SpecialTokenPolicy, Tokenizer, TokenizerVersion
10
+
11
+
12
+ class InvalidToolCallError(ValueError):
13
+ pass
14
+
15
+
16
+ class InvalidArgsToolCallError(InvalidToolCallError):
17
+ pass
18
+
19
+
20
+ def _split_content_and_tool_calls(
21
+ tokens: List[int], tool_call_token_id: int
22
+ ) -> tuple[List[int], Tuple[List[int], ...]]:
23
+ r"""Split the content and tool calls from a list of tokens.
24
+
25
+ The content is the first sequence of tokens that does not start with the tool call token ID.
26
+ The tool calls are the remaining sequences of tokens that start with the tool call token ID.
27
+
28
+ Args:
29
+ tokens: The list of tokens.
30
+ tool_call_token_id: The token ID that indicates the start of a tool call.
31
+
32
+ Returns:
33
+ A tuple containing the content and tool calls.
34
+ """
35
+ if not tokens:
36
+ return [], ()
37
+
38
+ maybe_content_and_tools_calls = _split_integer_list_by_value(tokens, tool_call_token_id)
39
+
40
+ has_content = maybe_content_and_tools_calls[0][0] != tool_call_token_id
41
+ if has_content:
42
+ content_tokens = maybe_content_and_tools_calls[0]
43
+ tools_calls_tokens = maybe_content_and_tools_calls[1:]
44
+ else:
45
+ content_tokens = []
46
+ tools_calls_tokens = maybe_content_and_tools_calls
47
+
48
+ return content_tokens, tools_calls_tokens
49
+
50
+
51
+ def _decode_tool_calls_v2_up_to_v7(tool_call_tokens: list[int], tokenizer: Tokenizer) -> List[ToolCall]:
52
+ r"""Decode a list of tool call tokens into a list of tool calls for tokenizer versions v2 to v7.
53
+
54
+ Note:
55
+ Expects the tool call tokens to be in the format:
56
+
57
+ `[TOOL_CALLS][{"id": "call_id", "name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]`
58
+ or
59
+
60
+ `[TOOL_CALLS][{"name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]`
61
+ """
62
+ tool_calls_list_string = tokenizer.decode(tool_call_tokens, special_token_policy=SpecialTokenPolicy.IGNORE)
63
+ try:
64
+ tool_calls_decoded_list = json.loads(tool_calls_list_string)
65
+ for tool_call in tool_calls_decoded_list:
66
+ # Check that the tool call arguments are dicts.
67
+ if "arguments" not in tool_call or not isinstance(tool_call["arguments"], dict):
68
+ raise InvalidArgsToolCallError("Invalid tool call arguments tokenization. Expected a dict.")
69
+ except json.JSONDecodeError as e:
70
+ raise InvalidToolCallError(
71
+ "Invalid tool call tokenization. Expected a JSON list of tool calls.",
72
+ ) from e
73
+
74
+ if not isinstance(tool_calls_decoded_list, list):
75
+ raise InvalidToolCallError("Invalid tool call tokenization. Expected a list of tool calls.")
76
+
77
+ return [
78
+ ToolCall(
79
+ id=tool_call.get("id", "null"),
80
+ function=FunctionCall(name=tool_call["name"], arguments=tool_call["arguments"]),
81
+ )
82
+ for tool_call in tool_calls_decoded_list
83
+ ]
84
+
85
+
86
+ def _decode_tool_call_v11_with_call_id(tool_call_tokens: list[int], tokenizer: Tokenizer) -> ToolCall:
87
+ r"""Decode a list of tool call tokens into a tool call for tokenizer version v11 with call ID.
88
+
89
+ Note:
90
+ Expects the tool call tokens to be in the format:
91
+
92
+ `[TOOL_CALLS]name[CALL_ID]call_id[ARGS]{"arg1": "value1", "arg2": "value2"}`
93
+
94
+ """
95
+ name, call_id_and_args = _split_tokens_by_one_occurence_control_token(tool_call_tokens, tokenizer, "[CALL_ID]")
96
+
97
+ call_id, args = _split_tokens_by_one_occurence_control_token(call_id_and_args, tokenizer, "[ARGS]")
98
+
99
+ try:
100
+ tool_call = ToolCall(
101
+ id=tokenizer.decode(call_id),
102
+ function=FunctionCall(
103
+ name=tokenizer.decode(name),
104
+ arguments=json.loads(tokenizer.decode(args, special_token_policy=SpecialTokenPolicy.IGNORE)),
105
+ ),
106
+ )
107
+ except json.JSONDecodeError as e:
108
+ raise InvalidArgsToolCallError("Invalid tokenized tool call arguments.") from e
109
+ return tool_call
110
+
111
+
112
+ def _decode_tool_call_v11(tool_call_tokens: list[int], tokenizer: Tokenizer) -> ToolCall:
113
+ r"""Decode a list of tool call tokens into a tool call for tokenizer version v11 without call ID.
114
+
115
+ Note:
116
+ Expects the tool call tokens to be in the format:
117
+
118
+ `[TOOL_CALLS]name[ARGS]{"arg1": "value1", "arg2": "value2"}`
119
+ """
120
+ name, args = _split_tokens_by_one_occurence_control_token(tool_call_tokens, tokenizer, "[ARGS]")
121
+ try:
122
+ tool_call = ToolCall(
123
+ function=FunctionCall(
124
+ name=tokenizer.decode(name, special_token_policy=SpecialTokenPolicy.IGNORE),
125
+ arguments=json.loads(tokenizer.decode(args, special_token_policy=SpecialTokenPolicy.IGNORE)),
126
+ ),
127
+ )
128
+ except json.JSONDecodeError as e:
129
+ raise InvalidArgsToolCallError("Invalid tokenized tool call arguments.") from e
130
+ return tool_call
131
+
132
+
133
+ def _decode_tool_calls(tool_call_tokens: Sequence[list[int]], tokenizer: Tokenizer) -> List[ToolCall]:
134
+ r"""Decode a list of tool call tokens into a list of tool calls.
135
+
136
+ Note:
137
+ Each list of tool call tokens are expected to be in the format:
138
+ - v2 to v7: `[TOOL_CALLS][{"name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]`
139
+ - v11+ without call ID: `[TOOL_CALLS]name[ARGS]{"arg1": "value1", "arg2": "value2"}`
140
+ - v11+ with call ID: `[TOOL_CALLS]name[CALL_ID]call_id[ARGS]{"arg1": "value1", "arg2": "value2"}`
141
+
142
+ Args:
143
+ tool_call_tokens: A list of lists of tokens.
144
+ tokenizer: The tokenizer to use for decoding.
145
+
146
+ Returns:
147
+ The list of decoded tool calls.
148
+ """
149
+ tools_calls = []
150
+ for tool_call in tool_call_tokens:
151
+ if tokenizer.version == TokenizerVersion.v1:
152
+ raise ValueError("Tool calls are not supported for tokenizer version v1.")
153
+ elif tokenizer.version <= TokenizerVersion.v7:
154
+ tools_calls.extend(_decode_tool_calls_v2_up_to_v7(tool_call, tokenizer))
155
+ elif tokenizer.version == TokenizerVersion.v11 and tokenizer.get_control_token("[CALL_ID]") in tool_call:
156
+ tools_calls.append(_decode_tool_call_v11_with_call_id(tool_call, tokenizer))
157
+ else:
158
+ tools_calls.append(_decode_tool_call_v11(tool_call, tokenizer))
159
+
160
+ return tools_calls
venv/lib/python3.10/site-packages/mistral_common/experimental/utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ from mistral_common.tokens.tokenizers.base import Tokenizer
4
+
5
+
6
+ def _split_integer_list_by_value(list_: List[int], value: int) -> Tuple[List[int], ...]:
7
+ r"""Split a list of integers by a given value.
8
+
9
+ Args:
10
+ list_: The list to split.
11
+ value: The value to split the list by.
12
+
13
+ Returns:
14
+ A tuple of lists of integers.
15
+
16
+ Examples:
17
+ >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 3)
18
+ ([1, 2], [3, 4, 5])
19
+ >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 6)
20
+ ([1, 2, 3, 4, 5],)
21
+ >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 1)
22
+ ([1, 2, 3, 4, 5],)
23
+ >>> _split_integer_list_by_value([1, 2, 3, 4, 5, 3, 5, 6, 7], 3)
24
+ ([1, 2], [3, 4, 5], [3, 5, 6, 7])
25
+ """
26
+ result = [list_[0]]
27
+ for i, item in enumerate(list_[1:]):
28
+ if item == value:
29
+ return (result, *_split_integer_list_by_value(list_[1 + i :], value))
30
+ result.append(item)
31
+ return (result,)
32
+
33
+
34
+ def _split_tokens_by_one_occurence_control_token(
35
+ list_: List[int], tokenizer: Tokenizer, control_token: str
36
+ ) -> Tuple[List[int], List[int]]:
37
+ r"""Split a list of integers by a given control token.
38
+
39
+ Raises:
40
+ ValueError: If the control token is not found in the list or if it is found more than once.
41
+ """
42
+ control_token_id = tokenizer.get_control_token(control_token)
43
+ first, *rest = _split_integer_list_by_value(list_, control_token_id)
44
+ if len(rest) == 0:
45
+ raise ValueError(f"Control token {control_token} not found in the list of tokens.")
46
+ if len(rest) > 1:
47
+ raise ValueError(f"Control token {control_token} found more than once in the list of tokens.")
48
+ return first, rest[0]
venv/lib/python3.10/site-packages/mistral_common/image.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ from typing import Union
4
+
5
+ import requests
6
+ from PIL import Image
7
+ from pydantic import BeforeValidator, PlainSerializer, SerializationInfo
8
+ from typing_extensions import Annotated
9
+
10
+ from mistral_common import __version__
11
+
12
+
13
+ def download_image(url: str) -> Image.Image:
14
+ r"""Download an image from a URL and return it as a PIL Image.
15
+
16
+ Args:
17
+ url: The URL of the image to download.
18
+
19
+ Returns:
20
+ The downloaded image as a PIL Image object.
21
+ """
22
+ headers = {"User-Agent": f"mistral-common/{__version__}"}
23
+ try:
24
+ # Make a request to download the image
25
+ response = requests.get(url, headers=headers)
26
+ response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
27
+
28
+ # Convert the image content to a PIL Image
29
+ img = Image.open(io.BytesIO(response.content))
30
+ return img
31
+
32
+ except requests.exceptions.RequestException as e:
33
+ raise RuntimeError(f"Error downloading the image from {url}: {e}.")
34
+ except Exception as e:
35
+ raise RuntimeError(f"Error converting to PIL image: {e}")
36
+
37
+
38
+ def maybe_load_image_from_str_or_bytes(x: Union[Image.Image, str, bytes]) -> Image.Image:
39
+ r"""Load an image from a string or bytes.
40
+
41
+ If the input is already a PIL Image, return it as is.
42
+
43
+ Args:
44
+ x: The input to load the image from. Can be a PIL Image, a string, or bytes.
45
+ If it's a string, it's assumed to be a base64 encoded string of bytes.
46
+
47
+ Returns:
48
+ The loaded image as a PIL Image object.
49
+ """
50
+ if isinstance(x, Image.Image):
51
+ return x
52
+ if isinstance(x, bytes):
53
+ try:
54
+ return Image.open(io.BytesIO(x))
55
+ except Exception:
56
+ raise RuntimeError("Encountered an error when loading image from bytes.")
57
+
58
+ try:
59
+ image = Image.open(io.BytesIO(base64.b64decode(x.encode("ascii"))))
60
+ return image
61
+ except Exception as e:
62
+ raise RuntimeError(
63
+ f"Encountered an error when loading image from bytes starting "
64
+ f"with '{x[:20]}'. Expected either a PIL.Image.Image or a base64 "
65
+ f"encoded string of bytes."
66
+ ) from e
67
+
68
+
69
+ def serialize_image_to_byte_str(im: Image.Image, info: SerializationInfo) -> str:
70
+ r"""Serialize an image to a base64 encoded string of bytes.
71
+
72
+ Args:
73
+ im: The image to serialize.
74
+ info: The serialization info.
75
+
76
+ Returns:
77
+ The serialized image as a base64 encoded string of bytes.
78
+ """
79
+ if hasattr(info, "context"):
80
+ context = info.context or {}
81
+ else:
82
+ context = {}
83
+
84
+ stream = io.BytesIO()
85
+ im_format = im.format or "PNG"
86
+ im.save(stream, format=im_format)
87
+ im_b64 = base64.b64encode(stream.getvalue()).decode("ascii")
88
+ if context and (max_image_b64_len := context.get("max_image_b64_len")):
89
+ return im_b64[:max_image_b64_len] + "..."
90
+ if context and context.get("add_format_prefix"):
91
+ im_b64 = f"data:image/{im_format.lower()};base64," + im_b64
92
+ return im_b64
93
+
94
+
95
+ SerializableImage = Annotated[
96
+ Image.Image,
97
+ BeforeValidator(maybe_load_image_from_str_or_bytes),
98
+ PlainSerializer(serialize_image_to_byte_str),
99
+ "A normal PIL image that supports serialization to b64 bytes string.",
100
+ ]
venv/lib/python3.10/site-packages/mistral_common/multimodal.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # This file is deprecated. TODO(Patrick) - as soon as vllm & transformers have adapted
2
+ # to new naming, throw deprecation warning and remove this file.
3
+ from mistral_common.image import * # noqa: F403
venv/lib/python3.10/site-packages/mistral_common/protocol/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (259 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/base.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/utils.cpython-310.pyc ADDED
Binary file (450 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/base.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from pydantic import Field
4
+
5
+ from mistral_common.base import MistralBase
6
+
7
+
8
+ class UsageInfo(MistralBase):
9
+ r"""Usage statistics for a completion request.
10
+
11
+ Attributes:
12
+ prompt_tokens: Number of tokens in the prompt.
13
+ completion_tokens: Number of tokens in the generated completion.
14
+ total_tokens: Total number of tokens used in the request (prompt + completion).
15
+
16
+ Examples:
17
+ >>> info = UsageInfo(prompt_tokens=10, completion_tokens=20, total_tokens=30)
18
+ """
19
+
20
+ prompt_tokens: int = 0
21
+ completion_tokens: Optional[int] = 0
22
+ total_tokens: int = 0
23
+
24
+
25
+ class BaseCompletionRequest(MistralBase):
26
+ """Base class for completion requests.
27
+
28
+ Attributes:
29
+ temperature: Sampling temperature to use, between 0 and 1. Higher values like 0.8 will make the output more
30
+ random, while lower values like 0.2 will make it more focused and deterministic.
31
+ top_p: Nucleus sampling parameter, top-p probability mass, between 0 and 1.
32
+ max_tokens: Maximum number of tokens to generate.
33
+ random_seed: Random seed for reproducibility.
34
+
35
+ Examples:
36
+ >>> request = BaseCompletionRequest(temperature=0.7, top_p=0.9, max_tokens=100, random_seed=42)
37
+ """
38
+
39
+ temperature: float = Field(default=0.7, ge=0.0, le=1.0)
40
+ top_p: float = Field(default=1.0, ge=0.0, le=1.0)
41
+ max_tokens: Optional[int] = Field(default=None, ge=0)
42
+ random_seed: Optional[int] = Field(default=None, ge=0)
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (269 Bytes). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/request.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/response.cpython-310.pyc ADDED
Binary file (2.57 kB). View file
 
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/request.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Union
2
+
3
+ from pydantic import Field
4
+
5
+ from mistral_common.base import MistralBase
6
+
7
+
8
+ class EmbeddingRequest(MistralBase):
9
+ r""" "Embedding request model used to generate embeddings for the given input.
10
+
11
+ See [EmbeddingResponse][mistral_common.protocol.embedding.response.EmbeddingResponse] for the response model.
12
+
13
+ Attributes:
14
+ input: Text to embed.
15
+ model: ID of the model to use.
16
+ encoding_format: The format to return the embeddings in.
17
+
18
+ Examples:
19
+ >>> request = EmbeddingRequest(input="Hello world!", model="mistral-embed")
20
+ """
21
+
22
+ input: Union[str, List[str]] = Field(description="Text to embed.")
23
+ model: str = Field(description="ID of the model to use.")
24
+ encoding_format: Optional[str] = Field(default="float", description="The format to return the embeddings in.")
venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/response.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from pydantic import Field
4
+
5
+ from mistral_common.base import MistralBase
6
+ from mistral_common.protocol.base import UsageInfo
7
+ from mistral_common.protocol.utils import random_uuid
8
+
9
+
10
+ class EmbeddingObject(MistralBase):
11
+ r"""Embedding object returned by the API.
12
+
13
+ Attributes:
14
+ object: The type of the object returned.
15
+ embedding: The embedding vector.
16
+ index: The index of the embedding in the input text.
17
+
18
+ Examples:
19
+ >>> embedding_object = EmbeddingObject(
20
+ ... object="embedding",
21
+ ... embedding=[0.1, 0.2, 0.3],
22
+ ... index=0
23
+ ... )
24
+ """
25
+
26
+ object: str = Field(default="embedding", description="The type of the object returned.")
27
+ embedding: List[float] = Field(description="The type of the object returned.")
28
+ index: int = Field(description="The index of the embedding in the input text.")
29
+
30
+
31
+ class EmbeddingResponse(MistralBase):
32
+ r""" "Embedding response returned by the API.
33
+
34
+ See the [EmbeddingRequest][mistral_common.protocol.embedding.request.EmbeddingRequest] for the request body.
35
+
36
+ Attributes:
37
+ id: The ID of the embedding.
38
+ object: The type of the object returned.
39
+ data: List of embeddings.
40
+ model: The model used to generate the embeddings.
41
+
42
+ Examples:
43
+ >>> response = EmbeddingResponse(
44
+ ... id="embd-123",
45
+ ... object="list",
46
+ ... data=[],
47
+ ... model="text-embedding-ada-002",
48
+ ... usage=UsageInfo(prompt_tokens=1, total_tokens=1, completion_tokens=0)
49
+ ... )
50
+ """
51
+
52
+ id: str = Field(default_factory=lambda: f"embd-{random_uuid()}")
53
+ object: str = Field(default="list", description="The type of the object returned.")
54
+ data: List[EmbeddingObject] = Field(description="List of embeddings.")
55
+ model: str = Field(description="The model used to generate the embeddings.")
56
+ usage: UsageInfo
venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__init__.py ADDED
File without changes