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

用BARD替代ChatGPT开发个人助手:API端点请求失败求助

解决Bard API端点无法工作的问题

问题根源

你用的https://ai.google/bard是Bard的网页端地址,并非官方API接口,所以会返回404错误。目前Google Bard已整合到Gemini平台,官方只提供Gemini API用于开发调用,没有独立的Bard API端点。此外,你当前的POST请求格式也不符合官方API的调用规范。

修复方案

1. 获取Gemini API密钥

登录Google账号后,前往Google AI Studio创建项目并生成专属API密钥。

2. 替换API调用逻辑

把原有的get_bard_response函数替换为以下适配Gemini API的代码:

import google.generativeai as genai

def get_gemini_response(query, api_key):
    # 配置API密钥
    genai.configure(api_key=api_key)
    # 初始化Gemini Pro模型(适合文本交互场景)
    model = genai.GenerativeModel('gemini-pro')
    try:
        # 发送请求并获取响应文本
        response = model.generate_content(query)
        return response.text
    except Exception as e:
        return f"请求出错: {str(e)}"

3. 更新主程序逻辑

在主入口部分添加API密钥,并替换原有的Bard调用:

if __name__ == "__main__":
    # 替换成你自己的Gemini API密钥
    GEMINI_API_KEY = "your-api-key-here"
    speak("Hello! How can I assist you today?")

    while True:
        user_input = listen_to_microphone()

        if user_input:
            if user_input.lower() == "exit":
                speak("Goodbye!")
                break

            # 调用Gemini API获取回复
            gemini_response = get_gemini_response(user_input, GEMINI_API_KEY)
            speak(gemini_response)

4. 安装必要依赖

执行以下命令安装Google Gemini的Python SDK:

pip install google-generativeai

额外提醒

  • 免费额度的API密钥有调用次数限制,若频繁请求失败,检查是否配额耗尽。
  • 非官方的Bard接口(模拟网页请求)稳定性极差,随时可能被Google封禁,不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:25:15