ChatInterface 是 Gradio 提供的一个专门用于构建聊天应用的类,它可以帮助你创建一个交互式的对话系统,支持用户输入和模型的实时响应。这个接口非常适合构建聊天机器人、问答系统或其他对话类应用。
1. 基本使用
import gradio as gr
# 1. 基本使用
def test01():
# ChatInterface 的 fn 函数至少接收 2 个参数
# 第一个参数存储当前输入的内容
# 第二个参数存储聊天的历史记录
def respond(message, history):
print(history)
return f'Hello, {message}'
app = gr.ChatInterface(fn=respond, type='messages')
app.launch()
'''
注意:history 中存储的历史数据有两种格式:
1. tuples 形式:[['你好啊', 'Hello, 你好啊']]
2. messages 形式:[{'role': 'user', 'metadata': {'title': None}, 'content': '你好啊'},
{'role': 'assistant', 'metadata': {'title': None}, 'content': 'Hello, 你好啊'}]
建议使用 messages 形式,与诸多大语言模型能够兼容
'''
# 2. 不同元素
def test02():
def respond(message, history):
reply = f'Hello, {message}'
if message == 'md':
reply = gr.Markdown('<h1>这是 MarkDown 内容</h1>')
if message == 'image':
reply = gr.Image('assets/image.png')
if message == 'audio':
reply = gr.Audio('assets/audio_sample.wav')
if message == 'video':
reply = gr.Video('https://mengbaoliang.cn/wp-content/uploads/2023/09/d80a1c634a7bd12.mp4')
return reply
gr.ChatInterface(fn=respond).launch()
if __name__ == '__main__':
test01()
2. 参数介绍
import time
import gradio as gr
import random
# 1. 基本参数
def test01():
def response(message, history, extra_input1, extra_input2):
print('extra_input1:', extra_input1)
print('extra_input2:', extra_input2)
print('-' * 20)
return random.choice(['Hello', '你好'])
app = gr.ChatInterface(fn=response,
type='messages',
# 聊天界面的标题
title='聊天系统',
# 提交按钮文本
submit_btn='提交',
# 聊天界面的描述,显示在标题下方,支持 Markdown 和 HTML
description='聊天系统描述',
# 指定界面的主题样式
theme=gr.themes.Default(),
# 页面加载是否自动聚焦到文本框
autofocus=True,
# 额外增加的输入控件
additional_inputs=['number', 'text'],
# 额外输入控件标题,也可以是 Accordion 控件
additional_inputs_accordion='额外输入',
# 控制的是在事件运行时如何显示进度动画
show_progress='minimal',
# 是否充满窗口高度
fill_height=True)
app.launch()
# 2. 其他参数
def test02():
def response(message, history, extra_input1, extra_input2):
print('message:', message)
return random.choice(['Hello', '你好'])
# 注意:额外控件的数据也可以不构建
app = gr.ChatInterface(fn=response,
type='messages',
# 多模态输入,fn 接收到的数据格式: {'text': '', 'files': ['文件临时路径']}
multimodal=True,
# 输入样例
examples=[['你是谁?', 10, 'A'], ['我是谁?', 20, 'B']],
# 页面样式
# css='.placeholder-content{background-color:red;}',
additional_inputs=['number', 'text'],
additional_inputs_accordion='额外输入')
app.launch()
if __name__ == '__main__':
test02()

冀公网安备13050302001966号