介绍
最近,一直在使用 ChatGPT 和搭建 API 交互页面来生成自然语言文本。在这篇博客中,这里分享一下我的使用体验以及一些最佳实践。
ChatGPT
ChatGPT 是一个自然语言生成器,它使用了深度学习技术来生成逼真的文本。目前我使用最多的就是用ChatGPT来辅助写代码了。
以下是一个使用 Python 代码来调用 ChatGPT 的示例:
import openai
openai.api_key = "YOUR_API_KEY"
prompt = "What are the benefits of using ChatGPT?"
model = "text-davinci-002"
response = openai.Completion.create(
engine=model,
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
print(response.choices[0].text)
API 交互页面
API 交互页面是一个允许用户通过 Web 界面来与 API 交互的页面。我使用 fastapi、vue框架来搭建了我的 API 交互页面。在这个页面上,我可以通过输入一些参数来调用我的 ChatGPT API,并将生成的文本呈现在页面上。
以下是一个使用 fastapi 框架和 vue框架来搭建 API 交互页面的示例:
import os
from fastapi import FastAPI,Request
from fastapi.responses import HTMLResponse # 响应html
# from fastapi.middleware.cors import CORSMiddleware
import openai
app = FastAPI()
def get_chat_api(prompt):
openai.api_key = "your_key"
model_engine = "text-davinci-003"
completions = openai.Completion.create(
engine=model_engine,
prompt=prompt,
max_tokens=2048,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
return message
@app.get("/")
def index():
html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'index.html')
html_content = ''
with open(html_path,encoding='utf-8') as f:
html_content = f.read()
return HTMLResponse(content=html_content, status_code=200)
@app.post("/chatgpt")
async def chatgpt(request: Request):
item_dict = await request.json()
isauth = int(item_dict.get("isauth", ""))
prompt = item_dict.get("prompt", "").strip()
if isauth == 1:
try:
data = get_chat_api(prompt)
except Exception as e:
return {"code": -1, "message": "接口调用失败"}
return {"code": 0, "data": data}
return {"code": -1, "message": "接口认证不成功"}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=9000)
结论
使用 ChatGPT 和搭建 API 交互页面是一个非常有趣和有用的体验。我希望这篇博客可以帮助你了解这些工具的使用,并给你一些灵感来尝试它们。如果你想要进一步探索 ChatGPT 和 API 交互页面,可以尝试使用我的示例代码和文档,以及访问我提供的体验地址来深入了解。
网友评论