可以给出具体的代码吗
时间: 2023-10-22 12:09:28 浏览: 13
当然可以,以下是一个简单的 Python 代码示例,使用了 Hugging Face 的 Transformers 库和 PyTorch 框架:
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# 加载模型和分词器
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
# 与 AI 进行对话
conversation_history = []
while True:
# 接收用户输入
user_input = input("User: ")
# 将用户输入添加到历史记录中
conversation_history.append(user_input)
# 将历史记录编码为模型输入
input_ids = tokenizer.encode(" ".join(conversation_history), return_tensors='pt')
# 生成回复
output = model.generate(input_ids=input_ids, max_length=50, do_sample=True, top_p=0.9, top_k=0)
# 将回复解码为人类可读文本并打印出来
response = tokenizer.decode(output[0], skip_special_tokens=True)
print("AI: " + response)
# 将 AI 的回复添加到历史记录中
conversation_history.append(response)
```
该代码使用 Microsoft 提供的 DialoGPT-medium 模型进行对话生成。用户输入会被添加到历史记录中,并编码为模型输入。模型生成回复,并将其解码为人类可读文本后打印出来,并将回复添加到历史记录中,以便在下一轮对话中参考。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)