掌握Multi-Agent实践(三):ReAct Agent集成Bing和Google搜索功能,增强处理复杂任务能力

大模型向量数据库云通信

一个普遍的现象是,大模型通常会根据给定的提示直接生成回复。对于一些简单的任务,大模型或许能够较好地应对。然而,当我们面对更加复杂的任务时,往往希望大模型能够表现得更加“智能”,具备适应多样场景和解决复杂问题的能力。为此,AgentScope 提供了内置的 ReAct 智能体框架,使模型能够在多步骤、高复杂度的任务中展现出更强的推理与决策能力。

ReAct 算法来源于论文 “ReAct:Synergizing Reasoning and Acting in Language Models”,发表在 2023 年的 ICLR 会议上。ReAct 算法的核心是通过交替进行 reasoning 和 acting 的方式帮助智能体更好地应对和解决复杂问题。相较于一般的 reasoning 方法,能够根据当前的场景进行分析,做出更具有针对性的行动,并且提供了更好的可解释性和更高的容错度。

论文链接:https://www.alphaxiv.org/abs/2210.03629

picture.image

在这里插入图片描述

1.ReActAgent

ReAct算法中,Acting一般通过调用工具的方式进行,因此我们首先需要为智能体准备工具函数,然后再使用这些工具函数解决我们的具体问题。

参考内容:

  • • ReActAgent
  • • 内置工具函数

1.1第一步:准备工具函数

为了让大模型能够使用工具函数,我们需要首先对工具函数进行处理,这里的处理包括两个层面:

    1. 处理需要开发者填入的参数,例如 API key,账户,密码等信息,使大模型可以直接调用该函数
    1. 生成大模型能够理解的函数说明,例如目前许多模型 API 要求的 JSON schema 格式为了降低用户的开发难度,AgentScope 提供了 ServiceFactory 模块,可以轻松地处理工具函数。以 bing_search 函数为例,这个函数需要输入以下参数
  • query :查询的问题
  • api\_key :bing 搜索的 API key
  • num\_results :搜索结果的返回数目开发者可以在 ServiceFactory.get 中为 bing_search 指定 api_key 和 num_results 两个参数,从而生成一个只要求使用者输入 query 的函数,以及 JSON schema 格式的函数说明。

 
 
 
 
   
results = bing\_search(question="What is an agent?",  
                     bing\_api\_key="your bing api key",  
                     num\_results=2,  
                     mkt="en-US")  
print(results)

 
 
 
 
   
  
from agentscope.service import bing\_search  
  
func\_for\_llm, func\_desc = ServiceFactory.get(  
  bing\_search,   
  api\_key=BING\_API\_KEY,   
  num\_results=3  
)

其中 JSON schema 格式的变量 func_desc 值如下:


 
 
 
 
   
  
{  
    "type": "function",  
    "function": {  
        "name": "bing\_search",  
        "description": "Search question in Bing Search API and return the searching results",  
        "parameters": {  
            "type": "object",  
            "properties": {  
                "question": {  
                    "type": "string",  
                    "description": "The search query string."  
                }  
            },  
            "required": [  
                "question"  
            ]  
        }  
    }  
}

使用类似的方法,我们就可以将不同的工具函数转换成大模型可调用的模式。那么这里我们准备以下的工具函数


 
 
 
 
   
  
from agentscope.service import (  
    bing\_search, # or google\_search,  
    read\_text\_file,  
    write\_text\_file,   
    ServiceFactory  
)  
  
# Deal with arguments that need to be input by developers  
tools = [  
    ServiceFactory.get(bing\_search, api\_key=BING\_API\_KEY, num\_results=3),  
    ServiceFactory.get(execute\_python\_code),  
    ServiceFactory.get(read\_text\_file),  
    ServiceFactory.get(write\_text\_file),  
]

更多内置工具参考:agentscope.service package

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述


 
 
 
 
   
results = google\_search(  
    'Python programming',  
    'your\_google\_api\_key',  
    'your\_cse\_id',  
    num\_results=2  
)  
if results.status == ServiceExecStatus.SUCCESS:  
    for result in results.content:  
        print(result['title'], result['link'], result['snippet'])

