chainlit 2.7.0__py3-none-any.whl → 2.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of chainlit might be problematic. Click here for more details.

Files changed (85) hide show
  1. {chainlit-2.7.0.dist-info → chainlit-2.7.1.dist-info}/METADATA +1 -1
  2. chainlit-2.7.1.dist-info/RECORD +4 -0
  3. chainlit/__init__.py +0 -207
  4. chainlit/__main__.py +0 -4
  5. chainlit/_utils.py +0 -8
  6. chainlit/action.py +0 -33
  7. chainlit/auth/__init__.py +0 -95
  8. chainlit/auth/cookie.py +0 -197
  9. chainlit/auth/jwt.py +0 -42
  10. chainlit/cache.py +0 -45
  11. chainlit/callbacks.py +0 -433
  12. chainlit/chat_context.py +0 -64
  13. chainlit/chat_settings.py +0 -34
  14. chainlit/cli/__init__.py +0 -235
  15. chainlit/config.py +0 -621
  16. chainlit/context.py +0 -112
  17. chainlit/data/__init__.py +0 -111
  18. chainlit/data/acl.py +0 -19
  19. chainlit/data/base.py +0 -107
  20. chainlit/data/chainlit_data_layer.py +0 -687
  21. chainlit/data/dynamodb.py +0 -616
  22. chainlit/data/literalai.py +0 -501
  23. chainlit/data/sql_alchemy.py +0 -741
  24. chainlit/data/storage_clients/__init__.py +0 -0
  25. chainlit/data/storage_clients/azure.py +0 -84
  26. chainlit/data/storage_clients/azure_blob.py +0 -94
  27. chainlit/data/storage_clients/base.py +0 -28
  28. chainlit/data/storage_clients/gcs.py +0 -101
  29. chainlit/data/storage_clients/s3.py +0 -88
  30. chainlit/data/utils.py +0 -29
  31. chainlit/discord/__init__.py +0 -6
  32. chainlit/discord/app.py +0 -364
  33. chainlit/element.py +0 -454
  34. chainlit/emitter.py +0 -450
  35. chainlit/hello.py +0 -12
  36. chainlit/input_widget.py +0 -182
  37. chainlit/langchain/__init__.py +0 -6
  38. chainlit/langchain/callbacks.py +0 -682
  39. chainlit/langflow/__init__.py +0 -25
  40. chainlit/llama_index/__init__.py +0 -6
  41. chainlit/llama_index/callbacks.py +0 -206
  42. chainlit/logger.py +0 -16
  43. chainlit/markdown.py +0 -57
  44. chainlit/mcp.py +0 -99
  45. chainlit/message.py +0 -619
  46. chainlit/mistralai/__init__.py +0 -50
  47. chainlit/oauth_providers.py +0 -835
  48. chainlit/openai/__init__.py +0 -53
  49. chainlit/py.typed +0 -0
  50. chainlit/secret.py +0 -9
  51. chainlit/semantic_kernel/__init__.py +0 -111
  52. chainlit/server.py +0 -1616
  53. chainlit/session.py +0 -304
  54. chainlit/sidebar.py +0 -55
  55. chainlit/slack/__init__.py +0 -6
  56. chainlit/slack/app.py +0 -427
  57. chainlit/socket.py +0 -381
  58. chainlit/step.py +0 -490
  59. chainlit/sync.py +0 -43
  60. chainlit/teams/__init__.py +0 -6
  61. chainlit/teams/app.py +0 -348
  62. chainlit/translations/bn.json +0 -214
  63. chainlit/translations/el-GR.json +0 -214
  64. chainlit/translations/en-US.json +0 -214
  65. chainlit/translations/fr-FR.json +0 -214
  66. chainlit/translations/gu.json +0 -214
  67. chainlit/translations/he-IL.json +0 -214
  68. chainlit/translations/hi.json +0 -214
  69. chainlit/translations/ja.json +0 -214
  70. chainlit/translations/kn.json +0 -214
  71. chainlit/translations/ml.json +0 -214
  72. chainlit/translations/mr.json +0 -214
  73. chainlit/translations/nl.json +0 -214
  74. chainlit/translations/ta.json +0 -214
  75. chainlit/translations/te.json +0 -214
  76. chainlit/translations/zh-CN.json +0 -214
  77. chainlit/translations.py +0 -60
  78. chainlit/types.py +0 -334
  79. chainlit/user.py +0 -43
  80. chainlit/user_session.py +0 -153
  81. chainlit/utils.py +0 -173
  82. chainlit/version.py +0 -8
  83. chainlit-2.7.0.dist-info/RECORD +0 -84
  84. {chainlit-2.7.0.dist-info → chainlit-2.7.1.dist-info}/WHEEL +0 -0
  85. {chainlit-2.7.0.dist-info → chainlit-2.7.1.dist-info}/entry_points.txt +0 -0
