如何消除Mistral Nemo工具调用时的思考与行动输出,仅返回自然结果?
移除AI工具调用输出中的思考与动作内容,保留自然化最终结果
问题背景
开发个人AI项目时,在多款开源模型中选定支持工具调用的Mistral Nemo,因Langgraph工具调用方案运行缓慢已弃用。目前已成功实现工具调用功能,但输出包含大量思考、动作相关冗余内容,需去除这些信息,仅保留自然化的最终回复。
当前代码
from langchain_openai import ChatOpenAI from langchain.agents import initialize_agent, AgentType, Tool from langchain.tools import tool from pydantic import SecretStr from langchain_core.runnables import RunnableConfig from langgraph.graph import START, MessagesState, StateGraph from langgraph.checkpoint.memory import MemorySaver from langchain_core.messages import HumanMessage, AIMessage @tool def get_weather(location: str) -> str: """获取指定地点的当前天气。""" return f"{location}当前天气为晴天。" @tool def get_rate(currencies) -> str: """获取两种货币之间的汇率。输入需为逗号分隔的两种货币,例如 USD,INR""" try: currency1, currency2 = currencies.split(',') return f"{currency1}兑换{currency2}的汇率为5.6" except ValueError: return "输入格式无效,请提供正确的货币格式。" tools = [get_weather, get_rate] config: RunnableConfig = {"configurable": {"thread_id": 1}} model = ChatOpenAI( base_url="http://localhost:8080/v1", # llama-server api_key=SecretStr("dummy"), # llama.cpp 忽略该参数 model="mistral-nemo", ) agent = initialize_agent( tools=tools, llm=model, agent_type=AgentType.OPENAI_FUNCTIONS, verbose=False, ) def call_model(state: MessagesState): response = agent.invoke({"input": state["messages"]}) return {"messages": state["messages"] + [AIMessage(content=response["output"])]} workflow = StateGraph(state_schema=MessagesState) workflow.add_edge(START, "model") workflow.add_node("model", call_model) memory = MemorySaver() app = workflow.compile(checkpointer=memory) config: RunnableConfig = {"configurable": {"thread_id": "1"}} query = "你好,JPY兑换NPR的当前汇率是多少?请调用工具并返回结果" input_messages = [HumanMessage(content=query)] for chunk, metadata in app.stream( {"messages": input_messages}, config=config, stream_mode="messages" ): if isinstance(chunk, AIMessage): print(chunk.content, end="", flush=True)
当前输出
我需要获取JPY和NPR之间的汇率。 Action: get_rate Action Input: JPY,NPR我现在知道最终答案了 Final Answer: JPY兑换NPR的当前汇率为5.6。JPY兑换NPR的当前汇率为5.6。
解决方案
方案1:正则提取最终答案
通过正则匹配输出中的「Final Answer」片段,提取核心内容并去除重复冗余:
import re def call_model(state: MessagesState): response = agent.invoke({"input": state["messages"]}) output_content = response["output"] # 匹配Final Answer后的内容 match = re.search(r"Final Answer:\s*(.*)", output_content, re.DOTALL) if match: final_answer = match.group(1).strip() # 去除重复的句子或标点 final_answer = re.sub(r"([^\n]+)\1+", r"\1", final_answer) else: final_answer = output_content # 无匹配时 fallback 原内容 return {"messages": state["messages"] + [AIMessage(content=final_answer)]}
方案2:自定义Agent提示模板
修改系统提示,引导模型直接返回自然化结果,禁止输出思考、动作等中间步骤:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder # 自定义系统提示 system_prompt = """你是专业助手,需根据用户问题调用对应工具,直接返回自然流畅的最终结果,不得输出任何思考过程、动作指令或中间步骤。""" prompt = ChatPromptTemplate.from_messages([ ("system", system_prompt), MessagesPlaceholder(variable_name="input"), MessagesPlaceholder(variable_name="agent_scratchpad"), ]) agent = initialize_agent( tools=tools, llm=model, agent_type=AgentType.OPENAI_FUNCTIONS, verbose=False, agent_kwargs={"prompt": prompt} )
方案3:输出内容过滤
直接切割输出字符串,提取「Final Answer」之后的部分:
def call_model(state: MessagesState): response = agent.invoke({"input": state["messages"]}) output_content = response["output"] # 切割并提取最终答案 if "Final Answer:" in output_content: final_answer = output_content.split("Final Answer:")[-1].strip() else: final_answer = output_content return {"messages": state["messages"] + [AIMessage(content=final_answer)]}
优化后预期输出
JPY兑换NPR的当前汇率为5.6。
内容的提问来源于stack exchange,提问作者deepyes02
相关产品推荐
相关产品推荐

