/
langchain_routes.ts
177 lines (168 loc) · 5.58 KB
/
langchain_routes.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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import { schema, TypeOf } from '@osd/config-schema';
import { Run } from 'langchain/callbacks';
import { LLMChain } from 'langchain/chains';
import { PromptTemplate } from 'langchain/prompts';
import { v4 as uuid } from 'uuid';
import {
HttpResponsePayload,
ILegacyScopedClusterClient,
IOpenSearchDashboardsResponse,
IRouter,
ResponseError,
} from '../../../../src/core/server';
import { ASSISTANT_API, LLM_INDEX } from '../../common/constants/llm';
import { OpenSearchTracer } from '../olly/callbacks/opensearch_tracer';
import { requestSummarizationChain } from '../olly/chains/summarization';
import { LLMModelFactory } from '../olly/models/llm_model_factory';
import { MLCommonsChatModel } from '../olly/models/mlcommons_chat_model';
import { OllyChatService } from '../services/chat/olly_chat_service';
const pplGenerationRoute = {
path: ASSISTANT_API.PPL_GENERATOR,
validate: {
body: schema.object({
index: schema.string(),
question: schema.string(),
}),
},
};
export type PPLGenerationRequestSchema = TypeOf<typeof pplGenerationRoute.validate.body>;
const summarizationRoute = {
path: ASSISTANT_API.SUMMARIZATION,
validate: {
body: schema.object({
question: schema.string(),
response: schema.string(),
query: schema.maybe(schema.string()),
isError: schema.boolean(),
index: schema.string(),
}),
},
};
export type SummarizationRequestSchema = TypeOf<typeof summarizationRoute.validate.body>;
export function registerLangchainRoutes(router: IRouter) {
router.post(
pplGenerationRoute,
async (
context,
request,
response
): Promise<IOpenSearchDashboardsResponse<HttpResponsePayload | ResponseError>> => {
const chatService = new OllyChatService();
try {
const ppl = await chatService.generatePPL(context, request);
return response.ok({ body: ppl });
} catch (error) {
context.assistant_plugin.logger.warn(error);
return response.custom({ statusCode: error.statusCode || 500, body: error.message });
}
}
);
router.post(
summarizationRoute,
async (
context,
request,
response
): Promise<IOpenSearchDashboardsResponse<HttpResponsePayload | ResponseError>> => {
try {
const runs: Run[] = [];
const traceId = uuid();
const opensearchClient = context.core.opensearch.client.asCurrentUser;
const callbacks = [new OpenSearchTracer(opensearchClient, traceId, runs)];
const model = LLMModelFactory.createModel({ client: opensearchClient });
const chainResponse = await requestSummarizationChain(
{ client: opensearchClient, model, ...request.body },
callbacks
);
return response.ok({ body: chainResponse });
} catch (error) {
context.assistant_plugin.logger.warn(error);
return response.custom({ statusCode: error.statusCode || 500, body: error.message });
}
}
);
router.post(
{
path: ASSISTANT_API.AGENT_TEST,
validate: {
body: schema.object({
question: schema.string(),
}),
},
},
async (
context,
request,
response
): Promise<IOpenSearchDashboardsResponse<HttpResponsePayload | ResponseError>> => {
try {
const { question } = request.body;
const opensearchObservabilityClient: ILegacyScopedClusterClient = context.assistant_plugin.observabilityClient.asScoped(
request
);
console.log('########### START CHAIN ####################');
// We can construct an LLMChain from a PromptTemplate and an LLM.
const model = new MLCommonsChatModel({}, context.core.opensearch.client.asCurrentUser);
const prompt = PromptTemplate.fromTemplate(
'What is a good name for a company that makes {product}?'
);
const chainA = new LLMChain({ llm: model, prompt });
// The result is an object with a `text` property.
const resA = await chainA.call({ product: 'colorful socks' });
console.log('########### END CHAIN ####################');
return response.ok({ body: resA });
} catch (error) {
return response.custom({
statusCode: error.statusCode || 500,
body: error.message,
});
}
}
);
router.post(
{
path: ASSISTANT_API.FEEDBACK,
validate: {
body: schema.object({
metadata: schema.object({
user: schema.string(),
tenant: schema.string(),
type: schema.string(),
sessionId: schema.maybe(schema.string()),
traceId: schema.maybe(schema.string()),
error: schema.maybe(schema.boolean()),
selectedIndex: schema.maybe(schema.string()),
}),
input: schema.string(),
output: schema.string(),
correct: schema.boolean(),
expectedOutput: schema.string(),
comment: schema.string(),
}),
},
},
async (
context,
request,
response
): Promise<IOpenSearchDashboardsResponse<HttpResponsePayload | ResponseError>> => {
try {
await context.core.opensearch.client.asCurrentUser.index({
index: LLM_INDEX.FEEDBACK,
body: { ...request.body, timestamp: new Date().toISOString() },
});
return response.ok();
} catch (error) {
console.error(error);
return response.custom({
statusCode: error.statusCode || 500,
body: error.message,
});
}
}
);
}