-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
cypher.ts
218 lines (179 loc) Β· 5.5 KB
/
cypher.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import { ChainValues } from "@langchain/core/utils/types";
import { BasePromptTemplate } from "@langchain/core/prompts";
import { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
import { LLMChain } from "../llm_chain.js";
import { BaseChain, ChainInputs } from "../base.js";
import { CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT } from "./prompts.js";
import { logVersion020MigrationWarning } from "../../util/entrypoint_deprecation.js";
/* #__PURE__ */ logVersion020MigrationWarning({
oldEntrypointName: "chains/graph_qa/cypher",
newPackageName: "@langchain/community",
});
export const INTERMEDIATE_STEPS_KEY = "intermediateSteps";
export interface GraphCypherQAChainInput extends ChainInputs {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
graph: any;
cypherGenerationChain: LLMChain;
qaChain: LLMChain;
inputKey?: string;
outputKey?: string;
topK?: number;
returnIntermediateSteps?: boolean;
returnDirect?: boolean;
}
export interface FromLLMInput {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
graph: any;
llm?: BaseLanguageModelInterface;
cypherLLM?: BaseLanguageModelInterface;
qaLLM?: BaseLanguageModelInterface;
qaPrompt?: BasePromptTemplate;
cypherPrompt?: BasePromptTemplate;
returnIntermediateSteps?: boolean;
returnDirect?: boolean;
}
/**
* @example
* ```typescript
* const chain = new GraphCypherQAChain({
* llm: new ChatOpenAI({ temperature: 0 }),
* graph: new Neo4jGraph(),
* });
* const res = await chain.invoke("Who played in Pulp Fiction?");
* ```
*/
export class GraphCypherQAChain extends BaseChain {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private graph: any;
private cypherGenerationChain: LLMChain;
private qaChain: LLMChain;
private inputKey = "query";
private outputKey = "result";
private topK = 10;
private returnDirect = false;
private returnIntermediateSteps = false;
constructor(props: GraphCypherQAChainInput) {
super(props);
const {
graph,
cypherGenerationChain,
qaChain,
inputKey,
outputKey,
topK,
returnIntermediateSteps,
returnDirect,
} = props;
this.graph = graph;
this.cypherGenerationChain = cypherGenerationChain;
this.qaChain = qaChain;
if (inputKey) {
this.inputKey = inputKey;
}
if (outputKey) {
this.outputKey = outputKey;
}
if (topK) {
this.topK = topK;
}
if (returnIntermediateSteps) {
this.returnIntermediateSteps = returnIntermediateSteps;
}
if (returnDirect) {
this.returnDirect = returnDirect;
}
}
_chainType() {
return "graph_cypher_chain" as const;
}
get inputKeys(): string[] {
return [this.inputKey];
}
get outputKeys(): string[] {
return [this.outputKey];
}
static fromLLM(props: FromLLMInput): GraphCypherQAChain {
const {
graph,
qaPrompt = CYPHER_QA_PROMPT,
cypherPrompt = CYPHER_GENERATION_PROMPT,
llm,
cypherLLM,
qaLLM,
returnIntermediateSteps = false,
returnDirect = false,
} = props;
if (!cypherLLM && !llm) {
throw new Error(
"Either 'llm' or 'cypherLLM' parameters must be provided"
);
}
if (!qaLLM && !llm) {
throw new Error("Either 'llm' or 'qaLLM' parameters must be provided");
}
if (cypherLLM && qaLLM && llm) {
throw new Error(
"You can specify up to two of 'cypherLLM', 'qaLLM', and 'llm', but not all three simultaneously."
);
}
const qaChain = new LLMChain({
llm: (qaLLM || llm) as BaseLanguageModelInterface,
prompt: qaPrompt,
});
const cypherGenerationChain = new LLMChain({
llm: (cypherLLM || llm) as BaseLanguageModelInterface,
prompt: cypherPrompt,
});
return new GraphCypherQAChain({
cypherGenerationChain,
qaChain,
graph,
returnIntermediateSteps,
returnDirect,
});
}
private extractCypher(text: string): string {
const pattern = /```(.*?)```/s;
const matches = text.match(pattern);
return matches ? matches[1] : text;
}
async _call(
values: ChainValues,
runManager?: CallbackManagerForChainRun
): Promise<ChainValues> {
const callbacks = runManager?.getChild();
const question = values[this.inputKey];
const intermediateSteps = [];
const generatedCypher = await this.cypherGenerationChain.call(
{ question, schema: this.graph.getSchema() },
callbacks
);
const extractedCypher = this.extractCypher(generatedCypher.text);
await runManager?.handleText(`Generated Cypher:\n`);
await runManager?.handleText(`${extractedCypher} green\n`);
intermediateSteps.push({ query: extractedCypher });
let chainResult: ChainValues;
const context = await this.graph.query(extractedCypher, {
topK: this.topK,
});
if (this.returnDirect) {
chainResult = { [this.outputKey]: context };
} else {
await runManager?.handleText("Full Context:\n");
await runManager?.handleText(`${context} green\n`);
intermediateSteps.push({ context });
const result = await this.qaChain.call(
{ question, context: JSON.stringify(context) },
callbacks
);
chainResult = {
[this.outputKey]: result[this.qaChain.outputKey],
};
}
if (this.returnIntermediateSteps) {
chainResult[INTERMEDIATE_STEPS_KEY] = intermediateSteps;
}
return chainResult;
}
}