google_searchAPI申请可以参考第二章

1.2 第二步:创建智能体


在准备好了工具函数之后,我们可以创建 ReAct 智能体了,创建的过程非常简单,初始化 agentscope,然后创建 ReActAgent 并输入对应的参数。复制代码


 
 
 
 
   
from agentscope.agents import ReActAgent  
import agentscope  
  
agentscope.init(model\_configs=YOUR\_MODEL\_CONFIGURATION)  
  
agent = ReActAgent(  
    name="assistant",  
    model\_config\_name=YOUR\_MODEL\_CONFIGURATION\_NAME,  
    tools=tools,  
    sys\_prompt="You are a helpful assistant.",  
    verbose=True, # set verbose to True to show the reasoning process  
)

为了让大家更加清楚 ReActAgent 的运行原理,我们这里首先展示一下这个智能体的系统提示(system prompt),包含了身份的说明,工具函数说明和提示三个部分。


 
 
 
 
   
You are a helpful assistant.  
  
The following tool functions are available in the format of

{index}. {function name}: {function description}
{argument name} ({argument type}): {argument description}
...


 
 
 
 
   
  
Tool Functions:  
1. bing\_search: Search question in Bing Search API and return the searching results  
  question (string): The search query string.  
2. execute\_python\_code: Execute Python code and capture the output. Note you must `print` the output to get the result.  
  code (string): The Python code to be executed.  
3. read\_text\_file: Read the content of the text file.  
  file\_path (string): The path to the text file to be read.  
4. write\_text\_file: Write content to a text file.  
  overwrite (boolean): Whether to overwrite the file if it already exists.  
  file\_path (string): The path to the file where content will be written.  
  content (string): Content to write into the file.  
  
Notice:  
1. Fully understand the tool function and its arguments before using it.  
2. Only use the tool function when it's necessary.  
3. Check if the arguments you provided to the tool function is correct in type and value.  
4. You can't take some problems for granted. For example, where you are, what's the time now, etc. But you can try to use the tool function to solve the problem.  
5. If the function execution fails, you should analyze the error and try to solve it.

1.3 第三步:测试 ReAct 智能体能力

此时我们用一个 ReAct 论文中经典的样例问题 “Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?” 来测试它的表现。


 
 
 
 
   
  
from agentscope.message import Msg  
  
msg\_question = Msg(  
    name="user",   
    content="Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?",   
    role="user"  
)  
      
res = agent(msg\_question)
  • • 第一轮
  • reasoning : 我们首先看到智能体分析了用户输入的问题,并且决定采用 bing_search 的工具函数进行调用
  • acting : bing_search 返回了搜索结果,但是这里我们注意到,返回的信息和问题答案并不相关。由于 ReAct 算法受到广泛的关注,因此我们在这里使用的样例问题搜索到的结果是与 ReAct 算法本身相关的介绍!这是一个非常有趣的搜索结果,出乎了我们的意料,下面我们看看智能体将会如何处理这个问题。复制代码

 
 
 
 
   
##################### ITER 1, STEP 1: REASONING ######################  
assistant: {  
    "thought": "I need to search for information about what other devices can control the program that the Apple Remote was originally designed to interact with.",  
    "speak": "Let me find that information for you.",  
    "function": [  
        {  
            "name": "bing\_search",  
            "arguments": {  
                "question": "What devices can control the program Apple Remote was designed for?"  
            }  
        }  
    ]  
}  
####################### ITER 1, STEP 2: ACTION #######################  
>>> Executing function bing\_search ...  
>>> END   
system: Execution Results:  
1. bing\_search:  
    [EXECUTE STATUS]: SUCCESS  
    [EXECUTE RESULT]: [{'title': '《ReAct: SYNERGIZING REASONING AND ACTING IN ...', 'link': 'https://www.cnblogs.com/LittleHann/p/17541295.html', 'snippet': 'Aside from the Apple Remote, what other devices can control the program Apple Remote was originally designed to interact with? 我们可以看到该模型生成了任务解决轨迹(思考、行动)。'}, {'title': 'REACT:在大模型中协同推理与行动,使其能够解决推理和 ...', 'link': 'https://baijiahao.baidu.com/s?id=1775590643651365661', 'snippet': 'Q:Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to intect with? 除了苹果遥控器之外,还有哪些设备可以控制最初设计用于连接的苹果遥控器所配合的程序?'}, {'title': 'ReAct Prompting | Prompt Engineering Guide', 'link': 'https://www.promptingguide.ai/techniques/react', 'snippet': 'Aside from the Apple Remote, what other devices can control the program Apple Remote was originally designed to interact with? Note that in-context examples are also added to the prompt but we exclude that here for simplicity.'}]
  • • 第二轮

 
 
 
 
   
  
