OpenAI ChatGPT是一种人工智能聊天机器人,基于大规模的深度学习模型,专门用于生成自然语言文本。它能够理解和生成人类语言,因此能够与用户进行对话、回答问题、提供信息和协助完成各种任务。ChatGPT能够用于多种应用场景,包括客户服务、教育辅导、内容创作等等。
ChatGPT的底层技术基于Transformer架构,经过大量文本数据的训练,使其在理解上下文和生成连贯的回应方面表现出色。用户可以通过输入文本与其互动,ChatGPT会根据上下文生成相关的答案或建议。
Python接口
申请第三方测试key
安装OpenAI模块
pip install openai
from openai import OpenAI
def chat_openai(question, model="gpt-3.5-turbo"):
text = ''
stream = True
openai_url = 'https://api.chatanywhere.tech/v1'
openai_key = 'sk-xxx'
client = OpenAI(base_url=openai_url, api_key=openai_key)
response = client.chat.completions.create(model=model, stream=stream, messages=[
{"role": "user", "content": question},
])
if stream:
for chunk in response:
content = chunk.choices[0].delta.content
if not content:
continue
text += content
print(content, end='', flush=True)
else:
content = response.choices[0].message.content
text += content
print(content)
print('\n')
return text
if __name__ == '__main__':
chat_openai('你是谁')
Kimi的API兼容OpenAI,只需要修改url和key即可,API KEY需要到官方网站申请,模型支持
- moonshot-v1-128k
- moonshot-v1-32k
- moonshot-v1-8k
Kimi url
Kimi API key申请
Gradio创建webUI
Grdio是一个开源Python库,可以快速创建大语言模型的交互webUI,无需了解HTTP、CSS、JavaScript等web语言。
安装gradio库
pip install gradio
在上一个例子基础上添加gradio创建的UI
from openai import OpenAI
import gradio as gr
def chat_openai(self, question, model="gpt-3.5-turbo"):
text = ''
stream = True
openai_url = 'https://api.chatanywhere.tech/v1'
openai_key = 'sk-xxx'
client = OpenAI(base_url=openai_url, api_key=openai_key)
response = client.chat.completions.create(model=model, stream=stream, messages=[
{"role": "user", "content": question},
])
if stream:
for chunk in response:
content = chunk.choices[0].delta.content
if not content:
continue
text += content
print(content, end='', flush=True)
yield text
else:
content = response.choices[0].message.content
text += content
print(content)
yield text
print('\n')
return text
def chat_response(message, history):
resp = chat_openai(message)
for r in resp:
yield r
def webui():
demo = gr.ChatInterface(fn=chat_response, type='messages', examples=['你好', '你是谁'])
demo.launch(server_name='0.0.0.0')
if __name__ == '__main__':
webui()
运行效果如下图所示
评论区