代理最終答案驗證

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

為何需要驗證

  • 代理的答案沒有幫上忙
  • 客戶體驗流失

為避免這種情況,smolagents 允許你驗證最終答案!

使用 Hugging Face smolagents 的 AI 代理

驗證代理的回應

def check_answer_length(final_answer, agent_memory):
    # Check if the answer is substantial enough
    if len(final_answer) < 200:
        raise Exception("Car recommendation is too brief")
    return True
  • final_answer 不符合規則就擲回例外;否則回傳 True
使用 Hugging Face smolagents 的 AI 代理

在代理中使用輸出驗證

car_advisor = CodeAgent(
    tools=[WebSearchTool()],
    model=InferenceClientModel(),
    final_answer_checks=[check_answer_length],
    verbosity_level=0
)
  • 在回應前執行 check_answer_length 驗證。
  • 依函式內定義的例外訊息自動重試。
使用 Hugging Face smolagents 的 AI 代理

中介評估:用 AI 驗證 AI

validation_prompt = """
Reasoning process: {}

Agent's final answer: {}

Does the final answer logically follow
from the reasoning and solve the user's 
question? 

Respond only TRUE or FALSE. 
No other text.
"""
使用 Hugging Face smolagents 的 AI 代理

用中介評估器驗證推理

def check_reasoning_accuracy(final_answer, agent_memory):
    evaluator_model = InferenceClientModel()
    reasoning_steps = agent_memory.get_succinct_steps()
    final_prompt = validation_prompt.format(reasoning_steps, final_answer)

    message = ChatMessage(role='user', content=final_prompt)
    evaluation = evaluator_model([message])

    if evaluation.content == "FALSE":
        raise Exception("The agent's reasoning process contains logical errors")
    else:
        return True
使用 Hugging Face smolagents 的 AI 代理

結合多重驗證

car_advisor = CodeAgent(
    tools=[WebSearchTool()],
    model=InferenceClientModel(),
    final_answer_checks=[check_answer_length, check_reasoning_accuracy],
    verbosity_level=0
)

在使用者看到前,更可能攔截並修正錯誤!

使用 Hugging Face smolagents 的 AI 代理

設計智慧系統

使用 Hugging Face smolagents 的 AI 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...