通过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   荣锋亮  阅读(172)  评论(5编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2021-07-28 docker 自定义网络解决网络冲突问题
2020-07-28 haproxy dataplaneapi golang sdk 简单使用
2020-07-28 haproxy dataplaneapi golang sdk 说明
2019-07-28 telegraf 学习二 几个概念
2018-07-28 cypress 端到端测试框架试用
2018-07-28 flow flow-typed 定义简单demo
2018-07-28 flow 编写flow-typed 定义(官方文档)

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示