LibreChat/packages/data-provider/src/actions.ts
Danny Avila a0291ed155
🚧 chore: merge latest dev build to main repo (#3844)
* agents - phase 1 (#30)

* chore: copy assistant files

* feat: frontend and data-provider

* feat: backend get endpoint test

* fix(MessageEndpointIcon): switched to AgentName and AgentAvatar

* fix: small fixes

* fix: agent endpoint config

* fix: show Agent Builder

* chore: install agentus

* chore: initial scaffolding for agents

* fix: updated Assistant logic to Agent Logic for some Agent components

* WIP first pass, demo of agent package

* WIP: initial backend infra for agents

* fix: agent list error

* wip: agents routing

* chore: Refactor useSSE hook to handle different data events

* wip: correctly emit events

* chore: Update @librechat/agentus npm dependency to version 1.0.9

* remove comment

* first pass: streaming agent text

* chore: Remove @librechat/agentus root-level workspace npm dependency

* feat: Agent Schema and Model

* fix: content handling fixes

* fix: content message save

* WIP: new content data

* fix: run step issue with tool calls

* chore: Update @librechat/agentus npm dependency to version 1.1.5

* feat: update controller and agent routes

* wip: initial backend tool and tool error handling support

* wip: tool chunks

* chore: Update @librechat/agentus npm dependency to version 1.1.7

* chore: update tool_call typing, add test conditions and logs

* fix: create agent

* fix: create agent

* first pass: render completed content parts

* fix: remove logging, fix step handler typing

* chore: Update @librechat/agentus npm dependency to version 1.1.9

* refactor: cleanup maps on unmount

* chore: Update BaseClient.js to safely count tokens for string, number, and boolean values

* fix: support subsequent messages with tool_calls

* chore: export order

* fix: select agent

* fix: tool call types and handling

* chore: switch to anthropic for testing

* fix: AgentSelect

* refactor: experimental: OpenAIClient to use array for intermediateReply

* fix(useSSE): revert old condition for streaming legacy client tokens

* fix: lint

* revert `agent_id` to `id`

* chore: update localization keys for agent-related components

* feat: zod schema handling for actions

* refactor(actions): if no params, no zodSchema

* chore: Update @librechat/agentus npm dependency to version 1.2.1

* feat: first pass, actions

* refactor: empty schema for actions without params

* feat: Update createRun function to accept additional options

* fix: message payload formatting; feat: add more client options

* fix: ToolCall component rendering when action has no args but has output

* refactor(ToolCall): allow non-stringy args

* WIP: first pass, correctly formatted tool_calls between providers

* refactor: Remove duplicate import of 'roles' module

* refactor: Exclude 'vite.config.ts' from TypeScript compilation

* refactor: fix agent related types
> - no need to use endpoint/model fields for identifying agent metadata
> - add `provider` distinction for agent-configured 'endpoint'
- no need for agent-endpoint map
- reduce complexity of tools as functions into tools as string[]
- fix types related to above changes
- reduce unnecessary variables for queries/mutations and corresponding react-query keys

* refactor: Add tools and tool_kwargs fields to agent schema

* refactor: Remove unused code and update dependencies

* refactor: Update updateAgentHandler to use req.body directly

* refactor: Update AgentSelect component to use localized hooks

* refactor: Update agent schema to include tools and provider fields

* refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values

* refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent

* refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues

* refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only)

* refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string.

* refactor: TypeError issues and handle provider as option

* feat: Add placeholder for provider selection in AgentPanel component

* refactor: Update agent schema to include author and provider fields

* fix: show expected 'create agent' placeholder when creating agent

* chore: fix localization strings, hide capabilities form for now

* chore: typing

* refactor: import order and use compact agents schema for now

* chore: typing

* refactor: Update AgentForm type to use AgentCapabilities

* fix agent form agent selection issues

* feat: responsive agent selection

* fix: Handle cancelled fetch in useSelectAgent hook

* fix: reset agent form on accordion close/open

* feat: Add agent_id to default conversation for agents endpoint

* feat: agents endpoint request handling

* refactor: reset conversation model on agent select

* refactor: add `additional_instructions` to conversation schema, organize other fields

* chore: casing

* chore: types

* refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id

* WIP: initial draft of real agent client initialization

* WIP: first pass, anthropic agent requests

* feat: remember last selected agent

* feat: openai and azure connected

* fix: prioritize agent model for runs unless an explicit override model is passed from client

* feat: Agent Actions

* fix: save agent id to convo

* feat: model panel (#29)

* feat: model panel

* bring back comments

* fix: method still null

* fix: AgentPanel FormContext

* feat: add more parameters

* fix: style issues; refactor: Agent Controller

* fix: cherry-pick

* fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit

* feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters`

* feat: icon and general `model_parameters` update

* feat: use react-hook-form better

* fix: agent builder form reset issue when switching panels

* refactor: modularize agent builder form

---------

Co-authored-by: Danny Avila <danny@librechat.ai>

* fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`.

* fix: tool call issues due to invalid input (anthropic) of empty string

* fix: handle empty text in Part component

---------

Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>

* refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig

* fix: Model Parameters not saved correctly

* refactor: remove console log

* feat: avatar upload and get for Agents (#36)

Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>

* chore: update to public package

* fix: typing, optional chaining

* fix: cursor not showing for content parts

* chore: conditionally enable agents

* ci: fix azure test

* ci: fix frontend tests, fix eslint api

* refactor: Remove unused errorContentPart variable

* continue of the agent message PR (#40)

* last fixes

* fix: agentMap

* pr merge test  (#41)

* fix: model icon not fetching correctly

* remove console logs

* feat: agent name

* refactor: pass documentsMap as a prop to allow re-render of assistant form

* refactor: pass documentsMap as a prop to allow re-render of assistant form

* chore: Bump version to 0.7.419

* fix: TypeError: Cannot read properties of undefined (reading 'id')

* refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox

---------

Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00

445 lines
14 KiB
TypeScript

import { z } from 'zod';
import axios from 'axios';
import { URL } from 'url';
import crypto from 'crypto';
import { load } from 'js-yaml';
import type { FunctionTool, Schema, Reference, ActionMetadata } from './types/assistants';
import type { OpenAPIV3 } from 'openapi-types';
import { Tools, AuthTypeEnum, AuthorizationTypeEnum } from './types/assistants';
export type ParametersSchema = {
type: string;
properties: Record<string, Reference | Schema>;
required: string[];
};
export type OpenAPISchema = OpenAPIV3.SchemaObject &
ParametersSchema & {
items?: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject;
};
export type ApiKeyCredentials = {
api_key: string;
custom_auth_header?: string;
authorization_type?: AuthorizationTypeEnum;
};
export type OAuthCredentials = {
tokenUrl: string;
clientId: string;
clientSecret: string;
scope: string;
};
export type Credentials = ApiKeyCredentials | OAuthCredentials;
export function sha1(input: string) {
return crypto.createHash('sha1').update(input).digest('hex');
}
export function createURL(domain: string, path: string) {
const cleanDomain = domain.replace(/\/$/, '');
const cleanPath = path.replace(/^\//, '');
const fullURL = `${cleanDomain}/${cleanPath}`;
return new URL(fullURL).toString();
}
const schemaTypeHandlers: Record<string, (schema: OpenAPISchema) => z.ZodTypeAny> = {
string: (schema) => {
if (schema.enum) {
return z.enum(schema.enum as [string, ...string[]]);
}
let stringSchema = z.string();
if (schema.minLength !== undefined) {
stringSchema = stringSchema.min(schema.minLength);
}
if (schema.maxLength !== undefined) {
stringSchema = stringSchema.max(schema.maxLength);
}
return stringSchema;
},
number: (schema) => {
let numberSchema = z.number();
if (schema.minimum !== undefined) {
numberSchema = numberSchema.min(schema.minimum);
}
if (schema.maximum !== undefined) {
numberSchema = numberSchema.max(schema.maximum);
}
return numberSchema;
},
integer: (schema) => (schemaTypeHandlers.number(schema) as z.ZodNumber).int(),
boolean: () => z.boolean(),
array: (schema) => {
if (schema.items) {
const zodSchema = openAPISchemaToZod(schema.items as OpenAPISchema);
if (zodSchema) {
return z.array(zodSchema);
}
return z.array(z.unknown());
}
return z.array(z.unknown());
},
object: (schema) => {
const shape: { [key: string]: z.ZodTypeAny } = {};
if (schema.properties) {
Object.entries(schema.properties).forEach(([key, value]) => {
const zodSchema = openAPISchemaToZod(value as OpenAPISchema);
shape[key] = zodSchema || z.unknown();
if (schema.required && schema.required.includes(key)) {
shape[key] = shape[key].describe(value.description || '');
} else {
shape[key] = shape[key].optional().describe(value.description || '');
}
});
}
return z.object(shape);
},
};
function openAPISchemaToZod(schema: OpenAPISchema): z.ZodTypeAny | undefined {
if (schema.type === 'object' && Object.keys(schema.properties || {}).length === 0) {
return undefined;
}
const handler = schemaTypeHandlers[schema.type as string] || (() => z.unknown());
return handler(schema);
}
export class FunctionSignature {
name: string;
description: string;
parameters: ParametersSchema;
constructor(name: string, description: string, parameters: ParametersSchema) {
this.name = name;
this.description = description;
this.parameters = parameters;
}
toObjectTool(): FunctionTool {
return {
type: Tools.function,
function: {
name: this.name,
description: this.description,
parameters: this.parameters,
},
};
}
}
export class ActionRequest {
domain: string;
path: string;
method: string;
operation: string;
operationHash?: string;
isConsequential: boolean;
contentType: string;
params?: object;
constructor(
domain: string,
path: string,
method: string,
operation: string,
isConsequential: boolean,
contentType: string,
) {
this.domain = domain;
this.path = path;
this.method = method;
this.operation = operation;
this.isConsequential = isConsequential;
this.contentType = contentType;
}
private authHeaders: Record<string, string> = {};
private authToken?: string;
setParams(params: object) {
this.operationHash = sha1(JSON.stringify(params));
this.params = params;
for (const [key, value] of Object.entries(params)) {
const paramPattern = `{${key}}`;
if (this.path.includes(paramPattern)) {
this.path = this.path.replace(paramPattern, encodeURIComponent(value as string));
delete (this.params as Record<string, unknown>)[key];
}
}
}
async setAuth(metadata: ActionMetadata) {
if (!metadata.auth) {
return;
}
const {
type,
/* API Key */
authorization_type,
custom_auth_header,
/* OAuth */
authorization_url,
client_url,
scope,
token_exchange_method,
} = metadata.auth;
const {
/* API Key */
api_key,
/* OAuth */
oauth_client_id,
oauth_client_secret,
} = metadata;
const isApiKey = api_key && type === AuthTypeEnum.ServiceHttp;
const isOAuth =
oauth_client_id &&
oauth_client_secret &&
type === AuthTypeEnum.OAuth &&
authorization_url &&
client_url &&
scope &&
token_exchange_method;
if (isApiKey && authorization_type === AuthorizationTypeEnum.Basic) {
const basicToken = Buffer.from(api_key).toString('base64');
this.authHeaders['Authorization'] = `Basic ${basicToken}`;
} else if (isApiKey && authorization_type === AuthorizationTypeEnum.Bearer) {
this.authHeaders['Authorization'] = `Bearer ${api_key}`;
} else if (
isApiKey &&
authorization_type === AuthorizationTypeEnum.Custom &&
custom_auth_header
) {
this.authHeaders[custom_auth_header] = api_key;
} else if (isOAuth) {
// TODO: WIP - OAuth support
if (!this.authToken) {
const tokenResponse = await axios.post(
client_url,
{
client_id: oauth_client_id,
client_secret: oauth_client_secret,
scope: scope,
grant_type: 'client_credentials',
},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
},
);
this.authToken = tokenResponse.data.access_token;
}
this.authHeaders['Authorization'] = `Bearer ${this.authToken}`;
}
}
async execute() {
const url = createURL(this.domain, this.path);
const headers = {
...this.authHeaders,
'Content-Type': this.contentType,
};
const method = this.method.toLowerCase();
if (method === 'get') {
return axios.get(url, { headers, params: this.params });
} else if (method === 'post') {
return axios.post(url, this.params, { headers });
} else if (method === 'put') {
return axios.put(url, this.params, { headers });
} else if (method === 'delete') {
return axios.delete(url, { headers, data: this.params });
} else if (method === 'patch') {
return axios.patch(url, this.params, { headers });
} else {
throw new Error(`Unsupported HTTP method: ${this.method}`);
}
}
}
export function resolveRef(
schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject,
components?: OpenAPIV3.ComponentsObject,
): OpenAPIV3.SchemaObject {
if ('$ref' in schema && components) {
const refPath = schema.$ref.replace(/^#\/components\/schemas\//, '');
const resolvedSchema = components.schemas?.[refPath];
if (!resolvedSchema) {
throw new Error(`Reference ${schema.$ref} not found`);
}
return resolveRef(resolvedSchema, components);
}
return schema as OpenAPIV3.SchemaObject;
}
function sanitizeOperationId(input: string) {
return input.replace(/[^a-zA-Z0-9_-]/g, '');
}
/** Function to convert OpenAPI spec to function signatures and request builders */
export function openapiToFunction(
openapiSpec: OpenAPIV3.Document,
generateZodSchemas = false,
): {
functionSignatures: FunctionSignature[];
requestBuilders: Record<string, ActionRequest>;
zodSchemas?: Record<string, z.ZodTypeAny>;
} {
const functionSignatures: FunctionSignature[] = [];
const requestBuilders: Record<string, ActionRequest> = {};
const zodSchemas: Record<string, z.ZodTypeAny> = {};
const baseUrl = openapiSpec.servers?.[0]?.url ?? '';
// Iterate over each path and method in the OpenAPI spec
for (const [path, methods] of Object.entries(openapiSpec.paths)) {
for (const [method, operation] of Object.entries(methods as OpenAPIV3.PathsObject)) {
const operationObj = operation as OpenAPIV3.OperationObject & {
'x-openai-isConsequential'?: boolean;
};
// Operation ID is used as the function name
const defaultOperationId = `${method}_${path}`;
const operationId = operationObj.operationId || sanitizeOperationId(defaultOperationId);
const description = operationObj.summary || operationObj.description || '';
const parametersSchema: OpenAPISchema = {
type: 'object',
properties: {},
required: [],
};
if (operationObj.parameters) {
for (const param of operationObj.parameters) {
const paramObj = param as OpenAPIV3.ParameterObject;
const resolvedSchema = resolveRef(
{ ...paramObj.schema } as OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject,
openapiSpec.components,
);
parametersSchema.properties[paramObj.name] = resolvedSchema;
if (paramObj.required) {
parametersSchema.required.push(paramObj.name);
}
}
}
if (operationObj.requestBody) {
const requestBody = operationObj.requestBody as OpenAPIV3.RequestBodyObject;
const content = requestBody.content;
const contentType = Object.keys(content)[0];
const schema = content[contentType]?.schema;
const resolvedSchema = resolveRef(
schema as OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject,
openapiSpec.components,
);
parametersSchema.properties = {
...parametersSchema.properties,
...resolvedSchema.properties,
};
if (resolvedSchema.required) {
parametersSchema.required.push(...resolvedSchema.required);
}
}
const functionSignature = new FunctionSignature(operationId, description, parametersSchema);
functionSignatures.push(functionSignature);
const actionRequest = new ActionRequest(
baseUrl,
path,
method,
operationId,
!!operationObj['x-openai-isConsequential'], // Custom extension for consequential actions
operationObj.requestBody ? 'application/json' : 'application/x-www-form-urlencoded',
);
requestBuilders[operationId] = actionRequest;
if (generateZodSchemas && Object.keys(parametersSchema.properties).length > 0) {
const schema = openAPISchemaToZod(parametersSchema);
if (schema) {
zodSchemas[operationId] = schema;
}
}
}
}
return { functionSignatures, requestBuilders, zodSchemas };
}
export type ValidationResult = {
status: boolean;
message: string;
spec?: OpenAPIV3.Document;
};
export function validateAndParseOpenAPISpec(specString: string): ValidationResult {
try {
let parsedSpec;
try {
parsedSpec = JSON.parse(specString);
} catch {
parsedSpec = load(specString);
}
// Check for servers
if (
!parsedSpec.servers ||
!Array.isArray(parsedSpec.servers) ||
parsedSpec.servers.length === 0
) {
return { status: false, message: 'Could not find a valid URL in `servers`' };
}
if (!parsedSpec.servers[0].url) {
return { status: false, message: 'Could not find a valid URL in `servers`' };
}
// Check for paths
const paths = parsedSpec.paths;
if (!paths || typeof paths !== 'object' || Object.keys(paths).length === 0) {
return { status: false, message: 'No paths found in the OpenAPI spec.' };
}
const components = parsedSpec.components?.schemas || {};
const messages = [];
for (const [path, methods] of Object.entries(paths)) {
for (const [httpMethod, operation] of Object.entries(methods as OpenAPIV3.PathItemObject)) {
// Ensure operation is a valid operation object
const { responses } = operation as OpenAPIV3.OperationObject;
if (typeof operation === 'object' && responses) {
for (const [statusCode, response] of Object.entries(responses)) {
const content = (response as OpenAPIV3.ResponseObject).content;
if (content && content['application/json'] && content['application/json'].schema) {
const schema = content['application/json'].schema;
if ('$ref' in schema && typeof schema.$ref === 'string') {
const refName = schema.$ref.split('/').pop();
if (refName && !components[refName]) {
messages.push(
`In context=('paths', '${path}', '${httpMethod}', '${statusCode}', 'response', 'content', 'application/json', 'schema'), reference to unknown component ${refName}; using empty schema`,
);
}
}
}
}
}
}
}
return {
status: true,
message: messages.join('\n') || 'OpenAPI spec is valid.',
spec: parsedSpec,
};
} catch (error) {
return { status: false, message: 'Error parsing OpenAPI spec.' };
}
}