当前位置: 首页 > news >正文

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

【Flask + 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 world"Now 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(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
http://www.lryc.cn/news/298008.html

相关文章:

  • 并发事务带来的问题及解决方法
  • CRNN介绍:用于识别图中文本的深度学习模型
  • 机器人运动学林沛群——变换矩阵
  • 阿里云增加数据库访问白名单
  • Rust基础拾遗--辅助功能
  • 【数据结构】双向链表(链表实现+测试+原码)
  • ChatGPT 3.5与4.0:深入解析技术进步与性能提升的关键数据
  • 前端JavaScript篇之ajax、axios、fetch的区别
  • 【PyTorch][chapter 15][李宏毅深度学习][Neighbor Embedding-LLE]
  • 在JSP中实现JAVABEAN
  • 智能优化算法 | Matlab实现飞蛾扑火(MFO)(内含完整源码)
  • LSF 主机状态 unreach 分析
  • SpringBoot日志
  • 006集——where语句进行属性筛选——arcgis
  • 《动手学深度学习(PyTorch版)》笔记8.3
  • 静态时序分析:建立时间分析
  • 深入探究 HTTP 简化:httplib 库介绍
  • ARP欺骗攻击利用之抓取https协议的用户名与密码
  • <s-table>、<a-table>接收后端数据
  • [数学]高斯消元
  • 【Linux】gdb调试与make/makefile工具
  • 使用Arcgis裁剪
  • sheng的学习笔记-网络爬虫scrapy框架
  • Qt PCL学习(三):点云滤波
  • Ainx-V0.2-简单的连接封装与业务绑定
  • 《杨绛传:生活不易,保持优雅》读书摘录
  • ChatGPT在肾脏病学领域的专业准确性评估
  • Centos7.9安装SQLserver2017数据库
  • spring boot和spring cloud项目中配置文件application和bootstrap中的值与对应的配置类绑定处理
  • 每天一个数据分析题(一百五十四)