📦 安装
安装SDK:
🛠️ 配置
创建 API KEY。
🚀 Python 实现
可以读取一个 JSON 文件,或者 JSON 字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| API_KEY = "sk-XXXXXX" BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
def translate_json(): ai_client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
print("Loading file...") with open("zh.json", "r", encoding="utf-8") as f: langdata = json.load(f) completion = ai_client.chat.completions.create( model="qwen-long", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "system", "content": json.dumps(langdata, ensure_ascii=False)}, {"role": "user", "content": "请将json值翻译为英文,直接输出结果"}, ], stream=False, )
print("Saving file...") with open("en.json", "w", encoding="utf-8") as file: file.write(completion.choices[0].message.content)
print("Complete")
|
可以以流的方式读取,将 stream
值设置为 True,然后读取流:
1 2 3 4
| result = "" for chunk in completion: print(chunk.model_dump()) result+=chunk.choices[0].delta.content.strip()
|
❓ 注意
如果安装 Google 翻译 googletrans
组件会导致运行异常。