##################### ITER 2, STEP 1: REASONING ######################  
assistant: {  
    "thought": "The search results did not provide a clear answer to the question. I need to refine the search query to get more specific results.",  
    "speak": "I'm sorry, I couldn't find a clear answer. Let me try a different search.",  
    "function": [  
        {  
            "name": "bing\_search",  
            "arguments": {  
                "question": "What devices can control Apple TV other than Apple Remote?"  
            }  
        }  
    ]  
}  
####################### ITER 2, STEP 2: ACTION #######################  
>>> Executing function bing\_search ...  
>>> END   
system: Execution Results:  
1. bing\_search:  
    [EXECUTE STATUS]: SUCCESS  
    [EXECUTE RESULT]: [{'title': 'Use other remotes to control Apple TV - Apple Support', 'link': 'https://support.apple.com/guide/tv/use-other-remotes-atvb0410f604/tvos', 'snippet': 'Table of Contents. Use other remotes to control Apple TV. You can use a supported TV or receiver remote, a network-based remote for home-control systems, or an infrared remote (commonly known as a universal remote) to control Apple TV.'}, {'title': '4 Siri Remote Alternatives You Can Use to Control Your Apple TV - MUO', 'link': 'https://www.makeuseof.com/alternative-apple-tv-remotes/', 'snippet': "Fortunately, if you find yourself looking for alternatives to control your Apple TV, there are several good options for you. You can use other Apple devices to operate the Apple TV, or even affordable Bluetooth accessories. We'll highlight the best alternatives to the Apple TV remote. 1. Use Your iPhone or iPad to Control the Apple TV"}, {'title': 'Apple TV Siri Remote: How to control TVs and receivers - 9to5Mac', 'link': 'https://9to5mac.com/2021/05/27/apple-tv-siri-remote-control-tv-receiver/', 'snippet': 'The old Siri Remote and Apple TV Remote also feature this functionality, but without a dedicated power button, it’s less convenient and intuitive to use. Another benefit of HDMI-CEC is that...'}]  

  • • 第三轮
  • • reasoning:在这一轮中,智能体总结了上一轮 bing_search 搜索出来的结果,并在 “speak” 字段形成了最终的回复。

 
 
 
 
   
  
##################### ITER 3, STEP 1: REASONING ######################  
assistant: {  
    "thought": "The search results provided a clear answer to the question. Other than the Apple Remote, you can use a supported TV or receiver remote, a network-based remote for home-control systems, an infrared remote (commonly known as a universal remote), or other Apple devices like an iPhone or iPad to control the Apple TV.",  
    "speak": "Other than the Apple Remote, you can use a supported TV or receiver remote, a network-based remote for home-control systems, an infrared remote (commonly known as a universal remote), or other Apple devices like an iPhone or iPad to control the Apple TV."  
}  

这个例子十分的有趣,我们看到了 ReAct 算法本身是如何处理错误信息,并且产生正确的回复,以及如何在 AgentScope 中方便地使用 ReActAgent 来解决我们的问题。

