网站建设项目实施方案,徐州seo招聘,免费建站的网址,wordpress更多的模板【Flask AI】接入CHATGLM API 实现翻译接口
最近的项目中#xff0c;需要加一个翻译功能#xff0c;正好chatglm4发布了#xff0c;于是决定着手用它实现。
https://chatglm.cn
准备
首先#xff0c;在chatglm开发者中心申请api key#xff0c;这里不再赘述 其次 AI】接入CHATGLM API 实现翻译接口
最近的项目中需要加一个翻译功能正好chatglm4发布了于是决定着手用它实现。
https://chatglm.cn
准备
首先在chatglm开发者中心申请api key这里不再赘述 其次选择自己的开发框架这里以 flask 为例
提示词
要实现翻译功能一个优良的提示词十分重要。 经过多次测试得到了这样一个较为稳定的提示词。
prompt_translation zh-en translation of input.Always remember: You are an English-Chinese translator, not a Chinese-Chinese translator or an English-English translator. Your output should only contains Chinese or English!You should Always just do the translate part and do not change its meaning! example1:input:write me a poem,output:帮我写一首诗example2:input:你好世界,output:hello worldNow I will give you my input:这个Prompt实现了中英互译注意这两个例子非常重要如果没有模型可能会永远输出英文或者中文。在调用api时把这个提示词设置为 assistant 可以减小模型把这段话认为是指令的概率。
接口代码
glm_blueprint.route(/api/glmTranslation, methods[POST])
def translation():user_content request.json.get(user-content)if not user_content:return jsonify({error: No user-content provided}), 400contentPrompt prompt_translationcompletion client.chat.completions.create(modelglm-4,messages[{role: system, content: contentPrompt},{role: assistant, content: user_content}],max_tokens200,temperature0.1,)# 将 ChatCompletionMessage 对象转换为可序列化的格式response_message completion.choices[0].message.content if completion.choices[0].message else No responsereturn jsonify({response: response_message})role 设置为 assistant 或 user 效果会不同模型可以自己更改glm-4目前效果最好如果要节省token可以限制max_token