This repository was archived by the owner on Jan 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOpenAiDataCombiner.ts
89 lines (83 loc) · 2.75 KB
/
OpenAiDataCombiner.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { IOpenAiFunction } from "./module";
/**
* Data combiner for OpenAI function call.
*
* @author Samchon
*/
export namespace OpenAiDataCombiner {
/**
* Properties of {@link parameters} function.
*/
export interface IProps {
/**
* Target function to call.
*/
function: IOpenAiFunction;
/**
* Arguments composed by LLM (Large Language Model).
*/
llm: any[];
/**
* Arguments composed by human.
*/
human: any[];
}
/**
* Combine LLM and human arguments into one.
*
* When you composes {@link IOpenAiDocument} with
* {@link IOpenAiDocument.IOptions.separate} option, then the arguments of the
* target function would be separated into two parts; LLM (Large Language Model)
* and human.
*
* In that case, you can combine both LLM and human composed arguments into one
* by utilizing this {@link OpenAiDataCombiner.parameters} function, referencing
* the target function metadata {@link IOpenAiFunction.separated}.
*
* @param props Properties to combine LLM and human arguments with metadata.
* @returns Combined arguments
*/
export const parameters = (props: IProps): any[] => {
const separated: IOpenAiFunction.ISeparated | undefined =
props.function.separated;
if (separated === undefined)
throw new Error(
"Error on OpenAiDataComposer.parameters(): the function parameters are not separated.",
);
return new Array(props.function.parameters.length).fill(0).map((_, i) => {
const llm: number = separated.llm.findIndex((p) => p.index === i);
const human: number = separated.human.findIndex((p) => p.index === i);
if (llm === -1 && human === -1)
throw new Error(
"Error on OpenAiDataComposer.parameters(): failed to gather separated arguments, because both LLM and human sides are all empty.",
);
return value(props.llm[llm], props.human[human]);
});
};
/**
* Combine two values into one.
*
* If both values are objects, then combines them in the properties level.
*
* Otherwise, returns the latter value if it's not null, otherwise the former value
*
* - `return (y ?? x)`
*
* @param x Value X
* @param y Value Y
* @returns Combined value
*/
export const value = (x: any, y: any): any =>
typeof x === "object" && typeof y === "object" && x !== null && y !== null
? combineObject(x, y)
: Array.isArray(x) && Array.isArray(y)
? new Array(Math.max(x.length, y.length))
.fill(0)
.map((_, i) => value(x[i], y[i]))
: y ?? x;
const combineObject = (x: any, y: any): any => {
const output: any = { ...x };
for (const [k, v] of Object.entries(y)) output[k] = value(x[k], v);
return output;
};
}