【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
相关推荐
Gopher_HBo几秒前
CompletableFuture函数原理
后端
m0_734949792 分钟前
PHP怎么使用Eloquent Attribute Synthesis属性合成_Laravel多源数据融合【指南】
jvm·数据库·python
墨染天姬2 分钟前
cursor的MCP怎么配置使用?
人工智能
colofullove2 分钟前
幂等设计与数据一致性:确保小说知识库的可靠更新
人工智能
香山上的麻雀10085 分钟前
由 Rust 开发的能大幅降低LLM token消耗的高性能 CLI 代理工具 rtk
开发语言·后端·rust
Fleshy数模5 分钟前
玩转 Python:多线程、装饰器、视觉检测与正则匹配实战
开发语言·python·视觉检测
Lucas_coding6 分钟前
【xiaozhi-esp32-server-服务端全模块启动】 xiaozhi-server 获取6位有效验证码
python
庄小焱6 分钟前
【AI模型】——基于知识图谱的RAG
人工智能·大模型·知识图谱·rag·ai模型·ai系统
❆VE❆8 分钟前
python实战(一):对接AI大模型并应用
开发语言·人工智能·python·ai
qq_3729069310 分钟前
CSS怎么在flex布局中实现项目均分间距_设置justify-content space-evenly
jvm·数据库·python