/
__init__.py
372 lines (289 loc) · 9.46 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import os
from dotenv import load_dotenv
env_found = load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
import asyncio
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
from fastapi import Request, Response
from pydantic.dataclasses import dataclass
from starlette.datastructures import Headers
if TYPE_CHECKING:
from chainlit.haystack.callbacks import HaystackAgentCallbackHandler
from chainlit.langchain.callbacks import (
LangchainCallbackHandler,
AsyncLangchainCallbackHandler,
)
from chainlit.llama_index.callbacks import LlamaIndexCallbackHandler
from chainlit.openai import instrument_openai
import chainlit.input_widget as input_widget
from chainlit.action import Action
from chainlit.cache import cache
from chainlit.chat_settings import ChatSettings
from chainlit.config import config
from chainlit.context import context
from chainlit.element import (
Audio,
Avatar,
File,
Image,
Pdf,
Plotly,
Pyplot,
Task,
TaskList,
TaskStatus,
Text,
Video,
)
from chainlit.logger import logger
from chainlit.message import (
AskActionMessage,
AskFileMessage,
AskUserMessage,
ErrorMessage,
Message,
)
from chainlit.oauth_providers import get_configured_oauth_providers
from chainlit.step import Step, step
from chainlit.sync import make_async, run_sync
from chainlit.telemetry import trace
from chainlit.types import ChatProfile, ThreadDict
from chainlit.user import PersistedUser, User
from chainlit.user_session import user_session
from chainlit.utils import make_module_getattr, wrap_user_function
from chainlit.version import __version__
from literalai import ChatGeneration, CompletionGeneration, GenerationMessage
if env_found:
logger.info("Loaded .env file")
@trace
def password_auth_callback(func: Callable[[str, str], Optional[User]]) -> Callable:
"""
Framework agnostic decorator to authenticate the user.
Args:
func (Callable[[str, str], Optional[User]]): The authentication callback to execute. Takes the email and password as parameters.
Example:
@cl.password_auth_callback
async def password_auth_callback(username: str, password: str) -> Optional[User]:
Returns:
Callable[[str, str], Optional[User]]: The decorated authentication callback.
"""
config.code.password_auth_callback = wrap_user_function(func)
return func
@trace
def header_auth_callback(func: Callable[[Headers], Optional[User]]) -> Callable:
"""
Framework agnostic decorator to authenticate the user via a header
Args:
func (Callable[[Headers], Optional[User]]): The authentication callback to execute.
Example:
@cl.header_auth_callback
async def header_auth_callback(headers: Headers) -> Optional[User]:
Returns:
Callable[[Headers], Optional[User]]: The decorated authentication callback.
"""
config.code.header_auth_callback = wrap_user_function(func)
return func
@trace
def oauth_callback(
func: Callable[[str, str, Dict[str, str], User], Optional[User]]
) -> Callable:
"""
Framework agnostic decorator to authenticate the user via oauth
Args:
func (Callable[[str, str, Dict[str, str], User], Optional[User]]): The authentication callback to execute.
Example:
@cl.oauth_callback
async def oauth_callback(provider_id: str, token: str, raw_user_data: Dict[str, str], default_app_user: User, id_token: str) -> Optional[User]:
Returns:
Callable[[str, str, Dict[str, str], User], Optional[User]]: The decorated authentication callback.
"""
if len(get_configured_oauth_providers()) == 0:
raise ValueError(
"You must set the environment variable for at least one oauth provider to use oauth authentication."
)
config.code.oauth_callback = wrap_user_function(func)
return func
@trace
def on_logout(func: Callable[[Request, Response], Any]) -> Callable:
"""
Function called when the user logs out.
Takes the FastAPI request and response as parameters.
"""
config.code.on_logout = wrap_user_function(func)
return func
@trace
def on_message(func: Callable) -> Callable:
"""
Framework agnostic decorator to react to messages coming from the UI.
The decorated function is called every time a new message is received.
Args:
func (Callable[[Message], Any]): The function to be called when a new message is received. Takes a cl.Message.
Returns:
Callable[[str], Any]: The decorated on_message function.
"""
config.code.on_message = wrap_user_function(func)
return func
@trace
def on_chat_start(func: Callable) -> Callable:
"""
Hook to react to the user websocket connection event.
Args:
func (Callable[], Any]): The connection hook to execute.
Returns:
Callable[], Any]: The decorated hook.
"""
config.code.on_chat_start = wrap_user_function(func, with_task=True)
return func
@trace
def on_chat_resume(func: Callable[[ThreadDict], Any]) -> Callable:
"""
Hook to react to resume websocket connection event.
Args:
func (Callable[], Any]): The connection hook to execute.
Returns:
Callable[], Any]: The decorated hook.
"""
config.code.on_chat_resume = wrap_user_function(func, with_task=True)
return func
@trace
def set_chat_profiles(
func: Callable[[Optional["User"]], List["ChatProfile"]]
) -> Callable:
"""
Programmatic declaration of the available chat profiles (can depend on the User from the session if authentication is setup).
Args:
func (Callable[[Optional["User"]], List["ChatProfile"]]): The function declaring the chat profiles.
Returns:
Callable[[Optional["User"]], List["ChatProfile"]]: The decorated function.
"""
config.code.set_chat_profiles = wrap_user_function(func)
return func
@trace
def on_chat_end(func: Callable) -> Callable:
"""
Hook to react to the user websocket disconnect event.
Args:
func (Callable[], Any]): The disconnect hook to execute.
Returns:
Callable[], Any]: The decorated hook.
"""
config.code.on_chat_end = wrap_user_function(func, with_task=True)
return func
@trace
def author_rename(func: Callable[[str], str]) -> Callable[[str], str]:
"""
Useful to rename the author of message to display more friendly author names in the UI.
Args:
func (Callable[[str], str]): The function to be called to rename an author. Takes the original author name as parameter.
Returns:
Callable[[Any, str], Any]: The decorated function.
"""
config.code.author_rename = wrap_user_function(func)
return func
@trace
def on_stop(func: Callable) -> Callable:
"""
Hook to react to the user stopping a thread.
Args:
func (Callable[[], Any]): The stop hook to execute.
Returns:
Callable[[], Any]: The decorated stop hook.
"""
config.code.on_stop = wrap_user_function(func)
return func
def action_callback(name: str) -> Callable:
"""
Callback to call when an action is clicked in the UI.
Args:
func (Callable[[Action], Any]): The action callback to execute. First parameter is the action.
"""
def decorator(func: Callable[[Action], Any]):
config.code.action_callbacks[name] = wrap_user_function(func, with_task=True)
return func
return decorator
def on_settings_update(
func: Callable[[Dict[str, Any]], Any]
) -> Callable[[Dict[str, Any]], Any]:
"""
Hook to react to the user changing any settings.
Args:
func (Callable[], Any]): The hook to execute after settings were changed.
Returns:
Callable[], Any]: The decorated hook.
"""
config.code.on_settings_update = wrap_user_function(func, with_task=True)
return func
def sleep(duration: int):
"""
Sleep for a given duration.
Args:
duration (int): The duration in seconds.
"""
return asyncio.sleep(duration)
@dataclass()
class CopilotFunction:
name: str
args: Dict[str, Any]
def acall(self):
return context.emitter.send_call_fn(self.name, self.args)
__getattr__ = make_module_getattr(
{
"LangchainCallbackHandler": "chainlit.langchain.callbacks",
"AsyncLangchainCallbackHandler": "chainlit.langchain.callbacks",
"LlamaIndexCallbackHandler": "chainlit.llama_index.callbacks",
"HaystackAgentCallbackHandler": "chainlit.haystack.callbacks",
"instrument_openai": "chainlit.openai",
}
)
__all__ = [
"user_session",
"CopilotFunction",
"Action",
"User",
"PersistedUser",
"Audio",
"Pdf",
"Plotly",
"Image",
"Text",
"Avatar",
"Pyplot",
"File",
"Task",
"TaskList",
"TaskStatus",
"Video",
"ChatSettings",
"input_widget",
"Message",
"ErrorMessage",
"AskUserMessage",
"AskActionMessage",
"AskFileMessage",
"Step",
"step",
"ChatGeneration",
"CompletionGeneration",
"GenerationMessage",
"on_logout",
"on_chat_start",
"on_chat_end",
"on_chat_resume",
"on_stop",
"action_callback",
"author_rename",
"on_settings_update",
"password_auth_callback",
"header_auth_callback",
"sleep",
"run_sync",
"make_async",
"cache",
"context",
"LangchainCallbackHandler",
"AsyncLangchainCallbackHandler",
"LlamaIndexCallbackHandler",
"HaystackAgentCallbackHandler",
"instrument_openai",
]
def __dir__():
return __all__