Skip to content

Commit b1ec575

Browse files
fridayLCaralHsi
andauthored
feat: add further questions for dialogue (#236)
* feat: add further questions for * fix: remove print * feat: add stream for further question --------- Co-authored-by: CaralHsi <[email protected]>
1 parent 1718b64 commit b1ec575

File tree

4 files changed

+92
-32
lines changed

4 files changed

+92
-32
lines changed

src/memos/api/product_models.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,4 @@ class SuggestionRequest(BaseRequest):
161161

162162
user_id: str = Field(..., description="User ID")
163163
language: Literal["zh", "en"] = Field("zh", description="Language for suggestions")
164+
message: list[MessageDict] | None = Field(None, description="List of messages to store.")

src/memos/api/routers/product_router.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,9 @@ def get_suggestion_queries_post(suggestion_req: SuggestionRequest):
148148
try:
149149
mos_product = get_mos_product_instance()
150150
suggestions = mos_product.get_suggestion_query(
151-
user_id=suggestion_req.user_id, language=suggestion_req.language
151+
user_id=suggestion_req.user_id,
152+
language=suggestion_req.language,
153+
message=suggestion_req.message,
152154
)
153155
return SuggestionResponse(
154156
message="Suggestions retrieved successfully", data={"query": suggestions}

src/memos/mem_os/product.py

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,13 @@
3636
from memos.memories.textual.item import (
3737
TextualMemoryItem,
3838
)
39-
from memos.templates.mos_prompts import MEMOS_PRODUCT_BASE_PROMPT, MEMOS_PRODUCT_ENHANCE_PROMPT
39+
from memos.templates.mos_prompts import (
40+
FURTHER_SUGGESTION_PROMPT,
41+
MEMOS_PRODUCT_BASE_PROMPT,
42+
MEMOS_PRODUCT_ENHANCE_PROMPT,
43+
SUGGESTION_QUERY_PROMPT_EN,
44+
SUGGESTION_QUERY_PROMPT_ZH,
45+
)
4046
from memos.types import MessageList
4147

4248

@@ -641,7 +647,23 @@ def user_register(
641647
except Exception as e:
642648
return {"status": "error", "message": f"Failed to register user: {e!s}"}
643649

644-
def get_suggestion_query(self, user_id: str, language: str = "zh") -> list[str]:
650+
def _get_further_suggestion(self, message: MessageList | None = None) -> list[str]:
651+
"""Get further suggestion prompt."""
652+
try:
653+
dialogue_info = "\n".join([f"{msg['role']}: {msg['content']}" for msg in message[-2:]])
654+
further_suggestion_prompt = FURTHER_SUGGESTION_PROMPT.format(dialogue=dialogue_info)
655+
message_list = [{"role": "system", "content": further_suggestion_prompt}]
656+
response = self.chat_llm.generate(message_list)
657+
clean_response = clean_json_response(response)
658+
response_json = json.loads(clean_response)
659+
return response_json["query"]
660+
except Exception as e:
661+
logger.error(f"Error getting further suggestion: {e}", exc_info=True)
662+
return []
663+
664+
def get_suggestion_query(
665+
self, user_id: str, language: str = "zh", message: MessageList | None = None
666+
) -> list[str]:
645667
"""Get suggestion query from LLM.
646668
Args:
647669
user_id (str): User ID.
@@ -650,37 +672,13 @@ def get_suggestion_query(self, user_id: str, language: str = "zh") -> list[str]:
650672
Returns:
651673
list[str]: The suggestion query list.
652674
"""
653-
675+
if message:
676+
further_suggestion = self._get_further_suggestion(message)
677+
return further_suggestion
654678
if language == "zh":
655-
suggestion_prompt = """
656-
你是一个有用的助手,可以帮助用户生成建议查询。
657-
我将获取用户最近的一些记忆,
658-
你应该生成一些建议查询,这些查询应该是用户想要查询的内容,
659-
用户最近的记忆是:
660-
{memories}
661-
请生成3个建议查询用中文,
662-
输出应该是json格式,键是"query",值是一个建议查询列表。
663-
664-
示例:
665-
{{
666-
"query": ["查询1", "查询2", "查询3"]
667-
}}
668-
"""
679+
suggestion_prompt = SUGGESTION_QUERY_PROMPT_ZH
669680
else: # English
670-
suggestion_prompt = """
671-
You are a helpful assistant that can help users to generate suggestion query.
672-
I will get some user recently memories,
673-
you should generate some suggestion query, the query should be user what to query,
674-
user recently memories is:
675-
{memories}
676-
if the user recently memories is empty, please generate 3 suggestion query in English,
677-
output should be a json format, the key is "query", the value is a list of suggestion query.
678-
679-
example:
680-
{{
681-
"query": ["query1", "query2", "query3"]
682-
}}
683-
"""
681+
suggestion_prompt = SUGGESTION_QUERY_PROMPT_EN
684682
text_mem_result = super().search("my recently memories", user_id=user_id, top_k=3)[
685683
"text_mem"
686684
]
@@ -844,6 +842,11 @@ def chat_with_references(
844842
total_time = round(float(time_end - time_start), 1)
845843

846844
yield f"data: {json.dumps({'type': 'time', 'data': {'total_time': total_time, 'speed_improvement': f'{speed_improvement}%'}})}\n\n"
845+
# get further suggestion
846+
current_messages.append({"role": "assistant", "content": full_response})
847+
further_suggestion = self._get_further_suggestion(current_messages)
848+
logger.info(f"further_suggestion: {further_suggestion}")
849+
yield f"data: {json.dumps({'type': 'suggestion', 'data': further_suggestion})}\n\n"
847850
yield f"data: {json.dumps({'type': 'end'})}\n\n"
848851

849852
logger.info(f"user_id: {user_id}, cube_id: {cube_id}, current_messages: {current_messages}")

src/memos/templates/mos_prompts.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,57 @@
185185
{dialogue}
186186
Current question: {query}
187187
Answer:"""
188+
189+
SUGGESTION_QUERY_PROMPT_ZH = """
190+
你是一个有用的助手,可以帮助用户生成建议查询。
191+
我将获取用户最近的一些记忆,
192+
你应该生成一些建议查询,这些查询应该是用户想要查询的内容,
193+
用户最近的记忆是:
194+
{memories}
195+
请生成3个建议查询用中文,如果用户最近的记忆是空,请直接随机生成3个建议查询用中文,不要有多余解释。
196+
输出应该是json格式,键是"query",值是一个建议查询列表。
197+
198+
示例:
199+
{{
200+
"query": ["查询1", "查询2", "查询3"]
201+
}}
202+
"""
203+
204+
SUGGESTION_QUERY_PROMPT_EN = """
205+
You are a helpful assistant that can help users to generate suggestion query.
206+
I will get some user recently memories,
207+
you should generate some suggestion query, the query should be user what to query,
208+
user recently memories is:
209+
{memories}
210+
if the user recently memories is empty, please generate 3 suggestion query in English,do not generate any other text,
211+
output should be a json format, the key is "query", the value is a list of suggestion query.
212+
213+
example:
214+
{{
215+
"query": ["query1", "query2", "query3"]
216+
}}
217+
"""
218+
219+
FURTHER_SUGGESTION_PROMPT = """
220+
You are a helpful assistant.
221+
You are given a dialogue between a user and a assistant.
222+
You need to suggest a further question based on the dialogue.
223+
Requirements:
224+
1. The further question should be related to the dialogue.
225+
2. The further question should be concise and accurate.
226+
3. You must return ONLY a valid JSON object. Do not include any other text, explanations, or formatting.
227+
the lastest dialogue is:
228+
{dialogue}
229+
output should be a json format, the key is "query", the value is a list of suggestion query.
230+
if dialogue is chinese,the quersuggestion query should be in chinese,if dialogue is english,the suggestion query should be in english.
231+
please do not generate any other text.
232+
233+
example english:
234+
{{
235+
"query": ["query1", "query2", "query3"]
236+
}}
237+
example chinese:
238+
{{
239+
"query": ["问题1", "问题2", "问题3"]
240+
}}
241+
"""

0 commit comments

Comments
 (0)