Skip to content
Open
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.vscode
.vscode
.env
6 changes: 4 additions & 2 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"tasks": {},
"tasks": {
"test": "YOUR_API_KEY=YOUR_API_KEY_HERE deno test --allow-env --allow-net"
},
"lock": false
}
}
4 changes: 2 additions & 2 deletions src/openai.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { basename } from "https://deno.land/std@0.189.0/path/mod.ts";
import { decodeStream, throwError } from "./util.ts";
import { decodeStream, throwErrorIfNeeded } from "./util.ts";
import type {
ChatCompletion,
ChatCompletionOptions,
Expand Down Expand Up @@ -70,7 +70,7 @@ export class OpenAI {
);
const data = await response.json();

throwError(data);
throwErrorIfNeeded(data);

return data;
}
Expand Down
19 changes: 19 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,3 +773,22 @@ export interface Moderation {
flagged: boolean;
}[];
}

export interface ErrorResponse {
error: Error;
}

export interface ModelError {
type: string;
message: string;
param: string | null;
code: string | null;
}

export class RequiredError extends Error {
public name = "RequiredError";

constructor(public readonly field: string, message?: string) {
super(message);
}
}
68 changes: 37 additions & 31 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,46 @@
import { TextDelimiterStream } from "https://deno.land/std@0.189.0/streams/mod.ts";
import { TextDelimiterStream } from "https://deno.land/std@0.189.0/streams/text_delimiter_stream.ts";
import { ModelError, RequiredError } from "./types.ts";

export function throwError(
data: { error?: { type: string; message: string; code: string } },
) {
if (data.error) {
let errorMessage = `${data.error.type}`;
if (data.error.message) {
errorMessage += ": " + data.error.message;
}
if (data.error.code) {
errorMessage += ` (${data.error.code})`;
}
// console.log(data.error);
throw new Error(errorMessage);
export function throwErrorIfNeeded(response: unknown) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you split this off into another PR? Ref: #18

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we restore the function code and create a new PR with this code and the issue reference?

I don't wanna create a branch from this branch. Should i wait until this be merged?

Sorry, I'm not an expert on github. I don't know the best practices for the prs T-T

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we restore the function code and create a new PR with this code and the issue reference?

Yes, this would be great!

// deno-lint-ignore ban-types
if ("error" in (response as object)) {
const {
error: { type, message },
} = response as { error: ModelError };

throw new RequiredError(type, message);
}
}

// deno-lint-ignore no-explicit-any
export async function decodeStream(
res: Response,
callback: (data: any) => void,
export async function decodeStream<T>(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice change, a fan of this

{ body: stream }: Response,
callback: (data: T) => void
) {
const chunks = res.body!
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First of all, thank you for the PR, we really appreciate it!

I think my big issue with this PR is the unnecessary complexity it introduces here. If I understand correctly, you have two issues with the current implementation:

  1. There's an error that we're not catching
  2. Wanting to be able to cancel the stream

Both of these can be solved in like ~10 lines of well written code with the current implementation as a base. Reimplementing a stream decoder seems not very useful to me (though I'd love to be proven wrong)!

If you would be willing to rework this PR, please let me know! If not, I will go through and fix these myself. Have a nice day!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanna rework this. About the tests. Where should I put them?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't really have tests per se since it's pretty hard to enable testing without using the API (we just use examples right now).

if (stream === null || stream.locked) {
throw new Error(`The stream is ${stream === null ? "null" : "locked"}.`);
}

const chunks = stream
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextDelimiterStream("\n\n"));

for await (const chunk of chunks) {
let data;
try {
data = JSON.parse(chunk);
} catch {
// no-op (just checking if error message)
}
if (data) throwError(data);
.pipeThrough(new TextDelimiterStream("\n\n"))
.getReader();

try {
for (;;) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for (;;) { is really dubious to me. Why not while(true) {?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah change that

const { done, value: chunk } = await chunks.read();

if (done || chunk === "data: [DONE]") {
break;
}

if (chunk === "data: [DONE]") break;
callback(JSON.parse(chunk.slice(6)));
const argument = JSON.parse(
chunk.startsWith("data: ") ? chunk.slice(6) : chunk
);

throwErrorIfNeeded(argument);
callback(argument);
}
} finally {
chunks.releaseLock();
}
}
32 changes: 32 additions & 0 deletions tests/createChatCompletionStream.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { assertEquals } from "https://deno.land/std@0.192.0/testing/asserts.ts";
import { OpenAI } from "../mod.ts";

const permissions = {
net: true,
env: true,
} satisfies Deno.PermissionOptions;

const openai = new OpenAI(Deno.env.get("YOUR_API_KEY")!);

Deno.test(
"createChatCompletionStream",
{ permissions },
async () =>
await openai.createChatCompletionStream(
{
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Who won the world series in 2020?" },
{
role: "assistant",
content: "The Los Angeles Dodgers won the World Series in 2020.",
},
{ role: "user", content: "Where was it played?" },
],
},
(chunk) => {
assertEquals(chunk.object, "chat.completion.chunk");
}
)
);