Word接入chatgpt的代码块
时间: 2023-09-26 11:14:16 浏览: 180
以下是使用Python中的Hugging Face Transformers库接入ChatGPT的示例代码:
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# 加载预训练的ChatGPT模型和tokenizer
model_name = "microsoft/DialoGPT-medium"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# 设置对话历史和新输入
history = "Hi, how are you doing today?"
new_input = "I'm doing well, thanks for asking. How about you?"
# 将对话历史和新输入编码为tokenizer的输入格式
input_ids = tokenizer.encode(history + new_input, return_tensors='pt')
# 生成回复
bot_output = model.generate(
input_ids,
max_length=1000,
pad_token_id=tokenizer.eos_token_id
)
# 将模型输出解码为人类可读的文本
bot_reply = tokenizer.decode(bot_output[0], skip_special_tokens=True)
# 打印回复
print("Bot: ", bot_reply)
```
以上代码加载了预训练的ChatGPT模型和tokenizer,并使用输入序列生成了回复。你可以根据需要修改对话历史、新输入、最大生成长度等参数。
阅读全文