How to generate response when the model without proper tools (multi-turn)?

hi @feng-1985

how about this one:

from langchain_core.messages import AIMessage


def call_model(state: CourseQAState) -> dict:
    system_message = (
        "你是一个高效的课程信息查询助手。"
        "如果用户的问题和课程信息无关,或者没有合适的工具可以回答,"
        "请明确告诉用户当前问题不受支持,并建议如何改写。"
    )
    model_with_tools = model.bind_tools(course_tools)

    response = model_with_tools.invoke([
        {"role": "system", "content": system_message},
        *state["messages"],
    ])
    response.name = "course_qa_agent"

    # Fallback: no tools selected AND no text content
    if isinstance(response, AIMessage):
        tool_calls = getattr(response, "tool_calls", None) or []
        # `content` can be str or list; normalize to string
        text = response.content
        if isinstance(text, list):
            text = "".join(part.get("text", "") for part in text if isinstance(part, dict))
        text = (text or "").strip()

        if not tool_calls and not text:
            # Synthesize a user-facing fallback message
            response = AIMessage(
                content=(
                    "这个问题目前不在课程查询工具的支持范围内。\n"
                    "请尝试:\n"
                    "1. 说明你感兴趣的课程名称或编号;\n"
                    "2. 提出更具体的、与课程信息相关的问题,例如:上课时间、授课老师、学分等。"
                ),
                name="course_qa_fallback",
            )

    answer = response.content
    return {"answer": answer, "messages": [response]}

or this:

    # ... after the first response
    if isinstance(response, AIMessage):
        tool_calls = getattr(response, "tool_calls", None) or []
        text = (response.content or "").strip()

        if not tool_calls and not text:
            # Call the base chat model without tools to explain the limitation
            fallback = model.invoke([
                {
                    "role": "system",
                    "content": (
                        "你是一个课程问答助手。当你不能通过任何工具回答问题时,"
                        "请用中文向用户解释:当前问题不在支持范围内,并给出如何改写问题的建议。"
                    ),
                },
                *state["messages"],
            ])
            fallback.name = "course_qa_fallback"
            response = fallback

    answer = response.content
    return {"answer": answer, "messages": [response]}
1 Like