python 调用 DeepSeek/ ChatGPT API 实例
DeepSeek
https://www.deepseek.com/
DeepSeek API: https://platform.deepseek.com/sign_in
提示库:https://api-docs.deepseek.com/zh-cn/prompt-library/
连接测试代码:
from openai import OpenAI
client = OpenAI(api_key="你的API码", base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
stream=False
)
print(response.choices[0].message.content)
如果成功,则会显示:
Hello! How can I assist you today? 😊
多轮对话及上下文拼接代码
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# Round 1
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
messages.append(response.choices[0].message)
print(f"Messages Round 1: {messages}")
# Round 2
messages.append({"role": "user", "content": "What is the second?"})
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
messages.append(response.choices[0].message)
print(f"Messages Round 2: {messages}")
提问DeepSeek,并将问题与回答都保存到word文档中
import requests
from docx import Document
# 设置 DeepSeek API 的 URL 和 API 密钥
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
API_KEY = "your_deepseek_api_key_here"
# 创建一个 Word 文档
doc = Document()
def ask_deepseek(question):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "deepseek-chat", # 根据实际情况调整模型名称
"messages": [{"role": "user", "content": question}]
}
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
answer = result['choices'][0]['message']['content']
return answer
else:
print(f"Error: {response.status_code} - {response.text}")
return None
def save_to_word(question, answer):
# 添加问题和回答到 Word 文档
doc.add_paragraph(f"问题: {question}")
doc.add_paragraph(f"回答: {answer}")
doc.add_paragraph("-" * 40) # 添加分隔线
def main():
while True:
# 获取用户输入的问题
question = input("请输入你的问题(输入 'exit' 退出): ")
if question.lower() == 'exit':
break
# 调用 DeepSeek API 获取回答
answer = ask_deepseek(question)
if answer:
print(f"回答: {answer}")
# 保存问题和回答到 Word 文档
save_to_word(question, answer)
else:
print("无法获取回答。")
# 保存 Word 文档
doc.save("questions_and_answers.docx")
print("问题和回答已保存到 questions_and_answers.docx")
if __name__ == "__main__":
main()
chatgpt 访问
网页直接访问:登录:https://chat.openai.com/auth/login
然后访问:https://chat.openai.com/chat
这时你就可以开始尽情和机器人聊天了,或者这里是个免费版(仅10次):https://book.employleague.cn/chatGTP
api接口
如果使用api接口,下面一段可用的,代理情况下使用的代码:
import openai
import os
# 只需要在python里设置代理即可
os.environ["HTTP_PROXY"] = "http://127.0.0.1:7890"
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:7890"
openai.api_key = 'sk-YOUR-API'
def ChatGPT_test(problem_message):
model_engine = "text-davinci-003"
completions = openai.Completion.create(
engine=model_engine,
prompt=problem_message,
max_tokens=1024,
n=1,
stop=None,
temperature=0.9,)
message = completions.choices[0].text
return message
if __name__ == "__main__": #主函数入口
input_message1=ChatGPT_test('2023年3月22日之前有哪些外资银行离开了中国?')
print(input_message1)
#另一种提问方式:
def test_openai(string):
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": string}]
)
return completion['choices'][0]['message']['content'].strip()
Answer2 = test_openai(Question2)
print(Answer2)
亲测非常有效!(可奇怪的是我问的是2023年,它答的是2020年,是因为数据库没更新吗?)
更进一步,用word文档保存问过的问题
import docx
from docx import Document # 导入相关库
from docx.shared import Inches,Cm,Pt
from docx.document import Document as Doc # 导入这个库的原因是在我们写相关函数的时候会得到提示,要不然许多函数得不到提示无法写出来,太过复杂了
file_path ='D:\MyData\PY files\\'
doc_name = 'chatGPT问答记录.docx'
document = docx.Document( file_path + doc_name )
'''
#新建文件
document = Document() # type: Doc
# 添加大标题(上面一行的注释也非常重要,否则无法获得提示)
document.add_heading('chatGPT & John问答记录', 0)
# 添加一级标题
document.add_heading(Question1, level=1)
# 添加带样式的段落
document.add_paragraph(Answer1)
doc.add_paragraph('这是一个段落')
doc.add_heading('标题',0)
doc.add_heading('标题1',1)
doc.add_heading('标题2',2)
doc.add_heading('标题3',3)
doc.add_heading('标题4',4)
doc = docx.Document( file_path+doc_name )
document.save(doc_name)
'''
# 换行
document.paragraphs[0].runs[0].add_break()
# 添加一级标题
document.add_heading(Question1, level=1)
# 添加带样式的段落
document.add_paragraph(Answer1)
# 添加一级标题
document.add_heading(Question2, level=1)
# 添加带样式的段落
document.add_paragraph(Answer2)
doc = docx.Document( file_path+doc_name )
document.save(doc_name)
#自定义一个函数将全部的paragraph段落内容存起来,每个paragraph段落之间用换行符\n隔开。
def getText(fileName):
doc = docx.Document(fileName)
TextList = []
for paragraph in doc.paragraphs:
TextList.append(paragraph.text)
return '\n'.join(TextList)
print(getText(doc_name))
相关材料
sms-activate.org出品的chatGPT注册全指南
https://sms-activate.org/cn/info/ChatGPT
ChatGPT Plus官方推荐新手教程
https://chatgpt-plus.github.io/chatgpt-plus/
ChatGPT API Key申请使用及充值教程【典藏】
https://juejin.cn/post/7206249233115643959
OpenAI 推出超神 ChatGPT 注册攻略来了
https://juejin.cn/post/7173447848292253704
ChatGPT_API_用法
https://www.jianshu.com/p/08765e9058c8
如何调用ChatGPT的API接口到官方例子的说明以及GitHub上的源码应用
https://www.rstk.cn/news/24374.html?action=onClick
MS快速入门:开始通过 Azure OpenAI 服务使用 ChatGPT
https://platform.openai.com/docs/guides/chat
当然,你首先需要一个clash或者梯子https://renzhe.cloud/
用户手册:https://docs.cfw.lbyczf.com/
https://github.com/Fndroid/clash_for_windows_pkg/releases
特别推荐
https://github.com/lzwme/chatgpt-sites
⭐⭐⭐] https://chat.lmsys.org FastChat。 基于 Vicuna: An Open Chatbot Impressing GPT-4
[⭐⭐⭐] https://modelscope.cn 魔塔社区(阿里达摩院)
[⭐⭐⭐🧑💻] https://www.weijiwangluo.com/talk ATalk。 是一个基于gpt-3.5-turbo引擎封装的网站,通过输入文本,输出相应的回答,实现智能聊天的功能
[⭐⭐] https://chat.gptplus.one ChatGPT Web。
[⭐⭐] https://chat.wobcw.com AIChat。 支持文字、翻译、画图的聊天机器人
[⭐⭐] https://chat.xiami.one 虾米Chat。
[⭐⭐] https://chatgpt.peterdavehello.org Free ChatGPT。 This is a free ChatGPT provided by @PeterDaveHello for testing purpose
[⭐⭐] https://chatgpt1680.zeabur.app ChatGPT Web - idc1680。
[⭐⭐] https://chatgptfly.club WoChat。 程序员Jack Dog 和 Tom Dog 为了方便部分同学使用而开发的免费社区平台。支持文字、语音、翻译、画图的聊天机器人
[⭐⭐] https://gpt.xcbl.cc 老北鼻AI智能助手。 您的私人ChatGPT聊天机器人。
[⭐⭐] https://smartchat.unknownbyte.com SmartChat。
[⭐⭐] https://smartchat.yihezu.cn SmartChat。
[⭐⭐🧑💻] https://www.gptbot.icu ChatGPT。 网站密码关注公众号:Maynor学长 回复“密码”获取
[⭐⭐] https://www.hayo.com HayoAI。 一款融合AI聊天、AI艺术创作、AI工具推荐、AI资讯及技术创新交流的高效应用。【每日使用次数限制为每项功能50次,重置时间为北京时间的0点】
[⭐⭐🧑💻] https://xmind.ai Xmind Copilot。 Xmind Copilot 思维导图 AI 助手