加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
AI_problems.py 3.27 KB
一键复制 编辑 原始数据 按行查看 历史
m_engmeng 提交于 2023-10-31 08:27 . AI生成英语、语文阅读题
import SparkApi
import json
#以下密钥信息从控制台获取
appid = "224fd526" #填写控制台中获取的 APPID 信息
api_secret = "NWYwYWZmZGI4NjUyOTM3NjQzMTYzOGQ5" #填写控制台中获取的 APISecret 信息
api_key ="4896b24fa85b93f88d91ef29d33e8c2c" #填写控制台中获取的 APIKey 信息
#用于配置大模型版本,
domain = "generalv3" # v3版本
#云端环境的服务地址
Spark_url = "wss://spark-api.xf-yun.com/v3.1/chat" # v3环境的地址
"""-------------------------------------------"""
""" 有关讯飞接口调用的函数 """
"""-------------------------------------------"""
def getText(text, role,content):
jsoncon = {}
jsoncon["role"] = role
jsoncon["content"] = content
text.append(jsoncon)
return text
def getlength(text):
length = 0
for content in text:
temp = content["content"]
leng = len(temp)
length += leng
return length
def checklen(text):
while (getlength(text) > 8000):
del text[0]
return text
def generate_english_reading(subject, grade):
"""根据年级请求AI,获得返回文本"""
text = []
request = f'请以json的格式输出一篇小学{grade}{subject}阅读文章,题目和答案' + '格式参考如下{"article:"","question":[{"Q":" ","A":" "}]}'
question = checklen(getText(text, "user", request))
SparkApi.answer = ""
# print("SparkApi.answer:", SparkApi.answer)
SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)
return SparkApi.answer
def generate_english_reading_problems(subject, grade):
"""生成期望格式的题目"""
text = generate_english_reading(subject, grade) + '\n' # 获取请求后返回的文本
text_json = json.loads(text)
# print(type(text_json))
page = text_json['article']
qa_list = text_json['question']
q_list = []
a_list = []
for i, qa in enumerate(qa_list, 1):
q_list.append("{}.{}".format(i, qa['Q']))
a_list.append("{}.{}".format(i, qa['A']))
question = "请阅读以下文章回答相关问题:\n{}\n\n{}".format(page, '\n'.join(q_list))
answer = "\n".join(a_list)
return question, answer
def get_request(subject, grade, topic, number, difficulty):
problems = []
if subject == '英语' and grade not in ['三年级', '四年级', '五年级', '六年级']:
questions = [{'question_text': "问题请求错误", 'answer': "暂无答案"}]
return questions
for i in range(number):
question, answer = generate_english_reading_problems(subject, grade)
while (question, answer) in problems:
# 防止出现重复的题目
question, answer = generate_english_reading_problems(subject, grade)
problems.append((question, answer))
questions = []
for i, (problem, answer) in enumerate(problems, 1):
questions.append({'question_text': f"{problem}", 'answer': f"{answer}"})
return questions
if __name__ == '__main__':
Grades = ['二年级','三年级', '四年级', '五年级', '六年级']
for grade in Grades:
questions = get_request("英语", grade, 1, 1, 'hard')
for q in questions:
print(q)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化