instructor 库实现llm与sqlite数据库连接

代码

import instructor
from openai import OpenAI
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine, Session

# Define the model that will serve as a Table for the database
class Hero(SQLModel, instructor.OpenAISchema, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

# Function to query OpenAI for a Hero record
client = instructor.from_openai(OpenAI(api_key = "your api key",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"))

def create_hero() -> Hero:
    return client.chat.completions.create(
        model="qwen-turbo",
        response_model=Hero,
        messages=[
            {"role": "user", "content": "Make a new superhero"},
        ],
    )

# Insert the response into the database
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine, checkfirst=True)

hero = create_hero()
print(hero.model_dump())


with Session(engine) as session:
    session.add(hero)
    session.commit()
{'name': 'Mighty Beaver', 'secret_name': 'The Mighty Beaver of Power', 'id': None, 'age': None}

生成数据库文件database.db
可用下面代码查看database.bd

## 

from sqlmodel import Session, select

# 查询所有英雄数据
with Session(engine) as session:
    statement = select(Hero)
    heroes = session.exec(statement).all()
    
    print("\n数据库中的英雄列表:")
    for hero in heroes:
        print(f"\nID: {hero.id}")
        print(f"英雄名: {hero.name}")
        print(f"秘密身份: {hero.secret_name}")
        print(f"年龄: {hero.age}")
        print("-" * 30)
数据库中的英雄列表:

ID: 1
英雄名: Mighty Beaver
秘密身份: The Mighty Beaver of Power
年龄: None
------------------------------

代码解释

1. 导入必要模块

import instructor
from openai import OpenAI
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine, Session
  • instructor: 用于增强 OpenAI API 的结构化输出功能
  • SQLModel: 结合了 SQLAlchemy 和 Pydantic 的 ORM 框架
  • Optional: 用于标注可选字段
  • Field: 用于定义数据库字段属性

2. 定义数据模型

class Hero(SQLModel, instructor.OpenAISchema, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None
  • 继承 SQLModel 和 OpenAISchema,使其同时具备数据库表和 AI 输出结构功能
  • id: 自增主键字段
  • name: 英雄名字
  • secret_name: 秘密身份
  • age: 可选的年龄字段

3. 初始化 AI 客户端

client = instructor.from_openai(OpenAI(
    api_key = "sk-xxx",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"))
  • 使用通义千问 API
  • instructor 包装使其支持结构化输出

4. 创建英雄函数

def create_hero() -> Hero:
    return client.chat.completions.create(
        model="qwen-turbo",
        response_model=Hero,
        messages=[
            {"role": "user", "content": "Make a new superhero"},
        ],
    )
  • 调用 AI 生成英雄信息
  • 指定返回类型为 Hero 模型
  • AI 会按照模型结构返回数据

5. 数据库操作

engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine, checkfirst=True)

hero = create_hero()
print(hero.model_dump())

with Session(engine) as session:
    session.add(hero)
    session.commit()
  • 创建 SQLite 数据库连接
  • 创建数据库表结构
  • 生成英雄数据并打印
  • 将数据保存到数据库

代码的主要特点:

  1. 结合 AI 生成和数据库存储
  2. 使用 SQLModel 简化数据库操作
  3. 结构化的数据模型定义
  4. 自动的数据验证和类型检查

类似例子

import instructor
from openai import OpenAI
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine, Session

# 定义图书模型
class Book(SQLModel, instructor.OpenAISchema, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    title: str = Field(description="书籍标题")
    author: str = Field(description="作者名称")
    genre: str = Field(description="图书类型,如科幻、文学等")
    publish_year: Optional[int] = Field(default=None, description="出版年份")
    rating: Optional[float] = Field(default=None, ge=0, le=5, description="评分(0-5)")

# 初始化 OpenAI 客户端
client = instructor.from_openai(OpenAI(
    api_key = "your api key",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
))

def create_book() -> Book:
    return client.chat.completions.create(
        model="qwen-turbo",
        response_model=Book,
        messages=[
            {
                "role": "user", 
                "content": "请推荐一本经典图书,包括书名、作者、类型、出版年份和评分"
            },
        ],
    )

# 创建数据库引擎和表
engine = create_engine("sqlite:///books.db")
SQLModel.metadata.create_all(engine, checkfirst=True)

# 创建并保存图书记录
book = create_book()
print("新增图书信息:")
print(book.model_dump())

# 将图书保存到数据库
with Session(engine) as session:
    session.add(book)
    session.commit()
新增图书信息:
{'id': None, 'title': '一九八四', 'author': '乔治·奥威尔', 'genre': '政治小说', 'publish_year': 1949, 'rating': 4.5}
from sqlmodel import Session, select
# 查看所有图书
with Session(engine) as session:
    # 查询所有记录
    statement = select(Book)
    books = session.exec(statement).all()
    
    print("\n所有图书列表:")
    for book in books:
        print(f"\nID: {book.id}")
        print(f"书名: {book.title}")
        print(f"作者: {book.author}")
        print(f"类型: {book.genre}")
        print(f"出版年份: {book.publish_year}")
        print(f"评分: {book.rating}")
所有图书列表:

ID: 1
书名: 一九八四
作者: 乔治·奥威尔
类型: 政治小说
出版年份: 1949
评分: 4.5

参考链接:https://github.com/instructor-ai/instructor/tree/main

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值