1
+ import chainlit as cl
2
+ from codeinterpreterapi import CodeInterpreterSession
3
+ from codeinterpreterapi import File as CIFile
4
+
5
+ UPLOADED_FILES = []
6
+
7
+ @cl .action_callback ("upload_file" )
8
+ async def on_action (action ):
9
+ files = None
10
+
11
+ # Wait for the user to upload a file
12
+ while files is None :
13
+ files = await cl .AskFileMessage (
14
+ content = "Please upload a text file to begin!" , accept = ["text/csv" ]
15
+ ).send ()
16
+ # Decode the file
17
+ text_file = files [0 ]
18
+ text = text_file .content .decode ("utf-8" )
19
+
20
+ UPLOADED_FILES .append (text_file )
21
+
22
+ # Let the user know that the system is ready
23
+ await cl .Message (
24
+ content = f"`{ text_file .name } ` uploaded, it contains { len (text )} characters!"
25
+ ).send ()
26
+ await action .remove ()
27
+
28
+ @cl .on_chat_start
29
+ async def start_chat ():
30
+ actions = [
31
+ cl .Action (name = "upload_file" , value = "example_value" , description = "Upload file" )
32
+ ]
33
+
34
+ await cl .Message (
35
+ content = "Hello, How can I assist you today" , actions = actions
36
+ ).send ()
37
+
38
+ @cl .on_message
39
+ async def run_conversation (user_message : str ):
40
+ session = CodeInterpreterSession ()
41
+ await session .astart ()
42
+
43
+ files = [CIFile (name = it .name , content = it .content ) for it in UPLOADED_FILES ]
44
+
45
+
46
+ response = await session .agenerate_response (user_message , files = files )
47
+ elements = [
48
+ cl .Image (
49
+ content = file .content ,
50
+ name = f"code-interpreter-image-{ file .name } " ,
51
+ display = "inline" ,
52
+ )
53
+ for file in response .files
54
+ ]
55
+ actions = [
56
+ cl .Action (name = "upload_file" , value = "example_value" , description = "Upload file" )
57
+ ]
58
+ await cl .Message (
59
+ content = response .content ,
60
+ elements = elements ,
61
+ actions = actions ,
62
+ ).send ()
63
+
64
+ await session .astop ()
0 commit comments