You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合Langchain的OpenAI函数调用与检索器实现多功能聊天机器人

实现检索+OpenAI函数调用的聊天机器人方案

核心整合思路

把网页检索模块包装成OpenAI可调用的函数,或者在生成回复前自动补充检索到的网页上下文,让模型同时具备工具调用和信息检索能力。

具体实现步骤

1. 封装网页检索为OpenAI函数

把你已有的检索逻辑包装成符合OpenAI函数规范的结构,让模型能主动判断是否需要调用它获取网页数据:

# 检索函数的定义(供OpenAI模型识别)
retrieval_function = {
    "name": "retrieve_web_content",
    "description": "当需要回答用户关于实时信息、外部网页内容或特定知识库的问题时调用此函数",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "用户问题的核心关键词,用于检索相关网页内容"
            },
            "target_url": {
                "type": "string",
                "description": "可选,指定要提取内容的具体网页URL"
            }
        },
        "required": ["query"]
    }
}

# 对应的检索执行逻辑(替换成你已有的检索模块代码)
def retrieve_web_content(query, target_url=None):
    if target_url:
        # 爬取指定URL并提取关键信息
        processed_content = crawl_and_extract(target_url)
    else:
        # 根据关键词搜索网页并生成摘要
        processed_content = web_search_summarize(query)
    return {"web_summary": processed_content}

2. 调整OpenAI调用流程,加入检索函数

在原有的OpenAI函数调用流程中,把检索函数加入可调用列表,让模型自主判断调用时机:

import openai
import json

def chat_with_combined_capabilities(user_msg, chat_history):
    # 初始化对话消息
    messages = [{"role": "system", "content": "你可以调用工具获取外部网页信息,也可以执行指定函数完成任务"}]
    messages.extend(chat_history)
    messages.append({"role": "user", "content": user_msg})

    # 首次调用OpenAI,判断是否需要调用工具
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=[retrieval_function,  # 加入检索函数
                   your_existing_func1,  # 原有的OpenAI函数
                   your_existing_func2],
        function_call="auto"
    )

    resp_msg = response["choices"][0]["message"]

    # 处理模型的工具调用请求
    if resp_msg.get("function_call"):
        func_name = resp_msg["function_call"]["name"]
        func_args = json.loads(resp_msg["function_call"]["arguments"])

        # 执行对应函数
        if func_name == "retrieve_web_content":
            func_result = retrieve_web_content(**func_args)
        elif func_name == "your_existing_func1":
            func_result = your_existing_func1(**func_args)
        # 其他函数的执行逻辑...

        # 将工具结果加入对话,再次调用生成最终回复
        messages.append(resp_msg)
        messages.append({
            "role": "function",
            "name": func_name,
            "content": json.dumps(func_result)
        })

        final_resp = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages
        )
        return final_resp["choices"][0]["message"]["content"]
    else:
        # 无需调用工具,直接返回模型回复
        return resp_msg["content"]

3. 备选方案:强制前置检索(无需模型判断)

如果希望所有问题都先补充网页检索信息,再结合函数调用能力回复,可在构造对话时直接注入检索结果:

def chat_with_pre_retrieval(user_msg, chat_history):
    # 先执行检索获取网页内容
    web_info = retrieve_web_content(user_msg)["web_summary"]
    
    # 构造包含检索信息的对话上下文
    messages = [{"role": "system", "content": f"以下是网页检索到的相关信息:{web_info}\n请结合这些信息和可用函数回复用户"}]
    messages.extend(chat_history)
    messages.append({"role": "user", "content": user_msg})

    # 调用OpenAI并传入原有函数列表
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=[your_existing_func1, your_existing_func2],
        function_call="auto"
    )

    # 后续函数调用处理逻辑同步骤2
    # ...

4. 关键注意事项

  • 确保检索函数的description精准描述适用场景,帮助模型正确判断调用时机
  • 对检索结果做精简处理,避免过长内容占用模型上下文token
  • 给函数执行逻辑添加异常处理(如URL无效、检索失败时的容错)

内容的提问来源于stack exchange,提问作者Felix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:18:33