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

fix: chat functions getting into stuck state, gpt json.parse #1199

Merged
merged 1 commit into from
Dec 25, 2023
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
135 changes: 87 additions & 48 deletions packages/trpc/src/services/chat/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from "../../types/assistantMessageSummary";
import dedent from "ts-dedent";
import { Capabilities, userHasCapability } from "../capabilities";
import * as Sentry from "@sentry/node";

export class Assistant {
private openAiHelper: OpenAIHelper;
Expand Down Expand Up @@ -77,6 +78,38 @@ export class Assistant {
assistantMessage.json as unknown as ChatCompletionMessageParam,
);

let expectedToolCalls = 0;
let toolCallingError = false;
for (const message of chatGPTContext) {
if (expectedToolCalls > 0 && message.role !== "tool") {
toolCallingError = true;
continue;
}

if (expectedToolCalls > 0 && message.role === "tool") {
expectedToolCalls--;
continue;
}

if (message.role === "assistant" && message.tool_calls) {
expectedToolCalls = message.tool_calls.length;
}
}

if (toolCallingError) {
console.error("TOOL CALLING ERROR", userId);
Sentry.captureMessage("TOOL CALLING ERROR", {
extra: {
userId,
context: chatGPTContext,
},
});
// If we have a tool calling error (a tool call not followed by tool responses)
// we must remove all context otherwise gpt will fail.
// TODO: better solution for this
return chatGPTContext.splice(0);
}

// Insert the system prompt at the beginning of the messages sent to ChatGPT (oldest)
chatGPTContext.unshift({
role: "system",
Expand Down Expand Up @@ -134,61 +167,67 @@ export class Assistant {
initBuildRecipe(assistantUser.id, recipes),
]);

await prisma.assistantMessage.create({
data: {
userId,
role: userMessage.role,
content: userMessage.content,
json: userMessage,
},
});
await prisma.$transaction(async (tx) => {
await tx.assistantMessage.create({
data: {
userId,
role: userMessage.role,
content: userMessage.content,
json: userMessage,
createdAt: new Date(), // Since ordering is important and we're in a transaction, we must create date here
},
});

const toolCallsById: Record<string, ChatCompletionMessageToolCall> = {};
for (const message of response) {
if (message.role === "assistant" && message.tool_calls) {
message.tool_calls.forEach((toolCall) => {
toolCallsById[toolCall.id] = toolCall;
});
const toolCallsById: Record<string, ChatCompletionMessageToolCall> = {};
for (const message of response) {
if (message.role === "assistant" && message.tool_calls) {
message.tool_calls.forEach((toolCall) => {
toolCallsById[toolCall.id] = toolCall;
});
}
}
}

for (const message of response) {
let recipeId: string | undefined = undefined;
if (
message.role === "tool" &&
toolCallsById[message.tool_call_id]?.function.name === "displayRecipe"
) {
const recipeToCreate = recipes.shift();
if (!recipeToCreate) {
throw new Error(
"ChatGPT claims it created a recipe but no recipe was created by function call",
);
for (const message of response) {
let recipeId: string | undefined = undefined;
if (
message.role === "tool" &&
toolCallsById[message.tool_call_id]?.function.name === "displayRecipe"
) {
const recipeToCreate = recipes.shift();
if (!recipeToCreate) {
throw new Error(
"ChatGPT claims it created a recipe but no recipe was created by function call",
);
}

const recipe = await tx.recipe.create({
data: recipeToCreate,
});

recipeId = recipe.id;
}

const recipe = await prisma.recipe.create({
data: recipeToCreate,
const content = Array.isArray(message.content)
? message.content
.map((part) =>
part.type === "text" ? part.text : part.image_url,
)
.join("\n")
: message.content;

await tx.assistantMessage.create({
data: {
userId,
role: message.role,
recipeId,
content,
name: "name" in message ? message.name : null,
json: message as object, // Prisma does not like OpenAI's typings
createdAt: new Date(), // Since ordering is important and we're in a transaction, we must create date here
},
});

recipeId = recipe.id;
}

const content = Array.isArray(message.content)
? message.content
.map((part) => (part.type === "text" ? part.text : part.image_url))
.join("\n")
: message.content;

await prisma.assistantMessage.create({
data: {
userId,
role: message.role,
recipeId,
content,
name: "name" in message ? message.name : null,
json: message as object, // Prisma does not like OpenAI's typings
},
});
}
});
}

async getChatHistory(userId: string): Promise<AssistantMessageSummary[]> {
Expand Down
100 changes: 53 additions & 47 deletions packages/trpc/src/services/chat/chatFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,33 @@ export const initBuildRecipe = (
function: (args) => {
console.log("buildRecipe called with", args);

const recipe: Prisma.RecipeUncheckedCreateInput = {
userId,
fromUserId: null,
title: typeof args.title === "string" ? args.title : "Unnamed",
description: "",
folder: "main",
source: "RecipeSage Cooking Assistant",
url: "",
rating: null,
yield: typeof args.yield === "string" ? args.yield : "",
activeTime: typeof args.activeTime === "string" ? args.activeTime : "",
totalTime: typeof args.totalTime === "string" ? args.totalTime : "",
ingredients: Array.isArray(args.ingredients)
? JSON.parse(`"${args.ingredients.join("\n").replaceAll('"', '\\"')}`)
: "",
instructions: Array.isArray(args.instructions)
? JSON.parse(
`"${args.instructions.join("\n").replaceAll('"', '\\"')}`,
)
: "",
notes: "",
};
try {
const recipe: Prisma.RecipeUncheckedCreateInput = {
userId,
fromUserId: null,
title: typeof args.title === "string" ? args.title : "Unnamed",
description: "",
folder: "main",
source: "RecipeSage Cooking Assistant",
url: "",
rating: null,
yield: typeof args.yield === "string" ? args.yield : "",
activeTime:
typeof args.activeTime === "string" ? args.activeTime : "",
totalTime: typeof args.totalTime === "string" ? args.totalTime : "",
ingredients: Array.isArray(args.ingredients)
? JSON.parse(JSON.stringify(args.ingredients.join("\n")))
: "",
instructions: Array.isArray(args.instructions)
? JSON.parse(JSON.stringify(args.instructions.join("\n")))
: "",
notes: "",
};

result.push(recipe);
result.push(recipe);
} catch (e) {
console.error("failed to construct a recipe", e);
}

// Return the same thing GPT sent us so that it replies to user with what it built
// If we don't do this, ChatGPT will create a new (different) recipe and reply with that
Expand Down Expand Up @@ -115,31 +118,34 @@ export const initOCRFormatRecipe = (
function: (args) => {
console.log("buildRecipe called with", args);

const recipe: Prisma.RecipeUncheckedCreateInput = {
userId,
fromUserId: null,
title: typeof args.title === "string" ? args.title : "Unnamed",
description:
typeof args.description === "string" ? args.description : "",
folder: "main",
source: "",
url: "",
rating: null,
yield: typeof args.yield === "string" ? args.yield : "",
activeTime: typeof args.activeTime === "string" ? args.activeTime : "",
totalTime: typeof args.totalTime === "string" ? args.totalTime : "",
ingredients: Array.isArray(args.ingredients)
? JSON.parse(`"${args.ingredients.join("\n").replaceAll('"', '\\"')}`)
: "",
instructions: Array.isArray(args.instructions)
? JSON.parse(
`"${args.instructions.join("\n").replaceAll('"', '\\"')}`,
)
: "",
notes: typeof args.notes === "string" ? args.notes : "",
};
try {
const recipe: Prisma.RecipeUncheckedCreateInput = {
userId,
fromUserId: null,
title: typeof args.title === "string" ? args.title : "Unnamed",
description:
typeof args.description === "string" ? args.description : "",
folder: "main",
source: "",
url: "",
rating: null,
yield: typeof args.yield === "string" ? args.yield : "",
activeTime:
typeof args.activeTime === "string" ? args.activeTime : "",
totalTime: typeof args.totalTime === "string" ? args.totalTime : "",
ingredients: Array.isArray(args.ingredients)
? JSON.parse(JSON.stringify(args.ingredients.join("\n")))
: "",
instructions: Array.isArray(args.instructions)
? JSON.parse(JSON.stringify(args.instructions.join("\n")))
: "",
notes: typeof args.notes === "string" ? args.notes : "",
};

result.push(recipe);
result.push(recipe);
} catch (e) {
console.error("failed to construct a recipe", e);
}

// Return the same thing GPT sent us so that it replies to user with what it built
// If we don't do this, ChatGPT will create a new (different) recipe and reply with that
Expand Down