通过instructor 对于LLM 进行结构化输出

很多时候我们是需要对于LLM 生成的内容进行结构化输出的,比如我们希望利用LLM的能力,对于用户发布的内容进行情感分析,或者对于文档内容提取关键信息并转换为结构化的内容,instructor 是一个很不错的选择(支持多种语言的),以下演示下基于python 的

参考使用

  • 大模型部署
    为了方便使用了基于ollama 的本地部署,使用了google 最近发布的gemma2 模型(9b)
  • 安装
python -m venv venv 
pip install -U instructor
  • 文本情感分析
import instructor
from pydantic import BaseModel
from openai import OpenAI
 
# Define your desired output structure
class Sentiment(BaseModel):
    negative: bool
    positive: bool
    neutral: bool
client = instructor.from_openai(OpenAI(
    base_url="http://localhost:11434/v1/",
    api_key="gemma2",
), mode=instructor.Mode.JSON,)
 
# Extract structured data from natural language
response = client.chat.completions.create(
    model= "qwen2:7b",
    response_model=Sentiment,
    messages=[{"role": "user",  "content":  "开开心心上班,开开心心下班"},],
)
 
print(response)
  • 效果

说明

以上只是一个简单的使用,python 版本的instructor 基于了pydantic,我们可以进行很多灵活的控制,同时官方文档也比较全,值得仔细看看,有助于我们利用大模型的能力,解决不少实际的问题

参考资料

https://python.useinstructor.com/
https://python.useinstructor.com/examples/
https://github.com/jxnl/instructor/

posted on 2024-07-28 08:00  荣锋亮  阅读(18)  评论(0编辑  收藏  举报

导航