Skip to content

Commit

Permalink
Merge pull request #160 from yanyao2333/fix-code-block-format
Browse files Browse the repository at this point in the history
将AI返回内容中的markdown代码块转换为普通json
  • Loading branch information
idootop authored Jul 24, 2024
2 parents 27bde0c + bba886e commit 5d455e2
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 24 deletions.
4 changes: 4 additions & 0 deletions src/services/bot/memory/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Memory, Message, Room, User } from "@prisma/client";
import { firstOf, lastOf } from "../../../utils/base";
import { Logger } from "../../../utils/log";
import { MemoryCRUD } from "../../db/memory";
import { LongTermMemoryCRUD } from "../../db/memory-long-term";
import { ShortTermMemoryCRUD } from "../../db/memory-short-term";
Expand All @@ -15,6 +16,7 @@ export class MemoryManager {
* owner 为空时,即房间自己的公共记忆
*/
private owner?: User;
private _logger = Logger.create({ tag: "Memory" });

constructor(room: Room, owner?: User) {
this.room = room;
Expand Down Expand Up @@ -118,6 +120,7 @@ export class MemoryManager {
lastMemory,
});
if (!newMemory) {
this._logger.error("💀 生成短期记忆失败");
return false;
}
const res = await ShortTermMemoryCRUD.addOrUpdate({
Expand Down Expand Up @@ -151,6 +154,7 @@ export class MemoryManager {
lastMemory,
});
if (!newMemory) {
this._logger.error("💀 生成长期记忆失败");
return false;
}
const res = await LongTermMemoryCRUD.addOrUpdate({
Expand Down
5 changes: 3 additions & 2 deletions src/services/bot/memory/long-term.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { LongTermMemory, ShortTermMemory } from "@prisma/client";
import { jsonDecode, lastOf } from "../../../utils/base";
import { lastOf } from "../../../utils/base";
import { buildPrompt } from "../../../utils/string";
import { cleanJsonAndDecode } from "../../../utils/parse";
import { openai } from "../../openai";
import { MessageContext } from "../conversation";

Expand Down Expand Up @@ -67,6 +68,6 @@ export class LongTermMemoryAgent {
shortTermMemory: lastOf(newMemories)!.text,
}),
});
return jsonDecode(res?.content)?.longTermMemories?.toString();
return cleanJsonAndDecode(res?.content)?.longTermMemories?.toString();
}
}
4 changes: 2 additions & 2 deletions src/services/bot/memory/short-term.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Memory, Message, ShortTermMemory, User } from "@prisma/client";
import { jsonDecode } from "../../../utils/base";
import { cleanJsonAndDecode } from "../../../utils/parse";
import { buildPrompt, formatMsg } from "../../../utils/string";
import { openai } from "../../openai";
import { MessageContext } from "../conversation";
Expand Down Expand Up @@ -78,6 +78,6 @@ export class ShortTermMemoryAgent {
.join("\n"),
}),
});
return jsonDecode(res?.content)?.shortTermMemories?.toString();
return cleanJsonAndDecode(res?.content)?.shortTermMemories?.toString();
}
}
3 changes: 2 additions & 1 deletion src/services/speaker/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
getMiIOT,
getMiNA,
} from "mi-service-lite";
import { clamp, jsonEncode, sleep } from "../../utils/base";
import { clamp, sleep } from "../../utils/base";
import { jsonEncode } from "../../utils/parse";
import { Logger } from "../../utils/log";
import { StreamResponse } from "./stream";
import { kAreYouOK } from "../../utils/string";
Expand Down
19 changes: 1 addition & 18 deletions src/utils/base.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isEmpty } from "./is";
import { jsonEncode } from "./parse"

export function timestamp() {
return new Date().getTime();
Expand Down Expand Up @@ -87,24 +88,6 @@ export function toSet<T = any>(datas: T[], byKey?: (e: T) => any) {
return Array.from(new Set(datas));
}

export function jsonEncode(obj: any, options?: { prettier?: boolean }) {
const { prettier } = options ?? {};
try {
return prettier ? JSON.stringify(obj, undefined, 4) : JSON.stringify(obj);
} catch (error) {
return undefined;
}
}

export function jsonDecode(json: string | null | undefined) {
if (json == undefined) return undefined;
try {
return JSON.parse(json!);
} catch (error) {
return undefined;
}
}

export function withDefault<T = any>(e: any, defaultValue: T): T {
return isEmpty(e) ? defaultValue : e;
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/io.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from "fs-extra";
import path from "path";

import { jsonDecode, jsonEncode } from "./base";
import { jsonDecode, jsonEncode } from "./parse";

export const kRoot = process.cwd();

Expand Down
32 changes: 32 additions & 0 deletions src/utils/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* 清理掉json字符串前后的其他字符,并解码
*/
export function cleanJsonAndDecode(input: string | undefined | null) {
if (input == undefined) return undefined;
const pattern = /(\{[\s\S]*?"\s*:\s*[\s\S]*?})/;
const match = input.match(pattern);

if (!match) {
return undefined;
}

return jsonDecode(match[0]);
}

export function jsonEncode(obj: any, options?: { prettier?: boolean }) {
const { prettier } = options ?? {};
try {
return prettier ? JSON.stringify(obj, undefined, 4) : JSON.stringify(obj);
} catch (error) {
return undefined;
}
}

export function jsonDecode(json: string | null | undefined) {
if (json == undefined) return undefined;
try {
return JSON.parse(json!);
} catch (error) {
return undefined;
}
}

0 comments on commit 5d455e2

Please sign in to comment.