chainlit/config.py DELETED
@@ -1,621 +0,0 @@
1
- import json
2
- import os
3
- import site
4
- import sys
5
- from importlib import util
6
- from pathlib import Path
7
- from typing import (
8
- TYPE_CHECKING,
9
- Any,
10
- Awaitable,
11
- Callable,
12
- Dict,
13
- List,
14
- Literal,
15
- Optional,
16
- Union,
17
- )
18
-
19
- import tomli
20
- from pydantic import BaseModel, ConfigDict, Field
21
- from starlette.datastructures import Headers
22
-
23
- from chainlit.data.base import BaseDataLayer
24
- from chainlit.logger import logger
25
- from chainlit.translations import lint_translation_json
26
- from chainlit.version import __version__
27
-
28
- from ._utils import is_path_inside
29
-
30
- if TYPE_CHECKING:
31
- from fastapi import Request, Response
32
-
33
- from chainlit.action import Action
34
- from chainlit.message import Message
35
- from chainlit.types import (
36
- ChatProfile,
37
- Feedback,
38
- InputAudioChunk,
39
- Starter,
40
- ThreadDict,
41
- )
42
- from chainlit.user import User
43
- else:
44
- # Pydantic needs to resolve forward annotations. Because all of these are used
45
- # within `typing.Callable`, alias to `Any` as Pydantic does not perform validation
46
- # of callable argument/return types anyway.
47
- Request = Response = Action = Message = ChatProfile = InputAudioChunk = Starter = ThreadDict = User = Feedback = Any # fmt: off
48
-
49
- BACKEND_ROOT = os.path.dirname(__file__)
50
- PACKAGE_ROOT = os.path.dirname(os.path.dirname(BACKEND_ROOT))
51
- TRANSLATIONS_DIR = os.path.join(BACKEND_ROOT, "translations")
52
-
53
-
54
- # Get the directory the script is running from
55
- APP_ROOT = os.getenv("CHAINLIT_APP_ROOT", os.getcwd())
56
-
57
- # Create the directory to store the uploaded files
58
- FILES_DIRECTORY = Path(APP_ROOT) / ".files"
59
- FILES_DIRECTORY.mkdir(exist_ok=True)
60
-
61
- config_dir = os.path.join(APP_ROOT, ".chainlit")
62
- public_dir = os.path.join(APP_ROOT, "public")
63
- config_file = os.path.join(config_dir, "config.toml")
64
- config_translation_dir = os.path.join(config_dir, "translations")
65
-
66
- # Default config file created if none exists
67
- DEFAULT_CONFIG_STR = f"""[project]
68
- # List of environment variables to be provided by each user to use the app.
69
- user_env = []
70
-
71
- # Duration (in seconds) during which the session is saved when the connection is lost
72
- session_timeout = 3600
73
-
74
- # Duration (in seconds) of the user session expiry
75
- user_session_timeout = 1296000 # 15 days
76
-
77
- # Enable third parties caching (e.g., LangChain cache)
78
- cache = false
79
-
80
- # Authorized origins
81
- allow_origins = ["*"]
82
-
83
- [features]
84
- # Process and display HTML in messages. This can be a security risk (see https://stackoverflow.com/questions/19603097/why-is-it-dangerous-to-render-user-generated-html-or-javascript)
85
- unsafe_allow_html = false
86
-
87
- # Process and display mathematical expressions. This can clash with "$" characters in messages.
88
- latex = false
89
-
90
- # Autoscroll new user messages at the top of the window
91
- user_message_autoscroll = true
92
-
93
- # Automatically tag threads with the current chat profile (if a chat profile is used)
94
- auto_tag_thread = true
95
-
96
- # Allow users to edit their own messages
97
- edit_message = true
98
-
99
- [features.slack]
100
- # Add emoji reaction when message is received (requires reactions:write OAuth scope)
101
- reaction_on_message_received = false
102
-
103
- # Authorize users to spontaneously upload files with messages
104
- [features.spontaneous_file_upload]
105
- enabled = true
106
- # Define accepted file types using MIME types
107
- # Examples:
108
- # 1. For specific file types:
109
- # accept = ["image/jpeg", "image/png", "application/pdf"]
110
- # 2. For all files of certain type:
111
- # accept = ["image/*", "audio/*", "video/*"]
112
- # 3. For specific file extensions:
113
- # accept = {{ "application/octet-stream" = [".xyz", ".pdb"] }}
114
- # Note: Using "*/*" is not recommended as it may cause browser warnings
115
- accept = ["*/*"]
116
- max_files = 20
117
- max_size_mb = 500
118
-
119
- [features.audio]
120
- # Enable audio features
121
- enabled = false
122
- # Sample rate of the audio
123
- sample_rate = 24000
124
-
125
- [features.mcp]
126
- # Enable Model Context Protocol (MCP) features
127
- enabled = false
128
-
129
- [features.mcp.sse]
130
- enabled = true
131
-
132
- [features.mcp.streamable-http]
133
- enabled = true
134
-
135
- [features.mcp.stdio]
136
- enabled = true
137
- # Only the executables in the allow list can be used for MCP stdio server.
138
- # Only need the base name of the executable, e.g. "npx", not "/usr/bin/npx".
139
- # Please don't comment this line for now, we need it to parse the executable name.
140
- allowed_executables = [ "npx", "uvx" ]
141
-
142
- [UI]
143
- # Name of the assistant.
144
- name = "Assistant"
145
-
146
- # default_theme = "dark"
147
-
148
- # layout = "wide"
149
-
150
- # default_sidebar_state = "open"
151
-
152
- # Description of the assistant. This is used for HTML tags.
153
- # description = ""
154
-
155
- # Chain of Thought (CoT) display mode. Can be "hidden", "tool_call" or "full".
156
- cot = "full"
157
-
158
- # Specify a CSS file that can be used to customize the user interface.
159
- # The CSS file can be served from the public directory or via an external link.
160
- # custom_css = "/public/test.css"
161
-
162
- # Specify additional attributes for a custom CSS file
163
- # custom_css_attributes = "media=\\\"print\\\""
164
-
165
- # Specify a JavaScript file that can be used to customize the user interface.
166
- # The JavaScript file can be served from the public directory.
167
- # custom_js = "/public/test.js"
168
-
169
- # The style of alert boxes. Can be "classic" or "modern".
170
- alert_style = "classic"
171
-
172
- # Specify additional attributes for custom JS file
173
- # custom_js_attributes = "async type = \\\"module\\\""
174
-
175
- # Custom login page image, relative to public directory or external URL
176
- # login_page_image = "/public/custom-background.jpg"
177
-
178
- # Custom login page image filter (Tailwind internal filters, no dark/light variants)
179
- # login_page_image_filter = "brightness-50 grayscale"
180
- # login_page_image_dark_filter = "contrast-200 blur-sm"
181
-
182
-
183
- # Specify a custom meta image url.
184
- # custom_meta_image_url = "https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png"
185
-
186
- # Load assistant logo directly from URL.
187
- logo_file_url = ""
188
-
189
- # Load assistant avatar image directly from URL.
190
- default_avatar_file_url = ""
191
-
192
- # Specify a custom build directory for the frontend.
193
- # This can be used to customize the frontend code.
194
- # Be careful: If this is a relative path, it should not start with a slash.
195
- # custom_build = "./public/build"
196
-
197
- # Specify optional one or more custom links in the header.
198
- # [[UI.header_links]]
199
- # name = "Issues"
200
- # display_name = "Report Issue"
201
- # icon_url = "https://avatars.githubusercontent.com/u/128686189?s=200&v=4"
202
- # url = "https://github.com/Chainlit/chainlit/issues"
203
-
204
- [meta]
205
- generated_by = "{__version__}"
206
- """
207
-
208
-
209
- DEFAULT_HOST = "127.0.0.1"
210
- DEFAULT_PORT = 8000
211
- DEFAULT_ROOT_PATH = ""
212
-
213
-
214
- class RunSettings(BaseModel):
215
- # Name of the module (python file) used in the run command
216
- module_name: Optional[str] = None
217
- host: str = DEFAULT_HOST
218
- port: int = DEFAULT_PORT
219
- ssl_cert: Optional[str] = None
220
- ssl_key: Optional[str] = None
221
- root_path: str = DEFAULT_ROOT_PATH
222
- headless: bool = False
223
- watch: bool = False
224
- no_cache: bool = False
225
- debug: bool = False
226
- ci: bool = False
227
-
228
-
229
- class PaletteOptions(BaseModel):
230
- main: Optional[str] = ""
231
- light: Optional[str] = ""
232
- dark: Optional[str] = ""
233
-
234
-
235
- class TextOptions(BaseModel):
236
- primary: Optional[str] = ""
237
- secondary: Optional[str] = ""
238
-
239
-
240
- class Palette(BaseModel):
241
- primary: Optional[PaletteOptions] = None
242
- background: Optional[str] = ""
243
- paper: Optional[str] = ""
244
- text: Optional[TextOptions] = None
245
-
246
-
247
- class SpontaneousFileUploadFeature(BaseModel):
248
- enabled: Optional[bool] = None
249
- accept: Optional[Union[List[str], Dict[str, List[str]]]] = None
250
- max_files: Optional[int] = None
251
- max_size_mb: Optional[int] = None
252
-
253
-
254
- class AudioFeature(BaseModel):
255
- sample_rate: int = 24000
256
- enabled: bool = False
257
-
258
-
259
- class McpSseFeature(BaseModel):
260
- enabled: bool = True
261
-
262
-
263
- class McpStreamableHttpFeature(BaseModel):
264
- enabled: bool = True
265
-
266
-
267
- class McpStdioFeature(BaseModel):
268
- enabled: bool = True
269
- allowed_executables: Optional[list[str]] = None
270
-
271
-
272
- class SlackFeature(BaseModel):
273
- reaction_on_message_received: bool = False
274
-
275
-
276
- class McpFeature(BaseModel):
277
- enabled: bool = False
278
- sse: McpSseFeature = Field(default_factory=McpSseFeature)
279
- streamable_http: McpStreamableHttpFeature = Field(
280
- default_factory=McpStreamableHttpFeature
281
- )
282
- stdio: McpStdioFeature = Field(default_factory=McpStdioFeature)
283
-
284
-
285
- class FeaturesSettings(BaseModel):
286
- spontaneous_file_upload: Optional[SpontaneousFileUploadFeature] = None
287
- audio: Optional[AudioFeature] = Field(default_factory=AudioFeature)
288
- mcp: McpFeature = Field(default_factory=McpFeature)
289
- slack: SlackFeature = Field(default_factory=SlackFeature)
290
- latex: bool = False
291
- user_message_autoscroll: bool = True
292
- unsafe_allow_html: bool = False
293
- auto_tag_thread: bool = True
294
- edit_message: bool = True
295
-
296
-
297
- class HeaderLink(BaseModel):
298
- name: str
299
- icon_url: str
300
- url: str
301
- display_name: Optional[str] = None
302
-
303
-
304
- class UISettings(BaseModel):
305
- name: str
306
- description: str = ""
307
- cot: Literal["hidden", "tool_call", "full"] = "full"
308
- default_theme: Optional[Literal["light", "dark"]] = "dark"
309
- layout: Optional[Literal["default", "wide"]] = "default"
310
- default_sidebar_state: Optional[Literal["open", "closed"]] = "open"
311
- github: Optional[str] = None
312
- # Optional custom CSS file that allows you to customize the UI
313
- custom_css: Optional[str] = None
314
- custom_css_attributes: Optional[str] = ""
315
- # Optional custom JS file that allows you to customize the UI
316
- custom_js: Optional[str] = None
317
-
318
- alert_style: Optional[Literal["classic", "modern"]] = "classic"
319
- custom_js_attributes: Optional[str] = "defer"
320
- # Optional custom background image for login page
321
- login_page_image: Optional[str] = None
322
- login_page_image_filter: Optional[str] = None
323
- login_page_image_dark_filter: Optional[str] = None
324
-
325
- # Optional custom meta tag for image preview
326
- custom_meta_image_url: Optional[str] = None
327
- # Optional logo file url
328
- logo_file_url: Optional[str] = None
329
- # Optional avatar image file url
330
- default_avatar_file_url: Optional[str] = None
331
- # Optional custom build directory for the frontend
332
- custom_build: Optional[str] = None
333
- # Optional header links
334
- header_links: Optional[List[HeaderLink]] = None
335
-
336
-
337
- class CodeSettings(BaseModel):
338
- # App action functions
339
- action_callbacks: Dict[str, Callable[["Action"], Any]]
340
-
341
- # Module object loaded from the module_name
342
- module: Any = None
343
-
344
- # App life cycle callbacks
345
- on_app_startup: Optional[Callable[[], Union[None, Awaitable[None]]]] = None
346
- on_app_shutdown: Optional[Callable[[], Union[None, Awaitable[None]]]] = None
347
-
348
- # Session life cycle callbacks
349
- on_logout: Optional[Callable[["Request", "Response"], Any]] = None
350
- on_stop: Optional[Callable[[], Any]] = None
351
- on_chat_start: Optional[Callable[[], Any]] = None
352
- on_chat_end: Optional[Callable[[], Any]] = None
353
- on_chat_resume: Optional[Callable[["ThreadDict"], Any]] = None
354
- on_message: Optional[Callable[["Message"], Any]] = None
355
- on_feedback: Optional[Callable[["Feedback"], Any]] = None
356
- on_audio_start: Optional[Callable[[], Any]] = None
357
- on_audio_chunk: Optional[Callable[["InputAudioChunk"], Any]] = None
358
- on_audio_end: Optional[Callable[[], Any]] = None
359
- on_mcp_connect: Optional[Callable] = None
360
- on_mcp_disconnect: Optional[Callable] = None
361
- on_settings_update: Optional[Callable[[Dict[str, Any]], Any]] = None
362
- set_chat_profiles: Optional[
363
- Callable[[Optional["User"]], Awaitable[List["ChatProfile"]]]
364
- ] = None
365
- set_starters: Optional[Callable[[Optional["User"]], Awaitable[List["Starter"]]]] = (
366
- None
367
- )
368
- # Auth callbacks
369
- password_auth_callback: Optional[
370
- Callable[[str, str], Awaitable[Optional["User"]]]
371
- ] = None
372
- header_auth_callback: Optional[Callable[[Headers], Awaitable[Optional["User"]]]] = (
373
- None
374
- )
375
- oauth_callback: Optional[
376
- Callable[[str, str, Dict[str, str], "User"], Awaitable[Optional["User"]]]
377
- ] = None
378
-
379
- # Helpers
380
- on_window_message: Optional[Callable[[str], Any]] = None
381
- author_rename: Optional[Callable[[str], Awaitable[str]]] = None
382
- data_layer: Optional[Callable[[], BaseDataLayer]] = None
383
-
384
-
385
- class ProjectSettings(BaseModel):
386
- allow_origins: List[str] = Field(default_factory=lambda: ["*"])
387
- # Socket.io client transports option
388
- transports: Optional[List[str]] = None
389
- # List of environment variables to be provided by each user to use the app. If empty, no environment variables will be asked to the user.
390
- user_env: Optional[List[str]] = None
391
- # Path to the local langchain cache database
392
- lc_cache_path: Optional[str] = None
393
- # Path to the local chat db
394
- # Duration (in seconds) during which the session is saved when the connection is lost
395
- session_timeout: int = 300
396
- # Duration (in seconds) of the user session expiry
397
- user_session_timeout: int = 1296000 # 15 days
398
- # Enable third parties caching (e.g LangChain cache)
399
- cache: bool = False
400
-
401
-
402
- class ChainlitConfigOverrides(BaseModel):
403
- """Configuration overrides that can be applied to specific chat profiles."""
404
-
405
- ui: Optional[UISettings] = None
406
- features: Optional[FeaturesSettings] = None
407
- project: Optional[ProjectSettings] = None
408
-
409
-
410
- class ChainlitConfig(BaseModel):
411
- model_config = ConfigDict(
412
- arbitrary_types_allowed=True, revalidate_instances="always"
413
- )
414
-
415
- # Directory where the Chainlit project is located
416
- root: str = APP_ROOT
417
- # Chainlit server URL. Used only for cloud features
418
- chainlit_server: str
419
- run: RunSettings
420
- features: FeaturesSettings
421
- ui: UISettings
422
- project: ProjectSettings
423
- code: CodeSettings
424
-
425
- def load_translation(self, language: str):
426
- translation = {}
427
- default_language = "en-US"
428
- # fallback to root language (ex: `de` when `de-DE` is not found)
429
- parent_language = language.split("-")[0]
430
-
431
- translation_dir = Path(config_translation_dir)
432
-
433
- translation_lib_file_path = translation_dir / f"{language}.json"
434
- translation_lib_parent_language_file_path = (
435
- translation_dir / f"{parent_language}.json"
436
- )
437
- default_translation_lib_file_path = translation_dir / f"{default_language}.json"
438
-
439
- if (
440
- is_path_inside(translation_lib_file_path, translation_dir)
441
- and translation_lib_file_path.is_file()
442
- ):
443
- translation = json.loads(
444
- translation_lib_file_path.read_text(encoding="utf-8")
445
- )
446
- elif (
447
- is_path_inside(translation_lib_parent_language_file_path, translation_dir)
448
- and translation_lib_parent_language_file_path.is_file()
449
- ):
450
- logger.warning(
451
- f"Translation file for {language} not found. Using parent translation {parent_language}."
452
- )
453
- translation = json.loads(
454
- translation_lib_parent_language_file_path.read_text(encoding="utf-8")
455
- )
456
- elif (
457
- is_path_inside(default_translation_lib_file_path, translation_dir)
458
- and default_translation_lib_file_path.is_file()
459
- ):
460
- logger.warning(
461
- f"Translation file for {language} not found. Using default translation {default_language}."
462
- )
463
- translation = json.loads(
464
- default_translation_lib_file_path.read_text(encoding="utf-8")
465
- )
466
-
467
- return translation
468
-
469
-
470
- def init_config(log=False):
471
- """Initialize the configuration file if it doesn't exist."""
472
- if not os.path.exists(config_file):
473
- os.makedirs(config_dir, exist_ok=True)
474
- with open(config_file, "w", encoding="utf-8") as f:
475
- f.write(DEFAULT_CONFIG_STR)
476
- logger.info(f"Created default config file at {config_file}")
477
- elif log:
478
- logger.info(f"Config file already exists at {config_file}")
479
-
480
- if not os.path.exists(config_translation_dir):
481
- os.makedirs(config_translation_dir, exist_ok=True)
482
- logger.info(
483
- f"Created default translation directory at {config_translation_dir}"
484
- )
485
-
486
- for file in os.listdir(TRANSLATIONS_DIR):
487
- if file.endswith(".json"):
488
- dst = os.path.join(config_translation_dir, file)
489
- if not os.path.exists(dst):
490
- src = os.path.join(TRANSLATIONS_DIR, file)
491
- with open(src, encoding="utf-8") as f:
492
- translation = json.load(f)
493
- with open(dst, "w", encoding="utf-8") as f:
494
- json.dump(translation, f, indent=4)
495
- logger.info(f"Created default translation file at {dst}")
496
-
497
-
498
- def load_module(target: str, force_refresh: bool = False):
499
- """Load the specified module."""
500
-
501
- # Get the target's directory
502
- target_dir = os.path.dirname(os.path.abspath(target))
503
-
504
- # Add the target's directory to the Python path
505
- sys.path.insert(0, target_dir)
506
-
507
- if force_refresh:
508
- # Get current site packages dirs
509
- site_package_dirs = site.getsitepackages()
510
-
511
- # Clear the modules related to the app from sys.modules
512
- for module_name, module in sys.modules.items():
513
- if (
514
- hasattr(module, "__file__")
515
- and module.__file__
516
- and module.__file__.startswith(target_dir)
517
- and not any(module.__file__.startswith(p) for p in site_package_dirs)
518
- ):
519
- sys.modules.pop(module_name, None)
520
-
521
- spec = util.spec_from_file_location(target, target)
522
- if not spec or not spec.loader:
523
- return
524
-
525
- module = util.module_from_spec(spec)
526
- if not module:
527
- return
528
-
529
- spec.loader.exec_module(module)
530
-
531
- sys.modules[target] = module
532
-
533
- # Remove the target's directory from the Python path
534
- sys.path.pop(0)
535
-
536
-
537
- def load_settings():
538
- with open(config_file, "rb") as f:
539
- toml_dict = tomli.load(f)
540
- # Load project settings
541
- project_config = toml_dict.get("project", {})
542
- features_settings = toml_dict.get("features", {})
543
- ui_settings = toml_dict.get("UI", {})
544
- meta = toml_dict.get("meta")
545
-
546
- if not meta or meta.get("generated_by") <= "0.3.0":
547
- raise ValueError(
548
- f"Your config file '{config_file}' is outdated. Please delete it and restart the app to regenerate it."
549
- )
550
-
551
- lc_cache_path = os.path.join(config_dir, ".langchain.db")
552
-
553
- project_settings = ProjectSettings(
554
- lc_cache_path=lc_cache_path,
555
- **project_config,
556
- )
557
-
558
- features_settings = FeaturesSettings(**features_settings)
559
-
560
- ui_settings = UISettings(**ui_settings)
561
-
562
- code_settings = CodeSettings(action_callbacks={})
563
-
564
- return {
565
- "features": features_settings,
566
- "ui": ui_settings,
567
- "project": project_settings,
568
- "code": code_settings,
569
- }
570
-
571
-
572
- def reload_config():
573
- """Reload the configuration from the config file."""
574
- global config
575
- if config is None:
576
- return
577
-
578
- settings = load_settings()
579
-
580
- config.features = settings["features"]
581
- config.code = settings["code"]
582
- config.ui = settings["ui"]
583
- config.project = settings["project"]
584
-
585
-
586
- def load_config():
587
- """Load the configuration from the config file."""
588
- init_config()
589
-
590
- settings = load_settings()
591
-
592
- chainlit_server = os.environ.get("CHAINLIT_SERVER", "https://cloud.chainlit.io")
593
-
594
- config = ChainlitConfig(
595
- chainlit_server=chainlit_server,
596
- run=RunSettings(),
597
- **settings,
598
- )
599
-
600
- return config
601
-
602
-
603
- def lint_translations():
604
- # Load the ground truth (en-US.json file from chainlit source code)
605
- src = os.path.join(TRANSLATIONS_DIR, "en-US.json")
606
- with open(src, encoding="utf-8") as f:
607
- truth = json.load(f)
608
-
609
- # Find the local app translations
610
- for file in os.listdir(config_translation_dir):
611
- if file.endswith(".json"):
612
- # Load the translation file
613
- to_lint = os.path.join(config_translation_dir, file)
614
- with open(to_lint, encoding="utf-8") as f:
615
- translation = json.load(f)
616
-
617
- # Lint the translation file
618
- lint_translation_json(file, truth, translation)
619
-
620
-
621
- config = load_config()