Skip to content

Commit

Permalink
fix: avoid unintended metadata parsing (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
gcalcedo authored Sep 20, 2024
1 parent 2ba7af0 commit dcc94c1
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@magicul/react-chat-stream",
"description": "A React hook that lets you easily integrate your custom ChatGPT-like chat in React.",
"version": "0.5.0",
"version": "0.5.1",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"homepage": "https://github.com/XD2Sketch/react-chat-stream#readme",
Expand Down
8 changes: 4 additions & 4 deletions src/hooks/useChatStream.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ChangeEvent, FormEvent, useState } from 'react';
import { decodeStreamToJson, getStream } from '../utils/streams';
import { UseChatStreamChatMessage, UseChatStreamInput } from '../types';
import { extractJsonFromEnd } from '../utils/json';

const BOT_ERROR_MESSAGE = 'Something went wrong fetching AI response.';

Expand Down Expand Up @@ -41,7 +42,6 @@ const useChatStream = (input: UseChatStreamInput) => {
const stream = await getStream(message, input.options, input.method);
const initialMessage = addMessage({ content: '', role: 'bot' });
let response = '';
let metadata = {};

for await (const chunk of decodeStreamToJson(stream)) {
if (!charactersPerSecond) {
Expand All @@ -51,10 +51,10 @@ const useChatStream = (input: UseChatStreamInput) => {
}

if (input.options.useMetadata) {
try {
metadata = JSON.parse(chunk.trim());
const metadata = extractJsonFromEnd(chunk);
if (metadata) {
return { ...initialMessage, content: response, metadata: metadata };
} catch {}
}
}

// Stream characters one by one based on the characters per second that is set.
Expand Down
20 changes: 20 additions & 0 deletions src/utils/json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const extractJsonFromEnd = (chunk: string) => {
const chunkTrimmed = chunk.trim();

const jsonObjectRegex = /({[^]*})\s*$/;
const match = chunkTrimmed.match(jsonObjectRegex);

if (!match) {
return null;
}

const jsonStr = match[1];
try {
const parsedData = JSON.parse(jsonStr);
if (typeof parsedData === 'object' && parsedData !== null && !Array.isArray(parsedData)) {
return parsedData;
}
} catch {}

return null;
};

0 comments on commit dcc94c1

Please sign in to comment.