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

使用Google Translate API遇TypeError:translate_text()不识别request参数

问题排查:Google Translate API TypeError错误

问题描述

我正在使用Google Translate API翻译文档,编写了如下文本翻译函数:

# Imports the Google Cloud Translation library
from google.cloud import translate


# Initialize Translation client
def translate_text(
text: str = "YOUR_TEXT_TO_TRANSLATE", project_id: str = "YOUR_PROJECT_ID"
) -> translate.TranslationServiceClient:
"""Translating Text."""

client = translate.TranslationServiceClient()

location = "global"

parent = f"projects/{project_id}/locations/{location}"

# Translate text from English to French
response = client.translate_text(
    request={
        "parent": parent,
        "contents": [text],
        "mime_type": "text/plain",  # mime types: text/plain, text/html
        "source_language_code": "en-US",
        "target_language_code": "fr",
    }
)

# Display the translation for each input text provided
for translation in response.translations:
    print(f"Translated text: {translation.translated_text}")

return response

运行代码时触发错误:

TypeError: TranslationServiceClient.translate_text() got an unexpected keyword argument 'request'

错误原因

你使用的google-cloud-translate客户端库版本不符合代码调用规范:

  • 新版本(v3正式版)的translate_text方法支持通过request参数传入字典传递配置;
  • 旧版本(如v2版本、v3早期预览版)的方法不支持request关键字参数,要求直接传入独立参数。

解决方法

方法1:升级客户端库到最新版

执行命令升级至支持request参数的版本:

pip install --upgrade google-cloud-translate

升级后原代码无需修改即可正常运行。

方法2:适配旧版本库的调用写法

若无法升级库,可修改translate_text调用代码,移除request包裹,直接传入参数:

response = client.translate_text(
    parent=parent,
    contents=[text],
    mime_type="text/plain",
    source_language_code="en-US",
    target_language_code="fr"
)

该写法兼容新旧版本客户端库。

额外修正:函数返回值类型标注

原函数返回值类型标注错误,实际返回翻译响应对象而非客户端实例,建议修改为:

def translate_text(
text: str = "YOUR_TEXT_TO_TRANSLATE", project_id: str = "YOUR_PROJECT_ID"
) -> translate.TranslateTextResponse:

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:10:24