File size: 11,178 Bytes
87337b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#
#
# Agora Real Time Engagement
# Created by Wei Hu in 2024-05.
# Copyright (c) 2024 Agora IO. All rights reserved.
#
#
from ten import (
    Extension,
    TenEnv,
    Cmd,
    Data,
    StatusCode,
    CmdResult,
)
import queue, threading
from datetime import datetime

PROPERTY_CHAT_MEMORY_TOKEN_LIMIT = "chat_memory_token_limit"
PROPERTY_GREETING = "greeting"

TASK_TYPE_CHAT_REQUEST = "chat_request"
TASK_TYPE_GREETING = "greeting"


class LlamaIndexExtension(Extension):
    def __init__(self, name: str):
        super().__init__(name)
        self.queue = queue.Queue()
        self.thread = None
        self.stop = False

        self.outdate_ts = datetime.now()
        self.outdate_ts_lock = threading.Lock()

        self.collection_name = ""
        self.chat_memory_token_limit = 3000
        self.chat_memory = None

    def _send_text_data(self, ten: TenEnv, text: str, end_of_segment: bool):
        try:
            output_data = Data.create("text_data")
            output_data.set_property_string("text", text)
            output_data.set_property_bool("end_of_segment", end_of_segment)
            ten.send_data(output_data)
            ten.log_info(f"text [{text}] end_of_segment {end_of_segment} sent")
        except Exception as err:
            ten.log_info(
                f"text [{text}] end_of_segment {end_of_segment} send failed, err {err}"
            )

    def on_start(self, ten: TenEnv) -> None:
        ten.log_info("on_start")

        greeting = None
        try:
            greeting = ten.get_property_string(PROPERTY_GREETING)
        except Exception as err:
            ten.log_warn(f"get {PROPERTY_GREETING} property failed, err: {err}")

        try:
            self.chat_memory_token_limit = ten.get_property_int(
                PROPERTY_CHAT_MEMORY_TOKEN_LIMIT
            )
        except Exception as err:
            ten.log_warn(
                f"get {PROPERTY_CHAT_MEMORY_TOKEN_LIMIT} property failed, err: {err}"
            )

        self.thread = threading.Thread(target=self.async_handle, args=[ten])
        self.thread.start()

        # enable chat memory
        from llama_index.core.storage.chat_store import SimpleChatStore
        from llama_index.core.memory import ChatMemoryBuffer

        self.chat_memory = ChatMemoryBuffer.from_defaults(
            token_limit=self.chat_memory_token_limit,
            chat_store=SimpleChatStore(),
        )

        # Send greeting if available
        if greeting is not None:
            self._send_text_data(ten, greeting, True)

        ten.on_start_done()

    def on_stop(self, ten: TenEnv) -> None:
        ten.log_info("on_stop")

        self.stop = True
        self.flush()
        self.queue.put(None)
        if self.thread is not None:
            self.thread.join()
            self.thread = None
        self.chat_memory = None

        ten.on_stop_done()

    def on_cmd(self, ten: TenEnv, cmd: Cmd) -> None:

        cmd_name = cmd.get_name()
        ten.log_info("on_cmd {cmd_name}")
        if cmd_name == "file_chunked":
            coll = cmd.get_property_string("collection")

            # only update selected collection if empty
            if len(self.collection_name) == 0:
                ten.log_info(
                    f"collection for querying has been updated from {self.collection_name} to {coll}"
                )
                self.collection_name = coll
            else:
                ten.log_info(
                    f"new collection {coll} incoming but won't change current collection_name {self.collection_name}"
                )

            # notify user
            file_chunked_text = "Your document has been processed. You can now start asking questions about your document. "
            # self._send_text_data(ten, file_chunked_text, True)
            self.queue.put((file_chunked_text, datetime.now(), TASK_TYPE_GREETING))
        elif cmd_name == "file_chunk":
            self.collection_name = ""  # clear current collection

            # notify user
            file_chunk_text = "Your document has been received. Please wait a moment while we process it for you.  "
            # self._send_text_data(ten, file_chunk_text, True)
            self.queue.put((file_chunk_text, datetime.now(), TASK_TYPE_GREETING))
        elif cmd_name == "update_querying_collection":
            coll = cmd.get_property_string("collection")
            ten.log_info(
                f"collection for querying has been updated from {self.collection_name} to {coll}"
            )
            self.collection_name = coll

            # notify user
            update_querying_collection_text = "Your document has been updated. "
            if len(self.collection_name) > 0:
                update_querying_collection_text += (
                    "You can now start asking questions about your document. "
                )
            # self._send_text_data(ten, update_querying_collection_text, True)
            self.queue.put(
                (update_querying_collection_text, datetime.now(), TASK_TYPE_GREETING)
            )

        elif cmd_name == "flush":
            self.flush()
            ten.send_cmd(Cmd.create("flush"), None)

        cmd_result = CmdResult.create(StatusCode.OK)
        cmd_result.set_property_string("detail", "ok")
        ten.return_result(cmd_result, cmd)

    def on_data(self, ten: TenEnv, data: Data) -> None:
        is_final = data.get_property_bool("is_final")
        if not is_final:
            ten.log_info("on_data ignore non final")
            return

        inputText = data.get_property_string("text")
        if len(inputText) == 0:
            ten.log_info("on_data ignore empty text")
            return

        ts = datetime.now()

        ten.log_info("on_data text [%s], ts [%s]", inputText, ts)
        self.queue.put((inputText, ts, TASK_TYPE_CHAT_REQUEST))

    def async_handle(self, ten: TenEnv):
        ten.log_info("async_handle started")
        while not self.stop:
            try:
                value = self.queue.get()
                if value is None:
                    break
                input_text, ts, task_type = value

                if ts < self.get_outdated_ts():
                    ten.log_info(
                        f"text [{input_text}] ts [{ts}] task_type [{task_type}] dropped due to outdated"
                    )
                    continue

                if task_type == TASK_TYPE_GREETING:
                    # send greeting text directly
                    self._send_text_data(ten, input_text, True)
                    continue

                ten.log_info("process input text [%s] ts [%s]", input_text, ts)

                # lazy import packages which requires long time to load
                from .llama_llm import LlamaLLM
                from .llama_retriever import LlamaRetriever

                # prepare chat engine
                chat_engine = None
                if len(self.collection_name) > 0:
                    from llama_index.core.chat_engine import ContextChatEngine

                    chat_engine = ContextChatEngine.from_defaults(
                        llm=LlamaLLM(ten=ten),
                        retriever=LlamaRetriever(ten=ten, coll=self.collection_name),
                        memory=self.chat_memory,
                        system_prompt=(
                            # "You are an expert Q&A system that is trusted around the world.\n"
                            "You are a voice assistant who talks in a conversational way and can chat with me like my friends. \n"
                            "I will speak to you in English or Chinese, and you will answer in the corrected and improved version of my text with the language I use. \n"
                            "Don’t talk like a robot, instead I would like you to talk like a real human with emotions. \n"
                            "I will use your answer for text-to-speech, so don’t return me any meaningless characters. \n"
                            "I want you to be helpful, when I’m asking you for advice, give me precise, practical and useful advice instead of being vague. \n"
                            "When giving me a list of options, express the options in a narrative way instead of bullet points.\n"
                            "Always answer the query using the provided context information, "
                            "and not prior knowledge.\n"
                            "Some rules to follow:\n"
                            "1. Never directly reference the given context in your answer.\n"
                            "2. Avoid statements like 'Based on the context, ...' or "
                            "'The context information ...' or anything along "
                            "those lines."
                        ),
                    )
                else:
                    from llama_index.core.chat_engine import SimpleChatEngine

                    chat_engine = SimpleChatEngine.from_defaults(
                        llm=LlamaLLM(ten=ten),
                        system_prompt=(
                            "You are a voice assistant who talks in a conversational way and can chat with me like my friends. \n"
                            "I will speak to you in English or Chinese, and you will answer in the corrected and improved version of my text with the language I use. \n"
                            "Don’t talk like a robot, instead I would like you to talk like a real human with emotions. \n"
                            "I will use your answer for text-to-speech, so don’t return me any meaningless characters. \n"
                            "I want you to be helpful, when I’m asking you for advice, give me precise, practical and useful advice instead of being vague. \n"
                            "When giving me a list of options, express the options in a narrative way instead of bullet points.\n"
                        ),
                        memory=self.chat_memory,
                    )

                resp = chat_engine.stream_chat(input_text)
                for cur_token in resp.response_gen:
                    if self.stop:
                        break
                    if ts < self.get_outdated_ts():
                        ten.log_info(
                            "stream_chat coming responses dropped due to outdated for input text [%s] ts [%s] ",
                            input_text,
                            ts,
                        )
                        break
                    text = str(cur_token)

                    # send out
                    self._send_text_data(ten, text, False)

                # send out end_of_segment
                self._send_text_data(ten, "", True)
            except Exception as e:
                ten.log_error(str(e))
        ten.log_info("async_handle stoped")

    def flush(self):
        with self.outdate_ts_lock:
            self.outdate_ts = datetime.now()

        while not self.queue.empty():
            self.queue.get()

    def get_outdated_ts(self):
        with self.outdate_ts_lock:
            return self.outdate_ts