mirror of
https://github.com/langgenius/dify.git
synced 2026-03-01 22:08:41 +08:00
Signed-off-by: majiayu000 <1835304752@qq.com> Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: NeatGuyCoding <15627489+NeatGuyCoding@users.noreply.github.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: yihong0618 <zouzou0208@gmail.com> Co-authored-by: QuantumGhost <obelisk.reg+git@gmail.com> Co-authored-by: 盐粒 Yanli <yanli@dify.ai> Co-authored-by: wangxiaolei <fatelei@gmail.com> Co-authored-by: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Co-authored-by: Cursx <33718736+Cursx@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: lif <1835304752@qq.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Asuka Minato <i@asukaminato.eu.org> Co-authored-by: fenglin <790872612@qq.com> Co-authored-by: qiaofenglin <qiaofenglin@baidu.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: TomoOkuyama <49631611+TomoOkuyama@users.noreply.github.com> Co-authored-by: Tomo Okuyama <tomo.okuyama@intersystems.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: zyssyz123 <916125788@qq.com> Co-authored-by: hj24 <mambahj24@gmail.com> Co-authored-by: Coding On Star <447357187@qq.com> Co-authored-by: CodingOnStar <hanxujiang@dify.ai> Co-authored-by: yyh <92089059+lyzno1@users.noreply.github.com> Co-authored-by: Xiangxuan Qu <fghpdf@outlook.com> Co-authored-by: fghpdf <fghpdf@users.noreply.github.com> Co-authored-by: coopercoder <whitetiger0127@163.com> Co-authored-by: zhaiguangpeng <zhaiguangpeng@didiglobal.com> Co-authored-by: Junyan Qin (Chin) <rockchinq@gmail.com> Co-authored-by: E.G <146701565+GlobalStar117@users.noreply.github.com> Co-authored-by: GlobalStar117 <GlobalStar117@users.noreply.github.com> Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: CodingOnStar <hanxujiang@dify.com> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: heyszt <270985384@qq.com> Co-authored-by: NeatGuyCoding <15627489+NeatGuyCoding@users.noreply.github.com> Co-authored-by: Yeuoly <45712896+Yeuoly@users.noreply.github.com> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: moonpanda <chuanzegao@163.com> Co-authored-by: warlocgao <warlocgao@tencent.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: KVOJJJin <jzongcode@gmail.com> Co-authored-by: eux <euxx@users.noreply.github.com> Co-authored-by: bangjiehan <bangjiehan@gmail.com> Co-authored-by: FFXN <31929997+FFXN@users.noreply.github.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: Nie Ronghua <nieronghua@sf-express.com> Co-authored-by: JQSevenMiao <141806521+JQSevenMiao@users.noreply.github.com> Co-authored-by: jiasiqi <jiasiqi3@tal.com> Co-authored-by: Seokrin Taron Sung <sungsjade@gmail.com> Co-authored-by: CrabSAMA <40541269+CrabSAMA@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: yessenia <yessenia.contact@gmail.com> Co-authored-by: Jax <anobaka@qq.com> Co-authored-by: niveshdandyan <155956228+niveshdandyan@users.noreply.github.com> Co-authored-by: OSS Contributor <oss-contributor@example.com> Co-authored-by: niveshdandyan <niveshdandyan@users.noreply.github.com> Co-authored-by: Sean Kenneth Doherty <Smaster7772@gmail.com>
188 lines
7.5 KiB
Python
188 lines
7.5 KiB
Python
import logging
|
|
from typing import Literal
|
|
|
|
from flask import request
|
|
from flask_restx import Resource
|
|
from pydantic import BaseModel, Field, TypeAdapter
|
|
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
|
|
|
|
import services
|
|
from controllers.common.schema import register_schema_models
|
|
from controllers.service_api import service_api_ns
|
|
from controllers.service_api.app.error import NotChatAppError
|
|
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
|
|
from core.app.entities.app_invoke_entities import InvokeFrom
|
|
from fields.conversation_fields import ResultResponse
|
|
from fields.message_fields import MessageInfiniteScrollPagination, MessageListItem
|
|
from libs.helper import UUIDStrOrEmpty
|
|
from models.model import App, AppMode, EndUser
|
|
from services.errors.message import (
|
|
FirstMessageNotExistsError,
|
|
MessageNotExistsError,
|
|
SuggestedQuestionsAfterAnswerDisabledError,
|
|
)
|
|
from services.message_service import MessageService
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class MessageListQuery(BaseModel):
|
|
conversation_id: UUIDStrOrEmpty
|
|
first_id: UUIDStrOrEmpty | None = None
|
|
limit: int = Field(default=20, ge=1, le=100, description="Number of messages to return")
|
|
|
|
|
|
class MessageFeedbackPayload(BaseModel):
|
|
rating: Literal["like", "dislike"] | None = Field(default=None, description="Feedback rating")
|
|
content: str | None = Field(default=None, description="Feedback content")
|
|
|
|
|
|
class FeedbackListQuery(BaseModel):
|
|
page: int = Field(default=1, ge=1, description="Page number")
|
|
limit: int = Field(default=20, ge=1, le=101, description="Number of feedbacks per page")
|
|
|
|
|
|
register_schema_models(service_api_ns, MessageListQuery, MessageFeedbackPayload, FeedbackListQuery)
|
|
|
|
|
|
@service_api_ns.route("/messages")
|
|
class MessageListApi(Resource):
|
|
@service_api_ns.expect(service_api_ns.models[MessageListQuery.__name__])
|
|
@service_api_ns.doc("list_messages")
|
|
@service_api_ns.doc(description="List messages in a conversation")
|
|
@service_api_ns.doc(
|
|
responses={
|
|
200: "Messages retrieved successfully",
|
|
401: "Unauthorized - invalid API token",
|
|
404: "Conversation or first message not found",
|
|
}
|
|
)
|
|
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
|
|
def get(self, app_model: App, end_user: EndUser):
|
|
"""List messages in a conversation.
|
|
|
|
Retrieves messages with pagination support using first_id.
|
|
"""
|
|
app_mode = AppMode.value_of(app_model.mode)
|
|
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
|
|
raise NotChatAppError()
|
|
|
|
query_args = MessageListQuery.model_validate(request.args.to_dict())
|
|
conversation_id = str(query_args.conversation_id)
|
|
first_id = str(query_args.first_id) if query_args.first_id else None
|
|
|
|
try:
|
|
pagination = MessageService.pagination_by_first_id(
|
|
app_model, end_user, conversation_id, first_id, query_args.limit
|
|
)
|
|
adapter = TypeAdapter(MessageListItem)
|
|
items = [adapter.validate_python(message, from_attributes=True) for message in pagination.data]
|
|
return MessageInfiniteScrollPagination(
|
|
limit=pagination.limit,
|
|
has_more=pagination.has_more,
|
|
data=items,
|
|
).model_dump(mode="json")
|
|
except services.errors.conversation.ConversationNotExistsError:
|
|
raise NotFound("Conversation Not Exists.")
|
|
except FirstMessageNotExistsError:
|
|
raise NotFound("First Message Not Exists.")
|
|
|
|
|
|
@service_api_ns.route("/messages/<uuid:message_id>/feedbacks")
|
|
class MessageFeedbackApi(Resource):
|
|
@service_api_ns.expect(service_api_ns.models[MessageFeedbackPayload.__name__])
|
|
@service_api_ns.doc("create_message_feedback")
|
|
@service_api_ns.doc(description="Submit feedback for a message")
|
|
@service_api_ns.doc(params={"message_id": "Message ID"})
|
|
@service_api_ns.doc(
|
|
responses={
|
|
200: "Feedback submitted successfully",
|
|
401: "Unauthorized - invalid API token",
|
|
404: "Message not found",
|
|
}
|
|
)
|
|
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
|
|
def post(self, app_model: App, end_user: EndUser, message_id):
|
|
"""Submit feedback for a message.
|
|
|
|
Allows users to rate messages as like/dislike and provide optional feedback content.
|
|
"""
|
|
message_id = str(message_id)
|
|
|
|
payload = MessageFeedbackPayload.model_validate(service_api_ns.payload or {})
|
|
|
|
try:
|
|
MessageService.create_feedback(
|
|
app_model=app_model,
|
|
message_id=message_id,
|
|
user=end_user,
|
|
rating=payload.rating,
|
|
content=payload.content,
|
|
)
|
|
except MessageNotExistsError:
|
|
raise NotFound("Message Not Exists.")
|
|
|
|
return ResultResponse(result="success").model_dump(mode="json")
|
|
|
|
|
|
@service_api_ns.route("/app/feedbacks")
|
|
class AppGetFeedbacksApi(Resource):
|
|
@service_api_ns.expect(service_api_ns.models[FeedbackListQuery.__name__])
|
|
@service_api_ns.doc("get_app_feedbacks")
|
|
@service_api_ns.doc(description="Get all feedbacks for the application")
|
|
@service_api_ns.doc(
|
|
responses={
|
|
200: "Feedbacks retrieved successfully",
|
|
401: "Unauthorized - invalid API token",
|
|
}
|
|
)
|
|
@validate_app_token
|
|
def get(self, app_model: App):
|
|
"""Get all feedbacks for the application.
|
|
|
|
Returns paginated list of all feedback submitted for messages in this app.
|
|
"""
|
|
query_args = FeedbackListQuery.model_validate(request.args.to_dict())
|
|
feedbacks = MessageService.get_all_messages_feedbacks(app_model, page=query_args.page, limit=query_args.limit)
|
|
return {"data": feedbacks}
|
|
|
|
|
|
@service_api_ns.route("/messages/<uuid:message_id>/suggested")
|
|
class MessageSuggestedApi(Resource):
|
|
@service_api_ns.doc("get_suggested_questions")
|
|
@service_api_ns.doc(description="Get suggested follow-up questions for a message")
|
|
@service_api_ns.doc(params={"message_id": "Message ID"})
|
|
@service_api_ns.doc(
|
|
responses={
|
|
200: "Suggested questions retrieved successfully",
|
|
400: "Suggested questions feature is disabled",
|
|
401: "Unauthorized - invalid API token",
|
|
404: "Message not found",
|
|
500: "Internal server error",
|
|
}
|
|
)
|
|
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY, required=True))
|
|
def get(self, app_model: App, end_user: EndUser, message_id):
|
|
"""Get suggested follow-up questions for a message.
|
|
|
|
Returns AI-generated follow-up questions based on the message content.
|
|
"""
|
|
message_id = str(message_id)
|
|
app_mode = AppMode.value_of(app_model.mode)
|
|
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
|
|
raise NotChatAppError()
|
|
|
|
try:
|
|
questions = MessageService.get_suggested_questions_after_answer(
|
|
app_model=app_model, user=end_user, message_id=message_id, invoke_from=InvokeFrom.SERVICE_API
|
|
)
|
|
except MessageNotExistsError:
|
|
raise NotFound("Message Not Exists.")
|
|
except SuggestedQuestionsAfterAnswerDisabledError:
|
|
raise BadRequest("Suggested Questions Is Disabled.")
|
|
except Exception:
|
|
logger.exception("internal server error.")
|
|
raise InternalServerError()
|
|
|
|
return {"result": "success", "data": questions}
|