python 调用HuggingFaceHub 的api 代码
时间: 2024-05-12 17:15:48 浏览: 20
下面是一个使用Hugging Face Hub API获取预训练模型的Python示例代码:
```python
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
# 使用Hugging Face Hub API获取模型和tokenizer
model_name = "microsoft/DialoGPT-medium"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# 创建对话生成pipeline
chat_pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer)
# 与机器人进行对话
chat_history = chat_pipeline("Hi, how are you?")
print(chat_history[0]["generated_text"])
```
这个示例代码首先使用`AutoTokenizer`和`AutoModelForCausalLM`类从Hugging Face Hub获取预训练模型和tokenizer。然后,它创建了一个`text-generation`的pipeline,用于生成文本,该pipeline将模型和tokenizer传递给一个`pipeline`函数。最后,它使用`chat_pipeline`与机器人进行对话并打印输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)