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
------------------------------
import instructor
from openai import OpenAI
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine, Session
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
client = instructor.from_openai(OpenAI(
api_key = "sk-xxx",
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"},
],
)
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()
代码的主要特点:
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