2024-08-15 09:17:36 +08:00
#
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
2024-09-04 10:36:15 +08:00
import json
2024-09-11 19:49:18 +08:00
import re
2024-09-12 17:51:20 +08:00
import traceback
2024-08-15 09:17:36 +08:00
from copy import deepcopy
2024-12-09 12:38:04 +08:00
2025-03-25 10:00:10 +08:00
import trio
from flask import Response , request
from flask_login import current_user , login_required
2024-09-04 10:36:15 +08:00
2025-03-25 10:00:10 +08:00
from api import settings
2024-09-04 10:36:15 +08:00
from api . db import LLMType
2025-03-25 10:00:10 +08:00
from api . db . db_models import APIToken
from api . db . services . conversation_service import ConversationService , structure_answer
from api . db . services . dialog_service import DialogService , ask , chat
2024-09-11 19:49:18 +08:00
from api . db . services . knowledgebase_service import KnowledgebaseService
2025-01-10 19:06:59 +08:00
from api . db . services . llm_service import LLMBundle , TenantService
2025-03-25 10:00:10 +08:00
from api . db . services . user_service import UserTenantService
from api . utils . api_utils import get_data_error_result , get_json_result , server_error_response , validate_request
2025-01-22 19:43:14 +08:00
from graphrag . general . mind_map_extractor import MindMapExtractor
2025-02-26 15:40:52 +08:00
from rag . app . tag import label_question
2024-08-15 09:17:36 +08:00
2025-01-10 19:06:59 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /set " , methods = [ " POST " ] ) # noqa: F821
2024-08-15 09:17:36 +08:00
@login_required
def set_conversation ( ) :
req = request . json
conv_id = req . get ( " conversation_id " )
2024-09-27 18:20:19 +08:00
is_new = req . get ( " is_new " )
Fix: value too long error for chat name (#7697)
### What problem does this PR solve?
Hello, when I input a very long line in the chat input box, it will fail
with following error:
```
2025-05-17 16:11:26,004 ERROR 182558 value too long for type character varying(255)
Traceback (most recent call last):
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3291, in execute_sql
cursor.execute(sql, params or ())
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(255)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/var/home/sfc/Projects/ragflow/api/apps/conversation_app.py", line 68, in set_conversation
ConversationService.save(**conv)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3128, in inner
return fn(*args, **kwargs)
File "/var/home/sfc/Projects/ragflow/api/db/services/common_service.py", line 145, in save
return cls.save_n(**kwargs)
File "/var/home/sfc/Projects/ragflow/api/db/services/common_service.py", line 139, in save_n
sample_obj = cls.model(**kwargs).save(force_insert=True)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 6923, in save
pk = self.insert(**field_dict).execute()
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2011, in inner
return method(self, database, *args, **kwargs)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2082, in execute
return self._execute(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2887, in _execute
return super(Insert, self)._execute(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2598, in _execute
cursor = self.execute_returning(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2605, in execute_returning
cursor = database.execute(self)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3299, in execute
return self.execute_sql(sql, params)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3289, in execute_sql
with __exception_wrapper__:
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3059, in __exit__
reraise(new_type, new_type(exc_value, *exc_args), traceback)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 192, in reraise
raise value.with_traceback(tb)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3291, in execute_sql
cursor.execute(sql, params or ())
peewee.DataError: value too long for type character varying(255)
```
This PR fix it by truncate the `name` field in the `set_conversation`
method in the `conversation_app.py`.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-05-19 10:25:41 +08:00
name = req . get ( " name " , " New conversation " )
if len ( name ) > 255 :
name = name [ 0 : 255 ]
2024-09-27 18:20:19 +08:00
del req [ " is_new " ]
if not is_new :
2024-08-15 09:17:36 +08:00
del req [ " conversation_id " ]
try :
if not ConversationService . update_by_id ( conv_id , req ) :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2024-08-15 09:17:36 +08:00
e , conv = ConversationService . get_by_id ( conv_id )
if not e :
2025-03-25 10:00:10 +08:00
return get_data_error_result ( message = " Fail to update a conversation! " )
2024-08-15 09:17:36 +08:00
conv = conv . to_dict ( )
return get_json_result ( data = conv )
except Exception as e :
return server_error_response ( e )
try :
e , dia = DialogService . get_by_id ( req [ " dialog_id " ] )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Dialog not found " )
Fix: value too long error for chat name (#7697)
### What problem does this PR solve?
Hello, when I input a very long line in the chat input box, it will fail
with following error:
```
2025-05-17 16:11:26,004 ERROR 182558 value too long for type character varying(255)
Traceback (most recent call last):
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3291, in execute_sql
cursor.execute(sql, params or ())
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(255)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/var/home/sfc/Projects/ragflow/api/apps/conversation_app.py", line 68, in set_conversation
ConversationService.save(**conv)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3128, in inner
return fn(*args, **kwargs)
File "/var/home/sfc/Projects/ragflow/api/db/services/common_service.py", line 145, in save
return cls.save_n(**kwargs)
File "/var/home/sfc/Projects/ragflow/api/db/services/common_service.py", line 139, in save_n
sample_obj = cls.model(**kwargs).save(force_insert=True)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 6923, in save
pk = self.insert(**field_dict).execute()
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2011, in inner
return method(self, database, *args, **kwargs)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2082, in execute
return self._execute(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2887, in _execute
return super(Insert, self)._execute(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2598, in _execute
cursor = self.execute_returning(database)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 2605, in execute_returning
cursor = database.execute(self)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3299, in execute
return self.execute_sql(sql, params)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3289, in execute_sql
with __exception_wrapper__:
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3059, in __exit__
reraise(new_type, new_type(exc_value, *exc_args), traceback)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 192, in reraise
raise value.with_traceback(tb)
File "/var/home/sfc/Projects/ragflow/.venv/lib/python3.10/site-packages/peewee.py", line 3291, in execute_sql
cursor.execute(sql, params or ())
peewee.DataError: value too long for type character varying(255)
```
This PR fix it by truncate the `name` field in the `set_conversation`
method in the `conversation_app.py`.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-05-19 10:25:41 +08:00
conv = { " id " : conv_id , " dialog_id " : req [ " dialog_id " ] , " name " : name , " message " : [ { " role " : " assistant " , " content " : dia . prompt_config [ " prologue " ] } ] }
2024-08-15 09:17:36 +08:00
ConversationService . save ( * * conv )
return get_json_result ( data = conv )
except Exception as e :
return server_error_response ( e )
2025-03-25 10:00:10 +08:00
@manager.route ( " /get " , methods = [ " GET " ] ) # noqa: F821
2024-08-15 09:17:36 +08:00
@login_required
def get ( ) :
conv_id = request . args [ " conversation_id " ]
try :
e , conv = ConversationService . get_by_id ( conv_id )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2024-09-04 10:36:15 +08:00
tenants = UserTenantService . query ( user_id = current_user . id )
2025-03-25 10:00:10 +08:00
avatar = None
2024-09-04 10:36:15 +08:00
for tenant in tenants :
2024-12-17 16:29:35 +07:00
dialog = DialogService . query ( tenant_id = tenant . tenant_id , id = conv . dialog_id )
2025-03-25 10:00:10 +08:00
if dialog and len ( dialog ) > 0 :
2024-12-17 16:29:35 +07:00
avatar = dialog [ 0 ] . icon
2024-09-04 10:36:15 +08:00
break
else :
2025-03-25 10:00:10 +08:00
return get_json_result ( data = False , message = " Only owner of conversation authorized for this operation. " , code = settings . RetCode . OPERATING_ERROR )
2024-12-10 17:03:24 +08:00
def get_value ( d , k1 , k2 ) :
return d . get ( k1 , d . get ( k2 ) )
for ref in conv . reference :
2024-12-11 19:23:59 +08:00
if isinstance ( ref , list ) :
continue
2025-03-25 10:00:10 +08:00
ref [ " chunks " ] = [
{
" id " : get_value ( ck , " chunk_id " , " id " ) ,
" content " : get_value ( ck , " content " , " content_with_weight " ) ,
" document_id " : get_value ( ck , " doc_id " , " document_id " ) ,
" document_name " : get_value ( ck , " docnm_kwd " , " document_name " ) ,
" dataset_id " : get_value ( ck , " kb_id " , " dataset_id " ) ,
" image_id " : get_value ( ck , " image_id " , " img_id " ) ,
" positions " : get_value ( ck , " positions " , " position_int " ) ,
2025-05-15 11:03:05 +08:00
" doc_type " : get_value ( ck , " doc_type " , " doc_type_kwd " ) ,
2025-03-25 10:00:10 +08:00
}
for ck in ref . get ( " chunks " , [ ] )
]
2024-12-10 17:03:24 +08:00
2024-08-15 09:17:36 +08:00
conv = conv . to_dict ( )
2025-03-25 10:00:10 +08:00
conv [ " avatar " ] = avatar
2024-08-15 09:17:36 +08:00
return get_json_result ( data = conv )
except Exception as e :
return server_error_response ( e )
2025-03-17 16:02:53 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /getsse/<dialog_id> " , methods = [ " GET " ] ) # type: ignore # noqa: F821
def getsse ( dialog_id ) :
token = request . headers . get ( " Authorization " ) . split ( )
2024-12-17 16:29:35 +07:00
if len ( token ) != 2 :
return get_data_error_result ( message = ' Authorization is not valid! " ' )
token = token [ 1 ]
objs = APIToken . query ( beta = token )
if not objs :
2024-12-26 16:08:17 +08:00
return get_data_error_result ( message = ' Authentication error: API key is invalid! " ' )
2024-12-17 16:29:35 +07:00
try :
e , conv = DialogService . get_by_id ( dialog_id )
if not e :
return get_data_error_result ( message = " Dialog not found! " )
conv = conv . to_dict ( )
2025-03-25 10:00:10 +08:00
conv [ " avatar " ] = conv [ " icon " ]
2024-12-17 16:29:35 +07:00
del conv [ " icon " ]
return get_json_result ( data = conv )
except Exception as e :
return server_error_response ( e )
2024-08-15 09:17:36 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /rm " , methods = [ " POST " ] ) # noqa: F821
2024-08-15 09:17:36 +08:00
@login_required
def rm ( ) :
conv_ids = request . json [ " conversation_ids " ]
try :
for cid in conv_ids :
2024-09-04 10:36:15 +08:00
exist , conv = ConversationService . get_by_id ( cid )
if not exist :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2024-09-04 10:36:15 +08:00
tenants = UserTenantService . query ( user_id = current_user . id )
for tenant in tenants :
if DialogService . query ( tenant_id = tenant . tenant_id , id = conv . dialog_id ) :
break
else :
2025-03-25 10:00:10 +08:00
return get_json_result ( data = False , message = " Only owner of conversation authorized for this operation. " , code = settings . RetCode . OPERATING_ERROR )
2024-08-15 09:17:36 +08:00
ConversationService . delete_by_id ( cid )
return get_json_result ( data = True )
except Exception as e :
return server_error_response ( e )
2025-03-25 10:00:10 +08:00
@manager.route ( " /list " , methods = [ " GET " ] ) # noqa: F821
2024-08-15 09:17:36 +08:00
@login_required
def list_convsersation ( ) :
dialog_id = request . args [ " dialog_id " ]
try :
2024-09-04 10:36:15 +08:00
if not DialogService . query ( tenant_id = current_user . id , id = dialog_id ) :
2025-03-25 10:00:10 +08:00
return get_json_result ( data = False , message = " Only owner of dialog authorized for this operation. " , code = settings . RetCode . OPERATING_ERROR )
convs = ConversationService . query ( dialog_id = dialog_id , order_by = ConversationService . model . create_time , reverse = True )
2024-12-10 17:03:24 +08:00
2024-08-15 09:17:36 +08:00
convs = [ d . to_dict ( ) for d in convs ]
return get_json_result ( data = convs )
except Exception as e :
return server_error_response ( e )
2025-03-25 10:00:10 +08:00
@manager.route ( " /completion " , methods = [ " POST " ] ) # noqa: F821
2024-08-15 09:17:36 +08:00
@login_required
2024-09-04 10:36:15 +08:00
@validate_request ( " conversation_id " , " messages " )
2024-08-15 09:17:36 +08:00
def completion ( ) :
req = request . json
msg = [ ]
for m in req [ " messages " ] :
if m [ " role " ] == " system " :
continue
if m [ " role " ] == " assistant " and not msg :
continue
2024-08-26 12:05:15 +08:00
msg . append ( m )
message_id = msg [ - 1 ] . get ( " id " )
2024-08-15 09:17:36 +08:00
try :
e , conv = ConversationService . get_by_id ( req [ " conversation_id " ] )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2024-08-29 18:32:58 +08:00
conv . message = deepcopy ( req [ " messages " ] )
2024-08-15 09:17:36 +08:00
e , dia = DialogService . get_by_id ( conv . dialog_id )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Dialog not found! " )
2024-08-15 09:17:36 +08:00
del req [ " conversation_id " ]
del req [ " messages " ]
if not conv . reference :
conv . reference = [ ]
2024-12-10 17:03:24 +08:00
else :
2025-03-25 10:00:10 +08:00
2024-12-10 17:03:24 +08:00
def get_value ( d , k1 , k2 ) :
return d . get ( k1 , d . get ( k2 ) )
for ref in conv . reference :
2024-12-12 19:00:34 +08:00
if isinstance ( ref , list ) :
continue
2025-03-25 10:00:10 +08:00
ref [ " chunks " ] = [
{
" id " : get_value ( ck , " chunk_id " , " id " ) ,
" content " : get_value ( ck , " content " , " content_with_weight " ) ,
" document_id " : get_value ( ck , " doc_id " , " document_id " ) ,
" document_name " : get_value ( ck , " docnm_kwd " , " document_name " ) ,
" dataset_id " : get_value ( ck , " kb_id " , " dataset_id " ) ,
" image_id " : get_value ( ck , " image_id " , " img_id " ) ,
" positions " : get_value ( ck , " positions " , " position_int " ) ,
2025-05-13 19:30:05 +08:00
" doc_type " : get_value ( ck , " doc_type_kwd " , " doc_type_kwd " ) ,
2025-03-25 10:00:10 +08:00
}
for ck in ref . get ( " chunks " , [ ] )
]
2024-08-15 09:17:36 +08:00
2024-12-10 17:03:24 +08:00
if not conv . reference :
conv . reference = [ ]
conv . reference . append ( { " chunks " : [ ] , " doc_aggs " : [ ] } )
2025-03-25 10:00:10 +08:00
2024-08-15 09:17:36 +08:00
def stream ( ) :
nonlocal dia , msg , req , conv
try :
for ans in chat ( dia , msg , True , * * req ) :
2024-12-10 17:03:24 +08:00
ans = structure_answer ( conv , ans , message_id , conv . id )
2024-11-05 11:02:31 +08:00
yield " data: " + json . dumps ( { " code " : 0 , " message " : " " , " data " : ans } , ensure_ascii = False ) + " \n \n "
2024-08-15 09:17:36 +08:00
ConversationService . update_by_id ( conv . id , conv . to_dict ( ) )
except Exception as e :
2024-10-22 11:38:37 +08:00
traceback . print_exc ( )
2025-03-25 10:00:10 +08:00
yield " data: " + json . dumps ( { " code " : 500 , " message " : str ( e ) , " data " : { " answer " : " **ERROR**: " + str ( e ) , " reference " : [ ] } } , ensure_ascii = False ) + " \n \n "
2024-11-05 11:02:31 +08:00
yield " data: " + json . dumps ( { " code " : 0 , " message " : " " , " data " : True } , ensure_ascii = False ) + " \n \n "
2024-08-15 09:17:36 +08:00
if req . get ( " stream " , True ) :
resp = Response ( stream ( ) , mimetype = " text/event-stream " )
resp . headers . add_header ( " Cache-control " , " no-cache " )
resp . headers . add_header ( " Connection " , " keep-alive " )
resp . headers . add_header ( " X-Accel-Buffering " , " no " )
resp . headers . add_header ( " Content-Type " , " text/event-stream; charset=utf-8 " )
return resp
else :
answer = None
for ans in chat ( dia , msg , * * req ) :
2024-12-10 17:03:24 +08:00
answer = structure_answer ( conv , ans , message_id , req [ " conversation_id " ] )
2024-08-15 09:17:36 +08:00
ConversationService . update_by_id ( conv . id , conv . to_dict ( ) )
break
return get_json_result ( data = answer )
except Exception as e :
return server_error_response ( e )
2024-08-26 12:05:15 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /tts " , methods = [ " POST " ] ) # noqa: F821
2024-08-27 13:15:54 +08:00
@login_required
def tts ( ) :
req = request . json
text = req [ " text " ]
2024-09-04 10:36:15 +08:00
2024-10-16 16:10:24 +08:00
tenants = TenantService . get_info_by ( current_user . id )
2024-08-27 13:15:54 +08:00
if not tenants :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Tenant not found! " )
2024-09-04 10:36:15 +08:00
2024-08-27 13:15:54 +08:00
tts_id = tenants [ 0 ] [ " tts_id " ]
if not tts_id :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " No default TTS model is set " )
2024-09-04 10:36:15 +08:00
2024-08-27 13:15:54 +08:00
tts_mdl = LLMBundle ( tenants [ 0 ] [ " tenant_id " ] , LLMType . TTS , tts_id )
2024-09-04 10:36:15 +08:00
2024-08-27 13:15:54 +08:00
def stream_audio ( ) :
try :
2024-09-19 19:15:16 +08:00
for txt in re . split ( r " [,。/《》?;:! \ n \ r:;]+ " , text ) :
for chunk in tts_mdl . tts ( txt ) :
yield chunk
2024-08-27 13:15:54 +08:00
except Exception as e :
2025-03-25 10:00:10 +08:00
yield ( " data: " + json . dumps ( { " code " : 500 , " message " : str ( e ) , " data " : { " answer " : " **ERROR**: " + str ( e ) } } , ensure_ascii = False ) ) . encode ( " utf-8 " )
2024-08-27 13:15:54 +08:00
2024-09-04 10:36:15 +08:00
resp = Response ( stream_audio ( ) , mimetype = " audio/mpeg " )
2024-08-27 13:15:54 +08:00
resp . headers . add_header ( " Cache-Control " , " no-cache " )
resp . headers . add_header ( " Connection " , " keep-alive " )
resp . headers . add_header ( " X-Accel-Buffering " , " no " )
2024-09-04 10:36:15 +08:00
2024-08-27 13:15:54 +08:00
return resp
2024-09-04 10:36:15 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /delete_msg " , methods = [ " POST " ] ) # noqa: F821
2024-08-26 12:05:15 +08:00
@login_required
@validate_request ( " conversation_id " , " message_id " )
2024-08-26 12:58:19 +08:00
def delete_msg ( ) :
2024-08-26 12:05:15 +08:00
req = request . json
e , conv = ConversationService . get_by_id ( req [ " conversation_id " ] )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2024-08-26 12:05:15 +08:00
conv = conv . to_dict ( )
for i , msg in enumerate ( conv [ " message " ] ) :
if req [ " message_id " ] != msg . get ( " id " , " " ) :
continue
2024-09-04 10:36:15 +08:00
assert conv [ " message " ] [ i + 1 ] [ " id " ] == req [ " message_id " ]
2024-08-26 12:05:15 +08:00
conv [ " message " ] . pop ( i )
conv [ " message " ] . pop ( i )
2024-09-04 10:36:15 +08:00
conv [ " reference " ] . pop ( max ( 0 , i / / 2 - 1 ) )
2024-08-26 12:05:15 +08:00
break
ConversationService . update_by_id ( conv [ " id " ] , conv )
return get_json_result ( data = conv )
2024-08-26 12:58:19 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /thumbup " , methods = [ " POST " ] ) # noqa: F821
2024-08-26 12:58:19 +08:00
@login_required
@validate_request ( " conversation_id " , " message_id " )
def thumbup ( ) :
req = request . json
e , conv = ConversationService . get_by_id ( req [ " conversation_id " ] )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Conversation not found! " )
2025-03-17 16:02:53 +08:00
up_down = req . get ( " thumbup " )
2024-08-26 12:58:19 +08:00
feedback = req . get ( " feedback " , " " )
conv = conv . to_dict ( )
for i , msg in enumerate ( conv [ " message " ] ) :
if req [ " message_id " ] == msg . get ( " id " , " " ) and msg . get ( " role " , " " ) == " assistant " :
2024-08-26 13:27:41 +08:00
if up_down :
msg [ " thumbup " ] = True
2024-12-08 14:21:12 +08:00
if " feedback " in msg :
del msg [ " feedback " ]
2024-08-26 12:58:19 +08:00
else :
msg [ " thumbup " ] = False
2024-12-08 14:21:12 +08:00
if feedback :
msg [ " feedback " ] = feedback
2024-08-26 12:58:19 +08:00
break
ConversationService . update_by_id ( conv [ " id " ] , conv )
2024-08-27 13:15:54 +08:00
return get_json_result ( data = conv )
2024-09-11 19:49:18 +08:00
2025-03-25 10:00:10 +08:00
@manager.route ( " /ask " , methods = [ " POST " ] ) # noqa: F821
2024-09-11 19:49:18 +08:00
@login_required
@validate_request ( " question " , " kb_ids " )
def ask_about ( ) :
req = request . json
uid = current_user . id
2024-11-15 17:30:56 +08:00
2024-09-11 19:49:18 +08:00
def stream ( ) :
nonlocal req , uid
try :
for ans in ask ( req [ " question " ] , req [ " kb_ids " ] , uid ) :
2024-11-05 11:02:31 +08:00
yield " data: " + json . dumps ( { " code " : 0 , " message " : " " , " data " : ans } , ensure_ascii = False ) + " \n \n "
2024-09-11 19:49:18 +08:00
except Exception as e :
2025-03-25 10:00:10 +08:00
yield " data: " + json . dumps ( { " code " : 500 , " message " : str ( e ) , " data " : { " answer " : " **ERROR**: " + str ( e ) , " reference " : [ ] } } , ensure_ascii = False ) + " \n \n "
2024-11-05 11:02:31 +08:00
yield " data: " + json . dumps ( { " code " : 0 , " message " : " " , " data " : True } , ensure_ascii = False ) + " \n \n "
2024-09-11 19:49:18 +08:00
resp = Response ( stream ( ) , mimetype = " text/event-stream " )
resp . headers . add_header ( " Cache-control " , " no-cache " )
resp . headers . add_header ( " Connection " , " keep-alive " )
resp . headers . add_header ( " X-Accel-Buffering " , " no " )
resp . headers . add_header ( " Content-Type " , " text/event-stream; charset=utf-8 " )
return resp
2025-03-25 10:00:10 +08:00
@manager.route ( " /mindmap " , methods = [ " POST " ] ) # noqa: F821
2024-09-11 19:49:18 +08:00
@login_required
@validate_request ( " question " , " kb_ids " )
def mindmap ( ) :
req = request . json
kb_ids = req [ " kb_ids " ]
e , kb = KnowledgebaseService . get_by_id ( kb_ids [ 0 ] )
if not e :
2024-11-05 11:02:31 +08:00
return get_data_error_result ( message = " Knowledgebase not found! " )
2024-09-11 19:49:18 +08:00
2025-01-10 19:06:59 +08:00
embd_mdl = LLMBundle ( kb . tenant_id , LLMType . EMBEDDING , llm_name = kb . embd_id )
2024-09-11 19:49:18 +08:00
chat_mdl = LLMBundle ( current_user . id , LLMType . CHAT )
2025-01-09 17:07:21 +08:00
question = req [ " question " ]
2025-03-25 10:00:10 +08:00
ranks = settings . retrievaler . retrieval ( question , embd_mdl , kb . tenant_id , kb_ids , 1 , 12 , 0.3 , 0.3 , aggs = False , rank_feature = label_question ( question , [ kb ] ) )
2024-09-11 19:49:18 +08:00
mindmap = MindMapExtractor ( chat_mdl )
2025-03-03 18:59:49 +08:00
mind_map = trio . run ( mindmap , [ c [ " content_with_weight " ] for c in ranks [ " chunks " ] ] )
mind_map = mind_map . output
2024-09-12 17:51:20 +08:00
if " error " in mind_map :
return server_error_response ( Exception ( mind_map [ " error " ] ) )
2024-09-11 19:49:18 +08:00
return get_json_result ( data = mind_map )
2025-03-25 10:00:10 +08:00
@manager.route ( " /related_questions " , methods = [ " POST " ] ) # noqa: F821
2024-09-11 19:49:18 +08:00
@login_required
@validate_request ( " question " )
def related_questions ( ) :
req = request . json
question = req [ " question " ]
chat_mdl = LLMBundle ( current_user . id , LLMType . CHAT )
prompt = """
2025-03-25 10:00:10 +08:00
Role: You are an AI language model assistant tasked with generating 5-10 related questions based on a user’ s original query. These questions should help expand the search query scope and improve search relevance.
2024-09-11 19:49:18 +08:00
Instructions:
2025-03-25 10:00:10 +08:00
Input: You are provided with a user’ s question.
Output: Generate 5-10 alternative questions that are related to the original user question. These alternatives should help retrieve a broader range of relevant documents from a vector database.
Context: Focus on rephrasing the original question in different ways, making sure the alternative questions are diverse but still connected to the topic of the original query. Do not create overly obscure, irrelevant, or unrelated questions.
Fallback: If you cannot generate any relevant alternatives, do not return any questions.
Guidance:
1. Each alternative should be unique but still relevant to the original query.
2. Keep the phrasing clear, concise, and easy to understand.
3. Avoid overly technical jargon or specialized terms unless directly relevant.
4. Ensure that each question contributes towards improving search results by broadening the search angle, not narrowing it.
Example:
Original Question: What are the benefits of electric vehicles?
Alternative Questions:
1. How do electric vehicles impact the environment?
2. What are the advantages of owning an electric car?
3. What is the cost-effectiveness of electric vehicles?
4. How do electric vehicles compare to traditional cars in terms of fuel efficiency?
5. What are the environmental benefits of switching to electric cars?
6. How do electric vehicles help reduce carbon emissions?
7. Why are electric vehicles becoming more popular?
8. What are the long-term savings of using electric vehicles?
9. How do electric vehicles contribute to sustainability?
10. What are the key benefits of electric vehicles for consumers?
2024-09-11 19:49:18 +08:00
Reason:
2025-03-25 10:00:10 +08:00
Rephrasing the original query into multiple alternative questions helps the user explore different aspects of their search topic, improving the quality of search results.
These questions guide the search engine to provide a more comprehensive set of relevant documents.
2024-09-11 19:49:18 +08:00
"""
2025-03-25 10:00:10 +08:00
ans = chat_mdl . chat (
prompt ,
[
{
" role " : " user " ,
" content " : f """
2024-09-11 19:49:18 +08:00
Keywords: { question }
Related search terms:
2025-03-25 10:00:10 +08:00
""" ,
}
] ,
{ " temperature " : 0.9 } ,
)
2024-09-11 19:49:18 +08:00
return get_json_result ( data = [ re . sub ( r " ^[0-9] \ . " , " " , a ) for a in ans . split ( " \n " ) if re . match ( r " ^[0-9] \ . " , a ) ] )