1.4 demo效果展示

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述


 
 
 
 
   
[95mUser[0m: 你知道阿里qwen3 大模型吗,介绍一下它的优点。  
[93msystem[0m: Respond with specific tags as outlined below:  
<thought>{what you thought}</thought>  
<function>{the function name you want to call}</function>  
<{argument name}>{argument value}</{argument name}>  
<{argument name}>{argument value}</{argument name}>  
...  
[92massistant[0m: <thought>我需要搜索关于阿里qwen3大模型的最新信息,以便介绍它的优点。</thought>  
<function>google\_search</function>  
<question>阿里qwen3 大模型的优点</question>  
[93msystem[0m: 1. Execute function google\_search  
   [ARGUMENTS]:  
       {"question": "阿里qwen3 大模型的优点"}  
   [RESULT]: [{'title': '英特尔第一时间深度优化Qwen3大模型,升级AI PC能力赋能多样化场景', 'link': 'https://newsroom.intel.com/zh-cn/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E8%8B%B1%E7%89%B9%E5%B0%94%E7%AC%AC%E4%B8%80%E6%97%B6%E9%97%B4%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%8C%96qwen3%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%8D%87%E7%BA%A7ai-pc%E8%83%BD%E5%8A%9B%E8%B5%8B%E8%83%BD', 'snippet': '拥抱开源生态,Day 0支持魔搭社区Ollama. 在本次阿里巴巴开源的新一代通义千问Qwen3 ... 优势以及快速迭代更新的能力。然而,在实际应用落地过程中,人们常常对其知识的\xa0...'}, {'title': '大模型服务平台百炼\_企业级大模型开发平台\_百炼AI应用构建-阿里云', 'link': 'https://www.aliyun.com/product/bailian', 'snippet': '阿里云百炼发布通义千问Qwen3全系列模型服务. 灵活的混合思考模式真正“小成本超 ... 产品优势. 高性能易调用,高开放易集成,高可用易落地,超低价安全可信,助力\xa0...'}, {'title': '阿里Qwen3系列模型发布,中美基础大模型竞争强度加大\_《财经 ...', 'link': 'https://news.caijingmobile.com/article/detail/546860?source\_id=40', 'snippet': 'Apr 29, 2025 ... 阿里Qwen3技术文档披露,它在基准测试中的得分,和DeepSeek-R1、OpenAI旗下的o1、o3-mini,谷歌的Gemini-2.5-Pro等全球一流大模型不相上下。 让模型性能提升\xa0...'}, {'title': '通义大模型\_AI大模型\_一站式大模型推理和部署服务-阿里云', 'link': 'https://www.aliyun.com/product/tongyi', 'snippet': '通义大模型是阿里云打造的高性能、低成本的AI基础设施,依托其深厚的训练数据与优化技术,支持全模态高效精准的模型服务调用和AI应用快速搭建,还能实现模型的高效训练。'}, {'title': '如何评价阿里云刚刚发布的Qwen3系列大型语言模型? - 知乎', 'link': 'https://www.zhihu.com/question/1900463055457989808', 'snippet': 'Apr 28, 2025 ... 特别是在STEM(科学、技术、工程、数学)、编码和推理等领域,Qwen3 Dense基础模型的表现甚至超过了更大规模的Qwen2. ... 模型和生成模型的优点,以及Deepseek和\xa0...'}, {'title': '麻省理工科技评论-阿里开源Qwen3 系列“混合”推理模型,可开关快慢 ...', 'link': 'https://www.mittrchina.com/news/detail/14728', 'snippet': '其中,最吸引人眼球的当属旗舰模型 Qwen3-235B-A22B。这是一款采用MoE(Mixture of Experts, 混合专家)架构的大模型,拥有2350 亿总参数量,在推理时激活其中\xa0...'}, {'title': 'Qwen3上线首都在线云平台-北京通信信息协会', 'link': 'https://www.bita.org.cn/newsinfo/8317496.html', 'snippet': '1 day ago ... 近日,阿里通义千问团队发布的Qwen3 大模型以一整套密集型和专家混合(MoE)模型震撼行业。凭借广泛的训练,Qwen3在推理能力、指令遵循能力、代理能力\xa0...'}, {'title': 'Qwen3 即将来袭:阿里云新模型相关支持已合并至vLLM 代码库 ...', 'link': 'https://www.oschina.net/news/343339', 'snippet': 'Apr 8, 2025 ... 阿里云旗下人工智能大模型系列Qwen 迎来重要进展,其下一代模型Qwen3的相关支持已正式合并至vLLM(高效大语言模型推理框架)的代码库中,标志着Qwen3的\xa0...'}, {'title': '轻松上手Qwen3,覆盖0.6 B到235 B 参数规模-阿里云技术解决方案', 'link': 'https://help.aliyun.com/document\_detail/2883412.html', 'snippet': '2 days ago ... 56日,权威大模型测评榜LiveBench 放榜,Qwen3-235B-A22B 登顶「全球开源模型冠军」,且指令遵循能力超越顶级闭源模型位列全球第一。'}, {'title': '讯飞星辰MaaS平台-官网', 'link': 'https://training.xfyun.cn/modelSquare', 'snippet': 'Qwen3 是Qwen 系列的最新一代大型语言模型,提供了一系列密集型和专家混合 ... 讯飞自研的高性能大语言模型,在指令解析等场景上有明显优势。在工业自动化控制\xa0...'}]  
  
[93msystem[0m: Respond with specific tags as outlined below:  
<thought>{what you thought}</thought>  
<function>{the function name you want to call}</function>  
<{argument name}>{argument value}</{argument name}>  
<{argument name}>{argument value}</{argument name}>  
...  
[92massistant[0m: <thought>从搜索结果中,我可以提取出关于阿里qwen3大模型的一些优点和特点。</thought>  
<function>finish</function>  
<response>阿里Qwen3大模型具有以下优点:  
  
1. **优秀的推理能力**:Qwen3模型在推理能力上表现出色,能处理复杂的AI任务。  
  
2. **参数混合架构**:采用混合专家(MoE)架构,这种模式在推理时可以只激活部分参数,从而提高效率。  
  
3. **广泛的应用领域**:尤其在STEM(科学、技术、工程、数学)、编码和推理等领域表现出色,比以往模型更有优势。  
  
4. **高效调用和集成**:能够以低成本实现高效的AI模型服务调用和快速构建AI应用程序。  
  
5. **开源和迭代更新**:拥抱开源生态,具备快速迭代更新的能力。  
  
6. **全球领先的性能**:在一些基准测试中,其性能超越许多全球一流的大模型。  
  
这些优点使得阿里Qwen3大模型在AI应用中展现出强大的竞争力。</response>  
[93msystem[0m: 1. Execute function finish  
   [ARGUMENTS]:  
       {"response": "阿里Qwen3大模型具有以下优点:\n\n1. **优秀的推理能力**:Qwen3模型在推理能力上表现出色,能处理复杂的AI任务。\n\n2. **参数混合架构**:采用混合专家(MoE)架构,这种模式在推理时可以只激活部分参数,从而提高效率。\n\n3. **广泛的应用领域**:尤其在STEM(科学、技术、工程、数学)、编码和推理等领域表现出色,比以往模型更有优势。\n\n4. **高效调用和集成**:能够以低成本实现高效的AI模型服务调用和快速构建AI应用程序。\n\n5. **开源和迭代更新**:拥抱开源生态,具备快速迭代更新的能力。\n\n6. **全球领先的性能**:在一些基准测试中,其性能超越许多全球一流的大模型。\n\n这些优点使得阿里Qwen3大模型在AI应用中展现出强大的竞争力。"}  
   [RESULT]: 阿里Qwen3大模型具有以下优点:  
  
1. **优秀的推理能力**:Qwen3模型在推理能力上表现出色,能处理复杂的AI任务。  
  
2. **参数混合架构**:采用混合专家(MoE)架构,这种模式在推理时可以只激活部分参数,从而提高效率。  
  
3. **广泛的应用领域**:尤其在STEM(科学、技术、工程、数学)、编码和推理等领域表现出色,比以往模型更有优势。  
  
4. **高效调用和集成**:能够以低成本实现高效的AI模型服务调用和快速构建AI应用程序。  
  
5. **开源和迭代更新**:拥抱开源生态,具备快速迭代更新的能力。  
  
6. **全球领先的性能**:在一些基准测试中,其性能超越许多全球一流的大模型。  
  
这些优点使得阿里Qwen3大模型在AI应用中展现出强大的竞争力。
  • 完整代码

 
 
 
 
   
# -*- coding: utf-8 -*-  
"""An example of a conversation with a ReAct agent."""  
import sys  
import io  
  
from agentscope.agents import UserAgent  
from agentscope.agents import ReActAgent  
from agentscope.service import (  
    bing\_search,    
    google\_search,  
    read\_text\_file,  
    write\_text\_file,  
    ServiceToolkit,  
    ServiceResponse,  
    ServiceExecStatus,  
)  
import agentscope  
  
# Prepare the Bing API key and model configuration  
# BING\_API\_KEY = "{YOUR\_BING\_API\_KEY}"  
  
# YOUR\_MODEL\_CONFIGURATION\_NAME = "{YOUR\_MODEL\_CONFIGURATION\_NAME}"  
# YOUR\_MODEL\_CONFIGURATION = {  
#     "model\_type": "xxx",  
#     "config\_name": YOUR\_MODEL\_CONFIGURATION\_NAME,  
#     # ...  
# }  
  
  
# Prepare a new tool function  
def execute\_python\_code(code: str) -> ServiceResponse:  # pylint: disable=C0301  
    """  
    Execute Python code and capture the output. Note you must `print` the output to get the result.  
    Args:  
        code (`str`):  
            The Python code to be executed.  
    """  # noqa  
  
    # Create a StringIO object to capture the output  
    old\_stdout = sys.stdout  
    new\_stdout = io.StringIO()  
    sys.stdout = new\_stdout  
  
    try:  
        # Using `exec` to execute code  
        namespace = {}  
        exec(code, namespace)  
    except Exception as e:  
        # If an exception occurs, capture the exception information  
        output = str(e)  
        status = ServiceExecStatus.ERROR  
    else:  
        # If the execution is successful, capture the output  
        output = new\_stdout.getvalue()  
        status = ServiceExecStatus.SUCCESS  
    finally:  
        # Recover the standard output  
        sys.stdout = old\_stdout  
  
    # Wrap the output and status into a ServiceResponse object  
    return ServiceResponse(status, output)  
  
  
# Prepare the tools for the agent  
service\_toolkit = ServiceToolkit()  
  
GOOGLE\_API\_KEY = ""  
CSE\_ID=""  
  
  
  
# Deal with arguments that need to be input by developers  
service\_toolkit.add(google\_search, api\_key=GOOGLE\_API\_KEY,cse\_id=CSE\_ID ,num\_results=10)  
service\_toolkit.add(execute\_python\_code)  
service\_toolkit.add(read\_text\_file)  
service\_toolkit.add(write\_text\_file)  
  
agentscope.init(model\_configs="./model\_configs.json",  
                project="Conversation with ReActAgent",   
                studio\_url="http://127.0.0.1:5000")  
  
  
YOUR\_MODEL\_CONFIGURATION\_NAME="gpt-4o"  
  
agent = ReActAgent(  
    name="assistant",  
    model\_config\_name=YOUR\_MODEL\_CONFIGURATION\_NAME,  
    service\_toolkit=service\_toolkit,   
    sys\_prompt="最终回答结果用中文回答。",  
    max\_iters=2,  
    verbose=True, # set verbose to True to show the reasoning process  
)  
  
  
user = UserAgent(name="User", input\_hint="User Input ('exit' to quit): ")  
  
# Build  
x = None  
while True:  
    x = user(x)  
    if x.content == "exit":  
        break  
    x = agent(x)  

  1. Google Search API 申请 =======================

Google Search API(Custom Search JSON)是 Google 提供的一种 API,允许开发者在自己的应用或网站中集成 Google 搜索功能。它可以返回 Google 搜索结果,包括网页、图片、新闻等,并支持自定义搜索引擎(CSE,Custom Search Engine)。

官方文档: Google Custom Search API

  • 强大的搜索能力 :依托 Google 的搜索引擎技术,提供高质量的搜索结果。
  • 可定制 :可以创建自定义搜索引擎,指定搜索的站点范围、关键词等。
  • 支持不同的数据类型 :可以获取网页、图片、新闻等搜索结果。
  • RESTful API :使用标准的 HTTP 请求,返回 JSON 格式数据,方便集成。
  • 免费 & 付费计划
  • • 免费版本每天最多 100 个请求。
  • • 付费版本支持更多的请求配额(最高 10,000 个请求 / 天)。
  • 与 Google 生态兼容 :可结合 Google Cloud 其他服务,如 BigQuery、Google Sheets 等。

获取 API Key 和 Custom Search Engine ID(cx)

使用 API 之前,需要完成以下步骤:

    1. 访问 Google Cloud Console 并创建一个项目。
    1. 在 Google Custom Search Engine 创建一个自定义搜索引擎(CSE)。
    1. 获取 Custom Search Engine ID (cx) ,在 CSE 管理页面查看。
    1. 在 Google API Console 启用 Custom Search JSON API
    1. 生成 API Key 并记录。
  • • 发送搜索请求

API 请求的基本格式:


 
 
 
 
   
GET https://www.googleapis.com/customsearch/v1?q=搜索词&key=YOUR\_API\_KEY&cx=YOUR\_CX\_ID

参数说明:

  • q :搜索关键词。
  • key :API 密钥。
  • cx :自定义搜索引擎 ID。
  • • 其他可选参数:
  • num :返回结果数量(1-10)。
  • start :分页参数,指定从第几条结果开始。
  • siteSearch :限制搜索范围到特定网站。
  • searchType=image :返回图片搜索结果。

2.1 登录谷歌云启动服务

picture.image

picture.image

在这里插入图片描述

2.2 选择 API 服务

  • • 选择创建的项目,进入 API 库。搜索 Google Search

picture.image

在这里插入图片描述

picture.image

  • • 选择 custom Search API 并启用。

此外,有个非常具有类似的 API-- Google Search Console API。和 Custom Search API 主要用于获取搜索结果不同,Google Search Console API 主要用于查询某网页在谷歌搜索中的排名和浏览情况,即查阅网站运行情况,并据此进一步制定 SEO 优化 措施。

picture.image

picture.image

picture.image

在这里插入图片描述

查询类 API 调用的关键额度是 每天 100 次搜索限制 ,尽管者并不是一个很高的搜索额度,不过对于学习者以及初期开发测试阶段应用来说,这个免费配额是够用的。当然,如果超出这个限额则需要按照 5 美元 / 千次进行计费,且普通开发者账户每天不能超过 1 万次查询,具体费用情况可以查询相关 帮助文档 : https://developers.google.com/custom-search/v1/overview。

picture.image

2.3 申请凭据

  • • 申请凭据 KEY

picture.image

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

2.4 Custom Search Engine ID (cx)获取

https://developers.google.com/custom-search/v1/overview?hl=zh-cn

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

picture.image

在这里插入图片描述

至此API_KEY = "YOUR_API_KEY",CX = "YOUR_CX_ID"都已获取 2.5 示例代码

  • 使用 Python 进行网页搜索

 
 
 
 
   
import requests  
   
API\_KEY = "YOUR\_API\_KEY"  
CX = "YOUR\_CX\_ID"  
QUERY = "深度学习"  
   
url = f"https://www.googleapis.com/customsearch/v1?q={QUERY}&key={API\_KEY}&cx={CX}"  
   
response = requests.get(url)  
data = response.json()  
   
# 提取并打印搜索结果  
for item in data.get("items", []):  
    print(f"标题: {item['title']}")  
    print(f"链接: {item['link']}")  
    print(f"摘要: {item['snippet']}\n")
  • 获取图片搜索结果

 
 
 
 
   
url = f"https://www.googleapis.com/customsearch/v1?q={QUERY}&searchType=image&key={API\_KEY}&cx={CX}"  
   
response = requests.get(url)  
data = response.json()  
   
# 提取并打印图片结果  
for item in data.get("items", []):  
    print(f"图片标题: {item['title']}")  
    print(f"图片链接: {item['link']}\n")
0
0
0
0
关于作者
关于作者

文章

0

获赞

0

收藏

0

相关资源
火山引擎大规模机器学习平台架构设计与应用实践
围绕数据加速、模型分布式训练框架建设、大规模异构集群调度、模型开发过程标准化等AI工程化实践,全面分享如何以开发者的极致体验为核心,进行机器学习平台的设计与实现。
相关产品
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论