由LLM驅動的打字稿中的結構化提取,為簡單,透明度和控製而設計。
通過OpenAI的函數調用API和ZOD,使用靜態類型推理驗證了Typescript-First-First-Firt schema驗證。教師的簡單性,透明度和以用戶為中心的設計而脫穎而出。無論您是經驗豐富的開發人員還是剛開始,您都會發現教練的方法直觀而可名。
bun add @instructor-ai/instructor zod openai
npm i @instructor-ai/instructor zod openai
pnpm add @instructor-ai/instructor zod openai
要查看所有提示和提取數據的提示和技巧,請查看文檔。
import Instructor from "@instructor-ai/instructor" ;
import OpenAI from "openai"
import { z } from "zod"
const oai = new OpenAI ( {
apiKey : process . env . OPENAI_API_KEY ?? undefined ,
organization : process . env . OPENAI_ORG_ID ?? undefined
} )
const client = Instructor ( {
client : oai ,
mode : "TOOLS"
} )
const UserSchema = z . object ( {
// Description will be used in the prompt
age : z . number ( ) . describe ( "The age of the user" ) ,
name : z . string ( )
} )
// User will be of type z.infer<typeof UserSchema>
const user = await client . chat . completions . create ( {
messages : [ { role : "user" , content : "Jason Liu is 30 years old" } ] ,
model : "gpt-3.5-turbo" ,
response_model : {
schema : UserSchema ,
name : "User"
}
} )
console . log ( user )
// { age: 30, name: "Jason Liu" }
創建講師客戶端的主要課程。
創建Instructor
function createInstructor < C extends GenericClient | OpenAI > ( args : {
client : OpenAILikeClient < C > ;
mode : Mode ;
debug ?: boolean ;
} ) : InstructorClient < C >
創建講師類的實例。
返回擴展的OpenAi型客戶端。
chat.completions.create
chat . completions . create <
T extends z . AnyZodObject ,
P extends T extends z . AnyZodObject ? ChatCompletionCreateParamsWithModel < T >
: ClientTypeChatCompletionParams < OpenAILikeClient < C > > & { response_model : never }
> (
params : P
) : Promise < ReturnTypeBasedOnParams < typeof this . client , P > >
當參數中存在Response_model時,會根據提供的模式創建一個結構化提取的聊天完成 - 否則將返回提供給所提供的客戶端。
講師支持不同模式來定義語言模型響應的結構和格式。這些模式在zod-stream
軟件包中定義,如下:
FUNCTIONS
(棄用):使用OpenAI的呼叫API生成響應。它映射到函數調用API的必要參數,包括function_call
和functions
屬性。
TOOLS
:使用OpenAI的工具規範生成響應。它為工具規範構建了所需的參數,包括tool_choice
和tools
屬性。
JSON
:它將response_format
設置為json_object
,並在系統消息中包含JSON模式以指導響應生成。 (一起&Anyscale)
MD_JSON
:生成嵌入在Markdown代碼塊中的JSON格式的響應。它在系統消息中包括JSON模式,並期望響應是在Markdown代碼塊中包裹的有效JSON對象。
JSON_SCHEMA
:使用“ JSON模式”生成響應,該響應符合提供的JSON模式。它將response_format
設置為使用提供的架構的json_object
,並在系統消息中包含架構描述。
講師支持部分流的完成,使您可以在模型生成其響應時實時接收提取的數據。這對於提供更具交互性的用戶體驗或逐步處理大量數據可能很有用。
import Instructor from "@instructor-ai/instructor"
import OpenAI from "openai"
import { z } from "zod"
const textBlock = `
In our recent online meeting, participants from various backgrounds joined to discuss the upcoming tech conference.
The names and contact details of the participants were as follows:
- Name: John Doe, Email: [email protected], Twitter: @TechGuru44
- Name: Jane Smith, Email: [email protected], Twitter: @DigitalDiva88
- Name: Alex Johnson, Email: [email protected], Twitter: @CodeMaster2023
During the meeting, we agreed on several key points. The conference will be held on March 15th, 2024, at the Grand Tech Arena located at 4521 Innovation Drive. Dr. Emily Johnson, a renowned AI researcher, will be our keynote speaker. The budget for the event is set at $50,000, covering venue costs, speaker fees, and promotional activities.
Each participant is expected to contribute an article to the conference blog by February 20th. A follow-up meeting is scheduled for January 25th at 3 PM GMT to finalize the agenda and confirm the list of speakers.
`
async function extractData ( ) {
const ExtractionSchema = z . object ( {
users : z . array (
z . object ( {
name : z . string ( ) ,
handle : z . string ( ) ,
twitter : z . string ( )
} )
) . min ( 3 ) ,
location : z . string ( ) ,
budget : z . number ( )
} )
const oai = new OpenAI ( {
apiKey : process . env . OPENAI_API_KEY ?? undefined ,
organization : process . env . OPENAI_ORG_ID ?? undefined
} )
const client = Instructor ( {
client : oai ,
mode : "TOOLS"
} )
const extractionStream = await client . chat . completions . create ( {
messages : [ { role : "user" , content : textBlock } ] ,
model : "gpt-3.5-turbo" ,
response_model : {
schema : ExtractionSchema ,
name : "Extraction"
} ,
max_retries : 3 ,
stream : true
} )
let extractedData = { }
for await ( const result of extractionStream ) {
extractedData = result
console . log ( "Partial extraction:" , result )
}
console . log ( "Final extraction:" , extractedData )
}
extractData ( )
在此示例中,我們使用ZOD定義了提取化學,以指定要提取的數據的結構。然後,我們創建一個具有流啟用流的講師客戶端,然後將架構傳遞到with wospy_model參數。
ExtracionsTream變量具有異步發電機,可在可用時產生部分提取結果。我們使用A for等待循環在流上迭代流,更新ExtractedData對象,並將每個部分結果記錄到控制台。
最後,一旦流耗盡,我們就會記錄完整的提取數據。
講師支持遵守OpenAI API規範的各種提供商。您可以通過配置適當的客戶端並指定所需的模型和模式來輕鬆切換提供商。
任何規模
import Instructor from "@instructor-ai/instructor"
import OpenAI from "openai"
import { z } from "zod"
const UserSchema = z . object ( {
age : z . number ( ) ,
name : z . string ( ) . refine ( name => name . includes ( " " ) , {
message : "Name must contain a space"
} )
} )
async function extractUser ( ) {
const client = new OpenAI ( {
baseURL : "https://api.endpoints.anyscale.com/v1" ,
apiKey : process . env . ANYSCALE_API_KEY
} )
const instructor = Instructor ( {
client : client ,
mode : "TOOLS"
} )
const user = await instructor . chat . completions . create ( {
messages : [ { role : "user" , content : "Jason Liu is 30 years old" } ] ,
model : "mistralai/Mixtral-8x7B-Instruct-v0.1" ,
response_model : {
schema : UserSchema ,
name : "User"
} ,
max_retries : 4
} )
return user
}
const anyscaleUser = await extractUser ( )
console . log ( "Anyscale user:" , anyscaleUser )
一起
import Instructor from "@instructor-ai/instructor"
import OpenAI from "openai"
import { z } from "zod"
const UserSchema = z . object ( {
age : z . number ( ) ,
name : z . string ( ) . refine ( name => name . includes ( " " ) , {
message : "Name must contain a space"
} )
} )
async function extractUser ( ) {
const client = new OpenAI ( {
baseURL : "https://api.together.xyz/v1" ,
apiKey : process . env . TOGETHER_API_KEY
} )
const instructor = Instructor ( {
client : client ,
mode : "TOOLS"
} )
const user = await instructor . chat . completions . create ( {
messages : [ { role : "user" , content : "Jason Liu is 30 years old" } ] ,
model : "mistralai/Mixtral-8x7B-Instruct-v0.1" ,
response_model : {
schema : UserSchema ,
name : "User"
} ,
max_retries : 4
} )
return user
}
const togetherUser = await extractUser ( )
console . log ( "Together user:" , togetherUser )
在這些示例中,我們從Anyscale中指定了一個特定的基本URL和API鍵,並一起指定。
提取器函數將模型,模式和提供商作為參數。它檢索相應的提供商配置,創建OpenAI客戶端,並使用指定模式初始化指導員實例。
然後,我們使用所需模型,響應架構和其他參數來調用ersenter.chat.completions.create,以提取用戶信息。
通過更改提供商,模型和模式參數時,可以在調用提取器時,可以輕鬆地在不同的提供商和配置之間切換。
講師支持與不遵守OpenAI SDK的提供商的集成,例如通過@DiMitrikennedy維護的llm-polyglot
庫,例如人類,Azure和Cohere。該庫提供了一個統一的界面,用於與不同提供商之間的各種語言模型進行交互。
import { createLLMClient } from "llm-polyglot"
import Instructor from "@instructor-ai/instructor"
import { z } from "zod"
const anthropicClient = createLLMClient ( {
provider : "anthropic" ,
apiKey : process . env . ANTHROPIC_API_KEY
} )
const UserSchema = z . object ( {
age : z . number ( ) ,
name : z . string ( )
} )
const instructor = Instructor < typeof anthropicClient > ( {
client : anthropicClient ,
mode : "TOOLS"
} )
async function extractUser ( ) {
const user = await instructor . chat . completions . create ( {
model : "claude-3-opus-20240229" ,
max_tokens : 1000 ,
messages : [
{
role : "user" ,
content : "My name is Dimitri Kennedy."
}
] ,
response_model : {
name : "extract_name" ,
schema : UserSchema
}
} )
return user
}
// Example usage
const extractedUser = await extractUser ( )
console . log ( "Extracted user:" , extractedUser )
在此示例中,我們使用LLM-PolyGlot庫中的createllmclient函數為人類提供商創建客戶端。我們將提供商名稱(“擬人化”)和該功能的相應API鍵傳遞給。
接下來,我們使用ZOD定義一個用戶chema來指定要提取的用戶數據的結構。
我們通過將人類客戶端和所需模式傳遞給教師函數來創建講師實例。請注意,我們使用講師明確指定客戶端類型。
提取器函數演示瞭如何使用講師實例從給定輸入中提取用戶信息。我們使用適當的模型(在這種情況下為“ Claude-3-Opus-20240229”),參數和包含包括我們用戶Chema的響應的wenders_model調用ersenter.chat.completions.create。
最後,我們記錄提取的用戶信息。
通過利用LLM-PolyGlot庫,講師可以與超越遵循OpenAI SDK的提供商無縫集成。這使您可以利用不同提供商提供的獨特功能和模型,同時仍能從教師的結構化提取和驗證功能中受益。
有關使用LLM-PolyGlot使用其他提供商的其他支持和信息,請參閱圖書館的文檔和示例。
如果您想查看更多查看我們的食譜。
安裝教練很輕鬆。
教練建於島上AI工具包的幾個強大包裝的頂部,由Dimitri Kennedy開發和維護。這些軟件包為結構化數據處理和流媒體提供了重要的功能。
Zod-tream是直接與LLM流直接接口的客戶端模塊。它利用模式流進行有效解析,並配備了處理OpenAI的原始響應的工具,按模式(功能,工具,JSON等)對其進行分類,並確保正確處理和流轉換。它是API集成提供結構化LLM響應流的理想選擇。
模式流是一個JSON流解析器,可逐步構建基於ZOD模式的響應模型。它專為實時數據處理和增量模型水合而設計。
LLM-PolyGlot是一個庫,它提供了一個統一的界面,用於與OpenAI,Anthropic,Azure和Cohere等不同提供商之間的各種語言模型進行交互。它簡化了與多個LLM提供商合作的過程,並啟用了與講師的無縫集成。
講師利用這些Island AI軟件包的力量為結構化數據提取和使用LLMS提供了無縫且有效的體驗。 Island AI的創建者Dimitri Kennedy與原始講師Python套餐的作者Jason Liu之間的合作導致了TypeScript版本的講師的開發,該版本介紹了LLM的部分JSON流的概念。
有關Island AI及其包裝的更多信息,請參閱Island AI存儲庫。
使用講師的問題從根本上說是為什麼使用ZOD的問題。
與OpenAI SDK合作- 講師遵循OpenAI的API。這意味著您可以在支持OpenAI API的多個提供商中使用相同的API來提示和提取。
可自定義- ZOD是高度可定制的。您可以定義自己的驗證器,自定義錯誤消息等。
生態系統ZOD是使用最廣泛使用的數據驗證庫。
戰鬥測試- ZOD每月下載超過240萬次,並得到大量貢獻者社區的支持。
如果您想提供幫助,請查看一些標記為good-first-issue
或help-wanted
問題。在這裡找到。它們可以是改進代碼,來賓博客文章或新烹飪書籍的任何內容。
請查看貢獻指南,以獲取有關如何設置事情,測試,更改和準則的詳細信息。
提示:其他語言支持
Check out ports to other languages below:
- [Python](https://www.github.com/jxnl/instructor)
- [Elixir](https://github.com/thmsmlr/instructor_ex/)
If you want to port Instructor to another language, please reach out to us on [Twitter](https://twitter.com/jxnlco) we'd love to help you get started!
該項目是根據MIT許可證的條款獲得許可的。