-
Notifications
You must be signed in to change notification settings - Fork 2k
/
zapier.ts
300 lines (263 loc) Β· 9.1 KB
/
zapier.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { Serializable } from "@langchain/core/load/serializable";
import { Tool } from "@langchain/core/tools";
import { renderTemplate } from "@langchain/core/prompts";
import {
AsyncCaller,
AsyncCallerParams,
} from "@langchain/core/utils/async_caller";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
const zapierNLABaseDescription: string =
"A wrapper around Zapier NLA actions. " +
"The input to this tool is a natural language instruction, " +
'for example "get the latest email from my bank" or ' +
'"send a slack message to the #general channel". ' +
"Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. " +
"For example, if the params are ['Message_Text', 'Channel'], your instruction should be something like 'send a slack message to the #general channel with the text hello world'. " +
"Another example: if the params are ['Calendar', 'Search_Term'], your instruction should be something like 'find the meeting in my personal calendar at 3pm'. " +
"Do not make up params, they will be explicitly specified in the tool description. " +
"If you do not have enough information to fill in the params, just say 'not enough information provided in the instruction, missing <param>'. " +
"If you get a none or null response, STOP EXECUTION, do not try to another tool! " +
"This tool specifically used for: {zapier_description}, " +
"and has params: {params}";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ZapierValues = Record<string, any>;
export interface ZapierNLAWrapperParams extends AsyncCallerParams {
/**
* NLA API Key. Found in the NLA documentation https://nla.zapier.com/docs/authentication/#api-key
* Can also be set via the environment variable `ZAPIER_NLA_API_KEY`
*/
apiKey?: string;
/**
* NLA OAuth Access Token. Found in the NLA documentation https://nla.zapier.com/docs/authentication/#oauth-credentials
* Can also be set via the environment variable `ZAPIER_NLA_OAUTH_ACCESS_TOKEN`
*/
oauthAccessToken?: string;
}
/**
* @deprecated Zapier has sunsetted the NLA API.
* A wrapper class for Zapier's Natural Language Actions (NLA). It
* provides an interface to interact with the 5k+ apps and 20k+ actions on
* Zapier's platform through a natural language API interface. This
* includes apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot,
* Google Sheets, Microsoft Teams, and many more.
*/
export class ZapierNLAWrapper extends Serializable {
lc_namespace = ["langchain", "tools", "zapier"];
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "ZAPIER_NLA_API_KEY",
};
}
zapierNlaApiKey?: string;
zapierNlaOAuthAccessToken?: string;
zapierNlaApiBase = "https://nla.zapier.com/api/v1/";
caller: AsyncCaller;
constructor(params?: ZapierNLAWrapperParams) {
super(params);
const zapierNlaOAuthAccessToken = params?.oauthAccessToken;
const zapierNlaApiKey = params?.apiKey;
const oauthAccessToken =
zapierNlaOAuthAccessToken ??
getEnvironmentVariable("ZAPIER_NLA_OAUTH_ACCESS_TOKEN");
const apiKey =
zapierNlaApiKey ?? getEnvironmentVariable("ZAPIER_NLA_API_KEY");
if (!apiKey && !oauthAccessToken) {
throw new Error(
"Neither ZAPIER_NLA_OAUTH_ACCESS_TOKEN or ZAPIER_NLA_API_KEY are set"
);
}
if (oauthAccessToken) {
this.zapierNlaOAuthAccessToken = oauthAccessToken;
} else {
this.zapierNlaApiKey = apiKey;
}
this.caller = new AsyncCaller(
typeof params === "string" ? {} : params ?? {}
);
}
protected _getHeaders(): Record<string, string> {
const headers: {
"Content-Type": string;
Accept: string;
Authorization?: string;
"x-api-key"?: string;
} = {
"Content-Type": "application/json",
Accept: "application/json",
};
if (this.zapierNlaOAuthAccessToken) {
headers.Authorization = `Bearer ${this.zapierNlaOAuthAccessToken}`;
} else {
headers["x-api-key"] = this.zapierNlaApiKey;
}
return headers;
}
protected async _getActionRequest(
actionId: string,
instructions: string,
params?: ZapierValues
): Promise<ZapierValues> {
const data = params ?? {};
data.instructions = instructions;
const headers = this._getHeaders();
// add api key to params
const resp = await this.caller.call(
fetch,
`${this.zapierNlaApiBase}exposed/${actionId}/execute/`,
{
method: "POST",
headers,
body: JSON.stringify(data),
}
);
if (!resp.ok) {
throw new Error(
`Failed to execute action ${actionId} with instructions ${instructions}`
);
}
const jsonResp = await resp.json();
if (jsonResp.status === "error") {
throw new Error(`Error from Zapier: ${jsonResp.error}`);
}
return jsonResp;
}
/**
* Executes an action that is identified by action_id, must be exposed
* (enabled) by the current user (associated with the set api_key or access token).
* @param actionId
* @param instructions
* @param params
*/
async runAction(
actionId: string,
instructions: string,
params?: ZapierValues
): Promise<ZapierValues> {
const resp = await this._getActionRequest(actionId, instructions, params);
return resp.status === "error" ? resp.error : resp.result;
}
/**
* Same as run, but instead of actually executing the action, will
* instead return a preview of params that have been guessed by the AI in
* case you need to explicitly review before executing.
* @param actionId
* @param instructions
* @param params
*/
async previewAction(
actionId: string,
instructions: string,
params?: ZapierValues
): Promise<ZapierValues> {
const data = params ?? {};
data.preview_only = true;
const resp = await this._getActionRequest(actionId, instructions, data);
return resp.input_params;
}
/**
* Returns a list of all exposed (enabled) actions associated with
* current user (associated with the set api_key or access token).
*/
async listActions(): Promise<ZapierValues[]> {
const headers = this._getHeaders();
const resp = await this.caller.call(
fetch,
`${this.zapierNlaApiBase}exposed/`,
{
method: "GET",
headers,
}
);
if (!resp.ok) {
if (resp.status === 401) {
if (this.zapierNlaOAuthAccessToken) {
throw new Error(
"A 401 Unauthorized error was returned. Check that your access token is correct and doesn't need to be refreshed."
);
}
throw new Error(
"A 401 Unauthorized error was returned. Check that your API Key is correct."
);
}
throw new Error("Failed to list actions");
}
return (await resp.json()).results;
}
/**
* Same as run, but returns a stringified version of the result.
* @param actionId
* @param instructions
* @param params
*/
async runAsString(
actionId: string,
instructions: string,
params?: ZapierValues
): Promise<string> {
const result = await this.runAction(actionId, instructions, params);
return JSON.stringify(result);
}
/**
* Same as preview, but returns a stringified version of the result.
* @param actionId
* @param instructions
* @param params
*/
async previewAsString(
actionId: string,
instructions: string,
params?: ZapierValues
): Promise<string> {
const result = await this.previewAction(actionId, instructions, params);
return JSON.stringify(result);
}
/**
* Same as list, but returns a stringified version of the result.
*/
async listActionsAsString(): Promise<string> {
const result = await this.listActions();
return JSON.stringify(result);
}
}
/**
* @deprecated Zapier has sunsetted the NLA API.
* A tool that uses the `ZapierNLAWrapper` to run a specific action. It
* takes in the `ZapierNLAWrapper` instance, an action ID, a description,
* a schema for the parameters, and optionally the parameters themselves.
*/
export class ZapierNLARunAction extends Tool {
static lc_name() {
return "ZapierNLARunAction";
}
apiWrapper: ZapierNLAWrapper;
actionId: string;
params?: ZapierValues;
name: string;
description: string;
constructor(
apiWrapper: ZapierNLAWrapper,
actionId: string,
zapierDescription: string,
paramsSchema: ZapierValues,
params?: ZapierValues
) {
super();
this.apiWrapper = apiWrapper;
this.actionId = actionId;
this.params = params;
this.name = zapierDescription;
const paramsSchemaWithoutInstructions = { ...paramsSchema };
delete paramsSchemaWithoutInstructions.instructions;
const paramsSchemaKeysString = JSON.stringify(
Object.keys(paramsSchemaWithoutInstructions)
);
this.description = renderTemplate(zapierNLABaseDescription, "f-string", {
zapier_description: zapierDescription,
params: paramsSchemaKeysString,
});
}
/** @ignore */
async _call(arg: string): Promise<string> {
return this.apiWrapper.runAsString(this.actionId, arg, this.params);
}
}