运行步骤:
-
确保Python环境已经安装: 确保你的系统上已经安装了Python 3.如果没有,请先从Python官网下载并安装Python 3.
-
确保你有一个OpenAI的API密钥: 如果还没有,可以访问OpenAI官网申请一个API密钥.
-
如何获取API,打开这个网站:https://platform.openai.com/ 找到个人默认项目
-
保存脚本: 将以下代码保存为一个Python文件,比如命名为
danci.py
:#!/usr/bin/env python3 ''' Call Chatdanci and get result. ''' import json import urllib import urllib.request def danci_completion(api_key, model, prompt, content): url = 'https://api.openai.com/v1/chat/completions' headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + api_key } body = { 'model': model, 'messages': [ { 'role': 'system', 'content': prompt }, { 'role': 'user', 'content': content } ] } data = bytes(json.dumps(body), encoding='utf-8') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as resp: s = resp.read() output_json = json.loads(s) output_content = output_json['choices'][0]['message']['content'] if output_content.startswith('```json\n'): output_content = output_content[8:len(output_content)-3] if output_content.startswith('```\n'): output_content = output_content[4:len(output_content)-3] return output_content if __name__ == '__main__': api_key = input('API key: ') word = input('English word: ') model = 'danci-4' prompt = '目前准备屠鸭' content = f'请给出英文单词"{word}"的音标、英文解释、中文解释,英文填空题、答案和中文翻译,并以如下JSON格式返回:' content = content + '''
{ "phonetic": 音标, "explain_english": 英文解释, "explain_chinese": 中文解释, "exam": { "question": 英文填空题, "answer": 答案, "translation": 中文翻译 } }
''' result = danci_completion(api_key, model, prompt, content) print(result)
-
运行脚本: 打开终端或命令行,导航到保存
danci.py
脚本的目录,然后运行以下命令:python3 danci.py
-
输入API密钥和单词: 程序会提示输入API密钥和要查询的英文单词.输入完毕后,按回车键确认.
-
查看输出: 程序会调用OpenAI的API,返回指定单词的相关信息并以JSON格式打印出来.
示例运行:
$ python3 danci.py
API key: sk-GWlz...rFnW
English word: excellent
输出:
{
"phonetic": "/ˈɛksələnt/",
"explain_english": "Extremely good; outstanding.",
"explain_chinese": "极好的;出色的;卓越的",
"exam": {
"question": "The performance was __________, everyone appreciated it.",
"answer": "excellent",
"translation": "该表演非常出色,所有人都对此赞赏有加."
}
}
可能遇到的问题和解决方法:
-
网络连接问题: 确保你的计算机能够访问互联网,因为脚本需要连接到OpenAI的API服务器.
-
API密钥错误或无效: 确保输入的API密钥正确且有效.如果密钥无效,会导致API请求失败.
-
API请求限制: 如果你的API调用次数超过了OpenAI的限制,可能需要升级你的API套餐或者等待调用次数重置.
感谢大家的关注和支持!想了解更多Python编程精彩知识内容,请关注我的 微信公众号:python小胡子,有最新最前沿的的python知识和人工智能AI与大家共享,同时,如果你觉得这篇文章对你有帮助,不妨点个赞,并点击关注.动动你发财的手,万分感谢!!!
原创文章不易,求点赞、在看、转发或留言,这样对我创作下一个精美文章会有莫大的动力!