forked from BBing/mindspore
62 lines
2.3 KiB
Python
62 lines
2.3 KiB
Python
import requests
|
||
from config import Config
|
||
import json
|
||
|
||
openai_key = Config.OPENAI_API_KEY
|
||
openai_url = Config.OPENAI_URL
|
||
MODEL = Config.OPENAI_MODEL
|
||
|
||
#与 OpenAI API 交互的模块,包括:封装与 OpenAI API 的请求;处理 API 返回的数据,并将其转换为项目需要的格式。
|
||
|
||
# 多语言支持:language 参数可以用来控制生成摘要的语言
|
||
def generate_summary(jina_data, language="zh", response_format="json", timeout=15):
|
||
if not openai_key or not openai_url:
|
||
print("OpenAI API Key or URL is missing.")
|
||
return None
|
||
|
||
# 根据用户选择的语言设置 prompt
|
||
prompt = f'''你的任务是作为一个高级翻译和编辑,理解发给你的内容,从中生产加工输出以下信息:标题、正文、图片。确保你的响应符合以下{response_format}结构,准确反映提取的数据,不做修改:
|
||
```{response_format}
|
||
{{
|
||
"title": "文章标题",
|
||
"content": "文章摘要",
|
||
"image": "文章包含的图片链接,保留url,如果没有留空"
|
||
}}
|
||
```重要的是你的输出严格遵守这种格式。
|
||
-严格确保统一翻译为{language}
|
||
-不翻译公司名称、人名'''
|
||
|
||
siliconflow_payload = {
|
||
"model": MODEL,
|
||
"messages": [
|
||
{
|
||
"role": "assistant",
|
||
"content": f"{prompt}{jina_data}"
|
||
}
|
||
]
|
||
}
|
||
siliconflow_headers = {
|
||
"accept": f"application/{response_format}",
|
||
"content-type": "application/json",
|
||
"authorization": f"Bearer {openai_key}"
|
||
}
|
||
|
||
try:
|
||
siliconflow_response = requests.post(siliconflow_url, json=siliconflow_payload, headers=siliconflow_headers, timeout=timeout)
|
||
siliconflow_response.raise_for_status()
|
||
response = siliconflow_response.json()
|
||
result_content = response['choices'][0]['message']['content']
|
||
|
||
print("Generated summary successfully.")
|
||
try:
|
||
json_str = result_content.strip().lstrip(f'```{response_format}').rstrip('```').strip()
|
||
parsed_json = json.loads(json_str)
|
||
return parsed_json
|
||
except json.JSONDecodeError as e:
|
||
print(f"Failed to parse {response_format} response: {e}")
|
||
return None
|
||
|
||
except requests.exceptions.RequestException as e:
|
||
print(f"SiliconFlow 请求错误:{e}")
|
||
return None
|