【Flask + AI】接入CHATGLM API 实现翻译接口

【Flask + AI】接入CHATGLM API 实现翻译接口

最近的项目中,需要加一个翻译功能,正好chatglm4发布了,于是决定着手用它实现。

https://chatglm.cn

准备

首先,在chatglm开发者中心申请api key,这里不再赘述

其次,选择自己的开发框架,这里以 flask 为例

提示词

要实现翻译功能,一个优良的提示词十分重要。

经过多次测试,得到了这样一个较为稳定的提示词。

python 复制代码
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 world"
    
    Now I will give you my input:
"""

这个Prompt 实现了中英互译,注意,这两个例子非常重要,如果没有,模型可能会永远输出英文或者中文。在调用api时,把这个提示词设置为 assistant 可以减小模型把这段话认为是指令的概率。

接口代码

python 复制代码
@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'}), 400

    contentPrompt = prompt_translation

    completion = client.chat.completions.create(
        model='glm-4',
        messages=[
            {"role": "system", "content": contentPrompt},
            {"role": "assistant", "content": user_content}
        ],
        max_tokens=200,
        temperature=0.1,
    )

    # 将 ChatCompletionMessage 对象转换为可序列化的格式
    response_message = completion.choices[0].message.content if completion.choices[0].message else "No response"

    return jsonify({"response": response_message})
  • role 设置为 assistant 或 user 效果会不同
  • 模型可以自己更改,glm-4目前效果最好
  • 如果要节省token,可以限制max_token
相关推荐
lijianhua_97126 小时前
国内某顶级大学内部用的ai自动生成论文的提示词
人工智能
蔡俊锋6 小时前
用AI实现乐高式大型可插拔系统的技术方案
人工智能·ai工程·ai原子能力·ai乐高工程
自然语6 小时前
人工智能之数字生命 认知架构白皮书 第7章
人工智能·架构
大熊背6 小时前
利用ISP离线模式进行分块LSC校正的方法
人工智能·算法·机器学习
eastyuxiao7 小时前
如何在不同的机器上运行多个OpenClaw实例?
人工智能·git·架构·github·php
诸葛务农7 小时前
AGI 主要技术路径及核心技术:归一融合及未来之路5
大数据·人工智能
光影少年7 小时前
AI Agent智能体开发
人工智能·aigc·ai编程
极梦网络无忧7 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger7 小时前
【Python】操作Excel文件
python·excel
ai生成式引擎优化技术7 小时前
TSPR-WEB-LLM-HIC (TWLH四元结构)AI生成式引擎(GEO)技术白皮书
人工智能