Skip to content

Commit

Permalink
use a factory to setup the instructor instance and proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
roodboi committed Jan 2, 2024
1 parent f31e73e commit f9fa74b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 15 deletions.
2 changes: 1 addition & 1 deletion examples/extract_user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const oai = new OpenAI({
organization: process.env.OPENAI_ORG_ID ?? undefined
})

const client = new Instructor({
const client = Instructor({
client: oai,
mode: "FUNCTIONS"
})
Expand Down
48 changes: 35 additions & 13 deletions src/instructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ type PatchedChatCompletionCreateParams = ChatCompletionCreateParamsNonStreaming
max_retries?: number
}

export default class Instructor {
private client: OpenAI
private mode: MODE
class Instructor {
readonly client: OpenAI
readonly mode: MODE

/**
* Creates an instance of the `Instructor` class.
Expand All @@ -56,10 +56,7 @@ export default class Instructor {
* @param {PatchedChatCompletionCreateParams} params - The parameters for chat completion.
* @returns {Promise<any>} The response from the chat completion.
*/
private chatCompletion = async ({
max_retries = 3,
...params
}: PatchedChatCompletionCreateParams) => {
chatCompletion = async ({ max_retries = 3, ...params }: PatchedChatCompletionCreateParams) => {
let attempts = 0
let validationIssues = []
let lastMessage = null
Expand Down Expand Up @@ -162,13 +159,38 @@ export default class Instructor {

return parser(response)
}
}

/**
* Public chat interface.
*/
public chat = {
completions: {
create: this.chatCompletion
type OAIClientExtended = OpenAI &
Instructor & {
chat: {
completions: {
create: (args: PatchedChatCompletionCreateParams) => Promise<unknown>
}
}
}

export default function (args: { client: OpenAI; mode: MODE }): OAIClientExtended {
const instructor = new Instructor(args)

const instructorWithProxy = new Proxy(instructor, {
get: (target, prop, receiver) => {
if (prop === "chat") {
return {
completions: {
create: target.chatCompletion.bind(target)
},
...target.client.chat
}
}

if (prop in target) {
return Reflect.get(target, prop, receiver)
}

return Reflect.get(target.client, prop, receiver)
}
})

return instructorWithProxy as OAIClientExtended
}
2 changes: 1 addition & 1 deletion tests/functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async function extractUser() {
organization: process.env.OPENAI_ORG_ID ?? undefined
})

const client = new Instructor({
const client = Instructor({
client: oai,
mode: "FUNCTIONS"
})
Expand Down

0 comments on commit f9fa74b

Please sign in to comment.