分享两点:1.人工智能的编程能力真的非常突出 2.个人的追问能力和兴趣探索在泛智能问答这块是相当需要的,意味着我们人人都可以更聪明更睿智。直接呈现代码,api key到官网付费获取就好针对国内用户可以说报价十分满分友好:
这段代码还结合了超长段落文本分割+question提问的思路,api key的一个tokens限制在65000-70000左右,之前专门调用脚本测试过,大概这个限制是针对于咱们个人用户设置,企业会有额外定制版。可以说这个限制也是相当宽泛了。
想要快速读懂这段代码,可以直接copy到通义千问的网页版进行提问:“解释这段代码”。希望大家都越来越来智能自主,变强。
import os
import requests
import time
# 忽略SSL证书验证警告(如果适用)
# 注意:在生产环境中应避免忽略SSL证书验证,这里仅为示例目的
# import ssl
# ssl._create_default_https_context = ssl._create_unverified_context
class DeepSeekClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://api.deepseek.com/v1'
def chat_completion(self, messages, model='deepseek-reasoner', stream=False):
headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
try:
response = requests.post(
url=f'{self.base_url}/chat/completions',
headers=headers,
json={'model': model, 'messages': messages, 'stream': stream}
)
response.raise_for_status()
return response.json()['choices'][0]['message']['content']
except requests.exceptions.RequestException as e:
print(f"请求失败: {str(e)}")
if hasattr(e, 'response') and e.response is not None:
print("响应内容:", e.response.text)
raise
def split_content(content, max_tokens=64000):
chunks = []
while len(content) > max_tokens:
chunks.append(content[:max_tokens])
content = content[max_tokens:]
if content:
chunks.append(content)
return chunks
def read_files_and_ask_questions(folder_path, output_file):
try:
# 获取文件夹下所有 .txt 文件
txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
# 初始化 DeepSeek 客户端
client = DeepSeekClient(api_key='sk-????')
# 打开输出文件以追加模式写入
with open(output_file, 'w', encoding='utf-8') as output_f:
for file_name in txt_files:
file_path = os.path.join(folder_path, file_name)
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as file:
full_content = file.read()
# 分割内容
content_chunks = split_content(full_content, max_tokens=3000) # 假设每个块不超过3000字符
# 定义问题列表
questions = [
"回答如下:1.什么行业 2.增量还是缩量 3.有什么创新。如果不符合,可以只返回none"
]
print(f"开始分析文件:{file_name}\n")
# 遍历问题并提问
for question in questions:
for i, chunk in enumerate(content_chunks):
combined_content = (
f"{chunk}\n\n{question}\n\n"
"请参考历史投喂的信息,做出回答的更新迭代,并确保回答不超过300字。"
)
messages = [{"role": "user", "content": combined_content}]
# 调用 DeepSeek API 获取回答
response = client.chat_completion(messages)
# 标记第几次回答
response_mark = f"文件:{file_name} - 第 {i + 1} 片段 - 问题:{question}\n"
# 将回答追加到输出文件
output_f.write(response_mark)
output_f.write(f"回答:{response}\n{'-' * 50}\n")
print(f"{response_mark}回答:{response}\n{'-' * 50}")
# 等待 5 秒后再发起下一次请求
if i < len(content_chunks) - 1 or question != questions[-1]:
print("等待 5 秒后继续...\n")
time.sleep(5)
except FileNotFoundError:
print(f"错误:未找到文件夹 {folder_path}")
except Exception as e:
print(f"未知错误:{str(e)}")
if __name__ == "__main__":
# 设置文件夹路径和输出文件路径
folder_path = os.path.join(os.getcwd(), "财经新闻")
output_file = os.path.join(os.getcwd(), "国产新闻联播总结.txt")
# 调用函数读取文件并提问
read_files_and_ask_questions(folder_path, output_file)