Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Shrink interface of KurtEvent and rename as KurtStream #7

Merged
merged 1 commit into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ for await (const event of stream) {
// data: undefined,
// }

await stream.finalText // "Hello! How can I assist you today?"
const { text } = await stream.result
console.log(text)
// "Hello! How can I assist you today?"
```

## Generate Structured Data Output
Expand All @@ -91,5 +93,7 @@ for await (const event of stream) {
// { chunk: '"}' }
// { finished: true, text: '{"say":"hello"}', data: { say: "hello" } }

await stream.finalData // { say: "hello" }
const { data } = await stream.result
console.log(data)
// { say: "hello" }
```
94 changes: 39 additions & 55 deletions spec/KurtResult.spec.ts → spec/KurtStream.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, test } from "@jest/globals"
import { z } from "zod"
import { KurtResult, type KurtResultEvent } from "../src/KurtResult"
import { KurtStream, type KurtStreamEvent } from "../src/KurtStream"

function kurtSayHelloEvents() {
return [
Expand All @@ -17,19 +17,19 @@ function kurtSayHelloEvents() {
]
}

function kurtSayHelloFinalEvent() {
function kurtSayHelloResult() {
const events = kurtSayHelloEvents()
// biome-ignore lint/style/noNonNullAssertion: Pending explanation
return events[events.length - 1]!
}

function kurtResultSayHello(
function kurtStreamSayHello(
opts: {
errorBeforeFinish?: boolean
} = {}
) {
const schema = z.object({ say: z.string() })
return new KurtResult<(typeof schema)["shape"]>(
return new KurtStream<(typeof schema)["shape"]>(
(async function* gen() {
const events = kurtSayHelloEvents()

Expand All @@ -41,7 +41,7 @@ function kurtResultSayHello(
if (opts.errorBeforeFinish && event.finished) throw new Error("Whoops!")

// Send the event.
yield event as KurtResultEvent<(typeof schema)["shape"]>
yield event as KurtStreamEvent<(typeof schema)["shape"]>
}
})()
)
Expand All @@ -59,105 +59,93 @@ async function expectThrow(message: string, fn: () => Promise<unknown>) {
}

describe("KurtResult", () => {
test("with an await for final text", async () => {
const result = kurtResultSayHello()

expect(await result.finalText).toEqual(kurtSayHelloFinalEvent().text)
})

test("with an await for final data", async () => {
const result = kurtResultSayHello()

expect(await result.finalData).toEqual(kurtSayHelloFinalEvent().data)
})

test("with an await for final event", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

expect(await result.finalEvent).toEqual(kurtSayHelloFinalEvent())
expect(await stream.result).toEqual(kurtSayHelloResult())
})

test("with an await for final event catching an error", async () => {
const result = kurtResultSayHello({ errorBeforeFinish: true })
const stream = kurtStreamSayHello({ errorBeforeFinish: true })

expectThrow("Whoops!", async () => await result.finalEvent)
expectThrow("Whoops!", async () => await stream.result)
})

test("with one event listener", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

const events: unknown[] = []
for await (const event of result) events.push(event)
for await (const event of stream) events.push(event)

expect(events).toEqual(kurtSayHelloEvents())
})

test("with one event listener, catching an error", async () => {
const result = kurtResultSayHello({ errorBeforeFinish: true })
const stream = kurtStreamSayHello({ errorBeforeFinish: true })

const events: unknown[] = []
await expectThrow("Whoops!", async () => {
for await (const event of result) events.push(event)
for await (const event of stream) events.push(event)
})

expect(events).toEqual(kurtSayHelloEvents().slice(0, -1))
})

test("with final awaits before listener", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

expect(await result.finalEvent).toEqual(kurtSayHelloFinalEvent())
expect(await result.finalText).toEqual(kurtSayHelloFinalEvent().text)
expect(await result.finalData).toEqual(kurtSayHelloFinalEvent().data)
expect(await stream.result).toEqual(kurtSayHelloResult())
expect(await stream.result).toEqual(kurtSayHelloResult())
expect(await stream.result).toEqual(kurtSayHelloResult())

const events: unknown[] = []
for await (const event of result) events.push(event)
for await (const event of stream) events.push(event)

expect(events).toEqual(kurtSayHelloEvents())
})

test("with final awaits after listener", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

const events: unknown[] = []
for await (const event of result) events.push(event)
for await (const event of stream) events.push(event)

expect(await result.finalEvent).toEqual(kurtSayHelloFinalEvent())
expect(await result.finalText).toEqual(kurtSayHelloFinalEvent().text)
expect(await result.finalData).toEqual(kurtSayHelloFinalEvent().data)
expect(await stream.result).toEqual(kurtSayHelloResult())
expect(await stream.result).toEqual(kurtSayHelloResult())
expect(await stream.result).toEqual(kurtSayHelloResult())

expect(events).toEqual(kurtSayHelloEvents())
})

test("with three listeners, each after the last one finished", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

const events1: unknown[] = []
const events2: unknown[] = []
const events3: unknown[] = []
for await (const event of result) events1.push(event)
for await (const event of result) events2.push(event)
for await (const event of result) events3.push(event)
for await (const event of stream) events1.push(event)
for await (const event of stream) events2.push(event)
for await (const event of stream) events3.push(event)

expect(events1).toEqual(kurtSayHelloEvents())
expect(events2).toEqual(kurtSayHelloEvents())
expect(events2).toEqual(kurtSayHelloEvents())
})

test("with three listeners, each catching an error", async () => {
const result = kurtResultSayHello({ errorBeforeFinish: true })
const stream = kurtStreamSayHello({ errorBeforeFinish: true })

const events1: unknown[] = []
const events2: unknown[] = []
const events3: unknown[] = []
await expectThrow("Whoops!", async () => {
for await (const event of result) events1.push(event)
for await (const event of stream) events1.push(event)
})
await expectThrow("Whoops!", async () => {
for await (const event of result) events2.push(event)
for await (const event of stream) events2.push(event)
})
await expectThrow("Whoops!", async () => {
for await (const event of result) events3.push(event)
for await (const event of stream) events3.push(event)
})

expect(events1).toEqual(kurtSayHelloEvents().slice(0, -1))
Expand All @@ -166,14 +154,14 @@ describe("KurtResult", () => {
})

test("with many listeners, interleaved with one another", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

const events: unknown[][] = []
const listeners: Promise<unknown>[] = []
async function listen(spawnMoreListeners = false) {
events.push([])
const listenerIndex = events.length - 1
for await (const event of result) {
for await (const event of stream) {
events[listenerIndex]?.push(event)
if (spawnMoreListeners) listeners.push(listen())
}
Expand All @@ -193,23 +181,21 @@ describe("KurtResult", () => {
})

test("with many listeners, interleaved with final event awaits", async () => {
const result = kurtResultSayHello()
const stream = kurtStreamSayHello()

const events: unknown[][] = []
const listeners: Promise<unknown>[] = []
const awaits: Promise<unknown>[] = []
async function listen(spawnMoreListeners = false) {
events.push([])
const listenerIndex = events.length - 1
for await (const event of result) {
for await (const event of stream) {
events[listenerIndex]?.push(event)
if (spawnMoreListeners) {
listeners.push(listen())
awaits.push(
(async () =>
expect(await result.finalEvent).toEqual(
kurtSayHelloFinalEvent()
))()
expect(await stream.result).toEqual(kurtSayHelloResult()))()
)
}
}
Expand All @@ -230,23 +216,21 @@ describe("KurtResult", () => {
})

test("with many listeners/awaits, interleaved, with error", async () => {
const result = kurtResultSayHello({ errorBeforeFinish: true })
const stream = kurtStreamSayHello({ errorBeforeFinish: true })

const events: unknown[][] = []
const listeners: Promise<unknown>[] = []
const errors: Promise<unknown>[] = []
async function listen(spawnMoreListeners = false) {
events.push([])
const listenerIndex = events.length - 1
for await (const event of result) {
for await (const event of stream) {
events[listenerIndex]?.push(event)
if (spawnMoreListeners) {
const listener = listen()
listeners.push(listener)
errors.push(expectThrow("Whoops!", async () => await listener))
errors.push(
expectThrow("Whoops!", async () => await result.finalEvent)
)
errors.push(expectThrow("Whoops!", async () => await stream.result))
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Kurt.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { KurtResult } from "./KurtResult"
import type { KurtStream } from "./KurtStream"
import type { KurtSchema, KurtSchemaInner } from "./KurtSchema"

export interface Kurt {
generateNaturalLanguage(
options: KurtGenerateNaturalLanguageOptions
): KurtResult
): KurtStream

generateStructuredData<T extends KurtSchemaInner>(
options: KurtGenerateStructuredDataOptions<T>
): KurtResult<T>
): KurtStream<T>
}

export interface KurtMessage {
Expand Down
18 changes: 9 additions & 9 deletions src/KurtOpenAI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
KurtGenerateStructuredDataOptions,
KurtMessage,
} from "./Kurt"
import { KurtResult, type KurtResultEvent } from "./KurtResult"
import { KurtStream, type KurtStreamEvent } from "./KurtStream"
import type {
KurtSchemaInner,
KurtSchemaInnerMaybe,
Expand Down Expand Up @@ -37,7 +37,7 @@ export class KurtOpenAI implements Kurt {

generateNaturalLanguage(
options: KurtGenerateNaturalLanguageOptions
): KurtResult {
): KurtStream {
return this.handleStream(
undefined,
this.options.openAI.chat.completions.create({
Expand All @@ -50,7 +50,7 @@ export class KurtOpenAI implements Kurt {

generateStructuredData<T extends KurtSchemaInner>(
options: KurtGenerateStructuredDataOptions<T>
): KurtResult<T> {
): KurtStream<T> {
const schema = options.schema

return this.handleStream(
Expand Down Expand Up @@ -80,7 +80,7 @@ export class KurtOpenAI implements Kurt {
private handleStream<T extends KurtSchemaInnerMaybe>(
schema: KurtSchemaMaybe<T>,
response: OpenAIResponse
): KurtResult<T> {
): KurtStream<T> {
async function* generator<T extends KurtSchemaInnerMaybe>() {
const stream = await response
const chunks: string[] = []
Expand All @@ -91,13 +91,13 @@ export class KurtOpenAI implements Kurt {

const textChunk = choice.delta.content
if (textChunk) {
yield { chunk: textChunk } as KurtResultEvent<T>
yield { chunk: textChunk } as KurtStreamEvent<T>
chunks.push(textChunk)
}

const dataChunk = choice.delta.tool_calls?.at(0)?.function?.arguments
if (dataChunk) {
yield { chunk: dataChunk } as KurtResultEvent<T>
yield { chunk: dataChunk } as KurtStreamEvent<T>
chunks.push(dataChunk)
}

Expand All @@ -111,19 +111,19 @@ export class KurtOpenAI implements Kurt {
finished: true,
text,
data,
} as KurtResultEvent<T>
} as KurtStreamEvent<T>
} else {
yield {
finished: true,
text,
data: undefined,
} as KurtResultEvent<T>
} as KurtStreamEvent<T>
}
}
}
}

return new KurtResult<T>(generator())
return new KurtStream<T>(generator())
}

private toOpenAIMessages = ({
Expand Down
Loading
Loading