@aigne/core 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/lib/cjs/index.js +1 -1
  2. package/lib/cjs/types/index.js +2 -4
  3. package/lib/esm/index.js +1 -1
  4. package/lib/esm/types/index.js +2 -4
  5. package/lib/types/index.d.ts +1 -1
  6. package/lib/types/types/agent.d.ts +5 -0
  7. package/lib/types/types/index.d.ts +2 -4
  8. package/lib/types/types/runnable.d.ts +20 -0
  9. package/package.json +3 -4
  10. package/lib/cjs/assistant/generate-output.js +0 -101
  11. package/lib/cjs/assistant/select-agent.js +0 -76
  12. package/lib/cjs/assistant/type.js +0 -11
  13. package/lib/cjs/common/aid.js +0 -42
  14. package/lib/cjs/common/index.js +0 -238
  15. package/lib/cjs/common/resource-manager.js +0 -199
  16. package/lib/cjs/constants.js +0 -9
  17. package/lib/cjs/executor/agent.js +0 -10
  18. package/lib/cjs/executor/aigc.js +0 -28
  19. package/lib/cjs/executor/api.js +0 -64
  20. package/lib/cjs/executor/base.js +0 -676
  21. package/lib/cjs/executor/blocklet.js +0 -25
  22. package/lib/cjs/executor/call-agent.js +0 -105
  23. package/lib/cjs/executor/decision.js +0 -478
  24. package/lib/cjs/executor/image-blender.js +0 -32
  25. package/lib/cjs/executor/index.js +0 -81
  26. package/lib/cjs/executor/llm.js +0 -379
  27. package/lib/cjs/executor/logic.js +0 -167
  28. package/lib/cjs/libs/blocklet/vc.js +0 -92
  29. package/lib/cjs/libs/openapi/request/index.js +0 -24
  30. package/lib/cjs/libs/openapi/request/util.js +0 -146
  31. package/lib/cjs/libs/openapi/types/index.js +0 -17
  32. package/lib/cjs/libs/openapi/util/call.js +0 -15
  33. package/lib/cjs/libs/openapi/util/check-schema.js +0 -67
  34. package/lib/cjs/libs/openapi/util/convert-schema.js +0 -44
  35. package/lib/cjs/libs/openapi/util/flatten-open-api.js +0 -21
  36. package/lib/cjs/libs/openapi/util/get-open-api-i18n-text.js +0 -7
  37. package/lib/cjs/runtime/resource-blocklet.js +0 -5
  38. package/lib/cjs/runtime/runtime.js +0 -143
  39. package/lib/cjs/types/assistant/index.js +0 -31
  40. package/lib/cjs/types/assistant/mustache/ReadableMustache.js +0 -69
  41. package/lib/cjs/types/assistant/mustache/directive.js +0 -35
  42. package/lib/cjs/types/assistant/mustache/mustache.js +0 -688
  43. package/lib/cjs/types/resource/index.js +0 -47
  44. package/lib/cjs/types/resource/project.js +0 -35
  45. package/lib/cjs/types/runtime/error.js +0 -18
  46. package/lib/cjs/types/runtime/index.js +0 -37
  47. package/lib/cjs/types/runtime/runtime-resource-blocklet-state.js +0 -4
  48. package/lib/cjs/types/runtime/schema.js +0 -259
  49. package/lib/cjs/utils/cron-job.js +0 -48
  50. package/lib/cjs/utils/extract-metadata-transform.js +0 -58
  51. package/lib/cjs/utils/extract-metadata-transform.test.js +0 -61
  52. package/lib/cjs/utils/fs.js +0 -49
  53. package/lib/cjs/utils/get-blocklet-agent.js +0 -351
  54. package/lib/cjs/utils/geti.js +0 -37
  55. package/lib/cjs/utils/is-non-nullable.js +0 -20
  56. package/lib/cjs/utils/render-message.js +0 -23
  57. package/lib/cjs/utils/resolve-secret-inputs.js +0 -49
  58. package/lib/cjs/utils/retry.js +0 -19
  59. package/lib/cjs/utils/task-id.js +0 -7
  60. package/lib/cjs/utils/tool-calls-transform.js +0 -18
  61. package/lib/esm/assistant/generate-output.js +0 -91
  62. package/lib/esm/assistant/select-agent.js +0 -71
  63. package/lib/esm/assistant/type.js +0 -7
  64. package/lib/esm/common/aid.js +0 -38
  65. package/lib/esm/common/index.js +0 -232
  66. package/lib/esm/common/resource-manager.js +0 -192
  67. package/lib/esm/constants.js +0 -6
  68. package/lib/esm/executor/agent.js +0 -6
  69. package/lib/esm/executor/aigc.js +0 -24
  70. package/lib/esm/executor/api.js +0 -34
  71. package/lib/esm/executor/base.js +0 -668
  72. package/lib/esm/executor/blocklet.js +0 -21
  73. package/lib/esm/executor/call-agent.js +0 -98
  74. package/lib/esm/executor/decision.js +0 -471
  75. package/lib/esm/executor/image-blender.js +0 -25
  76. package/lib/esm/executor/index.js +0 -74
  77. package/lib/esm/executor/llm.js +0 -372
  78. package/lib/esm/executor/logic.js +0 -160
  79. package/lib/esm/libs/blocklet/vc.js +0 -85
  80. package/lib/esm/libs/openapi/request/index.js +0 -20
  81. package/lib/esm/libs/openapi/request/util.js +0 -136
  82. package/lib/esm/libs/openapi/types/index.js +0 -1
  83. package/lib/esm/libs/openapi/util/call.js +0 -8
  84. package/lib/esm/libs/openapi/util/check-schema.js +0 -62
  85. package/lib/esm/libs/openapi/util/convert-schema.js +0 -42
  86. package/lib/esm/libs/openapi/util/flatten-open-api.js +0 -19
  87. package/lib/esm/libs/openapi/util/get-open-api-i18n-text.js +0 -5
  88. package/lib/esm/runtime/resource-blocklet.js +0 -2
  89. package/lib/esm/runtime/runtime.js +0 -136
  90. package/lib/esm/types/assistant/index.js +0 -9
  91. package/lib/esm/types/assistant/mustache/ReadableMustache.js +0 -63
  92. package/lib/esm/types/assistant/mustache/directive.js +0 -29
  93. package/lib/esm/types/assistant/mustache/mustache.js +0 -686
  94. package/lib/esm/types/resource/index.js +0 -26
  95. package/lib/esm/types/resource/project.js +0 -29
  96. package/lib/esm/types/runtime/error.js +0 -14
  97. package/lib/esm/types/runtime/index.js +0 -20
  98. package/lib/esm/types/runtime/runtime-resource-blocklet-state.js +0 -1
  99. package/lib/esm/types/runtime/schema.js +0 -249
  100. package/lib/esm/utils/cron-job.js +0 -44
  101. package/lib/esm/utils/extract-metadata-transform.js +0 -54
  102. package/lib/esm/utils/extract-metadata-transform.test.js +0 -59
  103. package/lib/esm/utils/fs.js +0 -41
  104. package/lib/esm/utils/get-blocklet-agent.js +0 -344
  105. package/lib/esm/utils/geti.js +0 -30
  106. package/lib/esm/utils/is-non-nullable.js +0 -13
  107. package/lib/esm/utils/render-message.js +0 -20
  108. package/lib/esm/utils/resolve-secret-inputs.js +0 -46
  109. package/lib/esm/utils/retry.js +0 -16
  110. package/lib/esm/utils/task-id.js +0 -3
  111. package/lib/esm/utils/tool-calls-transform.js +0 -15
  112. package/lib/types/assistant/generate-output.d.ts +0 -29
  113. package/lib/types/assistant/select-agent.d.ts +0 -14
  114. package/lib/types/assistant/type.d.ts +0 -61
  115. package/lib/types/common/aid.d.ts +0 -18
  116. package/lib/types/common/index.d.ts +0 -7
  117. package/lib/types/common/resource-manager.d.ts +0 -88
  118. package/lib/types/constants.d.ts +0 -6
  119. package/lib/types/executor/agent.d.ts +0 -5
  120. package/lib/types/executor/aigc.d.ts +0 -9
  121. package/lib/types/executor/api.d.ts +0 -9
  122. package/lib/types/executor/base.d.ts +0 -209
  123. package/lib/types/executor/blocklet.d.ts +0 -9
  124. package/lib/types/executor/call-agent.d.ts +0 -12
  125. package/lib/types/executor/decision.d.ts +0 -20
  126. package/lib/types/executor/image-blender.d.ts +0 -9
  127. package/lib/types/executor/index.d.ts +0 -8
  128. package/lib/types/executor/llm.d.ts +0 -38
  129. package/lib/types/executor/logic.d.ts +0 -9
  130. package/lib/types/libs/blocklet/vc.d.ts +0 -17
  131. package/lib/types/libs/openapi/request/index.d.ts +0 -17
  132. package/lib/types/libs/openapi/request/util.d.ts +0 -40
  133. package/lib/types/libs/openapi/types/index.d.ts +0 -20
  134. package/lib/types/libs/openapi/util/call.d.ts +0 -2
  135. package/lib/types/libs/openapi/util/check-schema.d.ts +0 -3
  136. package/lib/types/libs/openapi/util/convert-schema.d.ts +0 -8
  137. package/lib/types/libs/openapi/util/flatten-open-api.d.ts +0 -3
  138. package/lib/types/libs/openapi/util/get-open-api-i18n-text.d.ts +0 -2
  139. package/lib/types/runtime/resource-blocklet.d.ts +0 -2
  140. package/lib/types/runtime/runtime.d.ts +0 -20
  141. package/lib/types/types/assistant/index.d.ts +0 -405
  142. package/lib/types/types/assistant/mustache/ReadableMustache.d.ts +0 -2
  143. package/lib/types/types/assistant/mustache/directive.d.ts +0 -6
  144. package/lib/types/types/assistant/mustache/mustache.d.ts +0 -2
  145. package/lib/types/types/common/index.d.ts +0 -45
  146. package/lib/types/types/resource/index.d.ts +0 -17
  147. package/lib/types/types/resource/project.d.ts +0 -41
  148. package/lib/types/types/runtime/agent.d.ts +0 -33
  149. package/lib/types/types/runtime/error.d.ts +0 -10
  150. package/lib/types/types/runtime/index.d.ts +0 -116
  151. package/lib/types/types/runtime/runtime-resource-blocklet-state.d.ts +0 -5
  152. package/lib/types/types/runtime/schema.d.ts +0 -110
  153. package/lib/types/utils/cron-job.d.ts +0 -22
  154. package/lib/types/utils/extract-metadata-transform.d.ts +0 -16
  155. package/lib/types/utils/extract-metadata-transform.test.d.ts +0 -1
  156. package/lib/types/utils/fs.d.ts +0 -9
  157. package/lib/types/utils/get-blocklet-agent.d.ts +0 -219
  158. package/lib/types/utils/geti.d.ts +0 -1
  159. package/lib/types/utils/is-non-nullable.d.ts +0 -2
  160. package/lib/types/utils/render-message.d.ts +0 -6
  161. package/lib/types/utils/resolve-secret-inputs.d.ts +0 -11
  162. package/lib/types/utils/retry.d.ts +0 -1
  163. package/lib/types/utils/task-id.d.ts +0 -1
  164. package/lib/types/utils/tool-calls-transform.d.ts +0 -2
  165. /package/lib/cjs/types/{runtime/agent.js → agent.js} +0 -0
  166. /package/lib/cjs/types/{common/index.js → runnable.js} +0 -0
  167. /package/lib/esm/types/{runtime/agent.js → agent.js} +0 -0
  168. /package/lib/esm/types/{common/index.js → runnable.js} +0 -0
@@ -1,136 +0,0 @@
1
- import convertSchemaToObject from '../util/convert-schema';
2
- export const getRequestConfig = (pathItem, requestData, options) => {
3
- let url = pathItem.path || '';
4
- const config = {
5
- method: pathItem.method,
6
- url,
7
- headers: {},
8
- params: options?.params || {},
9
- data: options?.data || {},
10
- cookies: {},
11
- body: {},
12
- };
13
- const data = { ...requestData };
14
- const requestBodyData = { ...data };
15
- for (const parameter of pathItem.parameters || []) {
16
- if (Object.prototype.hasOwnProperty.call(data, parameter.name)) {
17
- const value = data[parameter.name];
18
- switch (parameter.in) {
19
- case 'path':
20
- url = url.replace(`{${parameter.name}}`, encodeURIComponent(value));
21
- break;
22
- case 'query':
23
- config.params[parameter.name] = value;
24
- break;
25
- case 'header':
26
- config.headers[parameter.name] = value;
27
- break;
28
- case 'cookie':
29
- config.cookies[parameter.name] = value;
30
- break;
31
- default:
32
- throw new Error('Unsupported parameter type');
33
- }
34
- delete requestBodyData[parameter.name];
35
- }
36
- }
37
- if (['POST', 'PUT', 'PATCH'].includes(pathItem.method.toUpperCase()) && pathItem.requestBody) {
38
- config.headers['Content-Type'] = getContentType(pathItem.requestBody);
39
- config.data = getRequestBody(pathItem.requestBody, requestBodyData || {});
40
- }
41
- config.url = url;
42
- config.body = requestBodyData;
43
- return config;
44
- };
45
- function getContentType(requestBody) {
46
- if (requestBody && requestBody.content) {
47
- const [firstMediaType] = Object.keys(requestBody.content);
48
- return firstMediaType || 'application/json';
49
- }
50
- return 'application/json';
51
- }
52
- function getRequestBody(requestBody, requestBodyData) {
53
- if (requestBody && requestBody.content) {
54
- const contentType = getContentType(requestBody);
55
- const mediaTypeObject = requestBody.content[contentType];
56
- if (mediaTypeObject && mediaTypeObject.schema) {
57
- switch (contentType) {
58
- case 'application/json':
59
- return JSON.stringify(requestBodyData);
60
- case 'application/x-www-form-urlencoded':
61
- return serializeFormEncoded(requestBodyData);
62
- case 'multipart/form-data':
63
- // eslint-disable-next-line no-case-declarations
64
- const formData = new FormData();
65
- Object.keys(requestBodyData).forEach((key) => {
66
- const value = requestBodyData[key];
67
- if (Array.isArray(value)) {
68
- value.forEach((item, index) => formData.append(`${key}[${index}]`, item));
69
- }
70
- else if (typeof value === 'object' && value !== null) {
71
- Object.keys(value).forEach((subKey) => {
72
- formData.append(`${key}[${subKey}]`, value[subKey]);
73
- });
74
- }
75
- else {
76
- formData.append(key, value);
77
- }
78
- });
79
- return formData;
80
- default:
81
- throw new Error(`Unsupported content type: ${contentType}`);
82
- }
83
- }
84
- }
85
- return requestBodyData;
86
- }
87
- function serializeFormEncoded(data) {
88
- return Object.keys(data)
89
- .map((key) => {
90
- const value = data[key];
91
- if (typeof value === 'object' && value !== null) {
92
- return serializeNestedObject(key, value);
93
- }
94
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
95
- })
96
- .join('&');
97
- }
98
- function serializeNestedObject(parentKey, obj) {
99
- return Object.keys(obj)
100
- .map((key) => {
101
- const value = obj[key];
102
- const fullKey = `${parentKey}[${key}]`;
103
- if (typeof value === 'object' && value !== null) {
104
- return serializeNestedObject(fullKey, value);
105
- }
106
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value)}`;
107
- })
108
- .join('&');
109
- }
110
- export function extractRequestBodyParameters(requestBody) {
111
- if (!requestBody || !requestBody.content) {
112
- return [];
113
- }
114
- const contentType = getContentType(requestBody);
115
- const mediaTypeObject = requestBody.content[contentType];
116
- if (!mediaTypeObject || !mediaTypeObject.schema) {
117
- console.warn(`No schema available for content type: ${contentType}`);
118
- return [];
119
- }
120
- const { schema } = mediaTypeObject;
121
- const schemaObject = convertSchemaToObject(schema);
122
- return Object.entries(schemaObject).map(([key, value]) => ({ name: key, ...value })) || [];
123
- }
124
- export function getAllParameters(dataset) {
125
- const requestBody = extractRequestBodyParameters(dataset?.requestBody);
126
- const datasetParameters = [
127
- ...(dataset?.parameters ?? []).map((i) => ({ ...i, type: i.schema?.type })),
128
- ...(requestBody ?? []),
129
- ];
130
- return datasetParameters;
131
- }
132
- export function getRequiredFields(dataset) {
133
- const parameterFields = dataset.parameters?.filter((param) => param.required).map((param) => param.name) || [];
134
- const requestBodyFields = Object.values(dataset.requestBody?.content || {}).flatMap((mediaObject) => mediaObject.schema?.required || []);
135
- return [...new Set([...parameterFields, ...requestBodyFields])];
136
- }
@@ -1 +0,0 @@
1
- export * from 'openapi3-ts/oas31';
@@ -1,8 +0,0 @@
1
- import { call as originalCall } from '@blocklet/sdk/lib/component';
2
- import isNil from 'lodash/isNil';
3
- export const call = (options) => {
4
- return originalCall({
5
- ...options,
6
- params: Object.fromEntries(Object.entries(options.params ?? {}).map(([key, value]) => [key, isNil(value) ? '' : String(value)])),
7
- });
8
- };
@@ -1,62 +0,0 @@
1
- import Joi from 'joi';
2
- const CustomJoi = Joi.extend((joi) => ({
3
- type: 'string',
4
- base: joi.string(),
5
- messages: {
6
- 'string.customId': '{{#label}} does not match the expected format (type:path:method)',
7
- },
8
- rules: {
9
- customId: {
10
- validate(value, helpers) {
11
- const [, path, method] = value.split(':');
12
- const parts = helpers.state.ancestors[0];
13
- if (!path || !method) {
14
- return helpers.error('string.customId');
15
- }
16
- if (path !== parts.path || (method || '').toLocaleLowerCase() !== (parts.method || '').toLocaleLowerCase()) {
17
- return helpers.error('string.customId');
18
- }
19
- return value;
20
- },
21
- },
22
- },
23
- }));
24
- const BaseParameterObjectSchema = Joi.object({
25
- description: Joi.string().optional(),
26
- required: Joi.boolean().optional(),
27
- deprecated: Joi.boolean().optional(),
28
- allowEmptyValue: Joi.boolean().optional(),
29
- style: Joi.string()
30
- .valid('matrix', 'label', 'form', 'simple', 'spaceDelimited', 'pipeDelimited', 'deepObject')
31
- .insensitive()
32
- .optional(),
33
- explode: Joi.boolean().optional(),
34
- allowReserved: Joi.boolean().optional(),
35
- schema: Joi.any().optional(),
36
- examples: Joi.object().pattern(Joi.string(), Joi.any).optional(),
37
- example: Joi.any().optional(),
38
- content: Joi.any().optional(),
39
- }).optional();
40
- const ParameterObjectSchema = BaseParameterObjectSchema.keys({
41
- name: Joi.string().required(),
42
- in: Joi.string().valid('query', 'header', 'path', 'cookie').insensitive().required(),
43
- });
44
- const RequestBodyObjectSchema = Joi.object({});
45
- const ResponsesObjectSchema = Joi.object({});
46
- export default Joi.object({
47
- id: CustomJoi.string().customId().required(),
48
- name: Joi.string().optional().allow('').empty([null, '']),
49
- type: Joi.string().optional().allow('').empty([null, '']),
50
- url: Joi.string()
51
- .pattern(/^https?:\/\//)
52
- .optional()
53
- .allow('')
54
- .empty([null, '']),
55
- path: Joi.string().required(),
56
- method: Joi.string().valid('GET', 'POST', 'PUT', 'DELETE', 'PATCH').insensitive().required(),
57
- summary: Joi.string().optional().allow('').empty([null, '']),
58
- description: Joi.string().optional().allow('').empty([null, '']),
59
- parameters: Joi.array().items(ParameterObjectSchema).optional().allow(null, '').empty([null, '']),
60
- requestBody: RequestBodyObjectSchema.optional().allow('').empty([null, '']),
61
- responses: ResponsesObjectSchema.optional().allow('').empty([null, '']),
62
- }).unknown(true);
@@ -1,42 +0,0 @@
1
- const convertSchemaToObject = (schema) => {
2
- if (!schema || typeof schema !== 'object') {
3
- throw new Error('Invalid schema: Schema must be an object');
4
- }
5
- switch (schema.type) {
6
- case 'object':
7
- return convertObjectSchema(schema);
8
- case 'array':
9
- return convertArraySchema(schema);
10
- default:
11
- return convertPrimitiveSchema(schema);
12
- }
13
- };
14
- const convertObjectSchema = (schema) => {
15
- const result = {};
16
- if (schema.properties && typeof schema.properties === 'object') {
17
- Object.keys(schema.properties).forEach((property) => {
18
- result[property] = schema.properties[property];
19
- });
20
- }
21
- return result;
22
- };
23
- const convertArraySchema = (schema) => {
24
- if (!schema.items) {
25
- return [];
26
- }
27
- return [convertSchemaToObject(schema.items)];
28
- };
29
- const convertPrimitiveSchema = (schema) => {
30
- switch (schema.type) {
31
- case 'string':
32
- return { ...schema, value: schema.default ?? (schema.enum ? schema.enum[0] : '') };
33
- case 'integer':
34
- case 'number':
35
- return { ...schema, value: schema.default ?? 0 };
36
- case 'boolean':
37
- return { ...schema, value: schema.default ?? false };
38
- default:
39
- return { ...schema, value: schema.default ?? null };
40
- }
41
- };
42
- export default convertSchemaToObject;
@@ -1,19 +0,0 @@
1
- function flattenApiStructure(apiStructure) {
2
- const flattened = [];
3
- const paths = apiStructure?.paths || {};
4
- for (const path in paths) {
5
- for (const method in paths[path]) {
6
- const endpoint = paths[path]?.[method];
7
- flattened.push({
8
- id: endpoint['x-id'],
9
- name: endpoint['x-did'],
10
- path: endpoint['x-path'],
11
- method: endpoint['x-method'],
12
- did: endpoint['x-did'],
13
- ...endpoint,
14
- });
15
- }
16
- }
17
- return flattened;
18
- }
19
- export default flattenApiStructure;
@@ -1,5 +0,0 @@
1
- const getOpenApiTextFromI18n = (data, key, locale) => {
2
- const i18nKey = `x-${key}-${locale}`;
3
- return data[i18nKey] || data[key];
4
- };
5
- export default getOpenApiTextFromI18n;
@@ -1,2 +0,0 @@
1
- import { ResourceManager } from '../common/resource-manager';
2
- export const resourceManager = new ResourceManager();
@@ -1,136 +0,0 @@
1
- import { join } from 'path';
2
- import { chatCompletions, imageGenerations } from '@blocklet/ai-kit/api/call';
3
- import { readFile } from 'fs-extra';
4
- import { glob } from 'glob';
5
- import { parse } from 'yaml';
6
- import { defaultImageModel, defaultTextModel, getSupportedImagesModels } from '../common';
7
- import { parseIdentity, stringifyIdentity } from '../common/aid';
8
- import { RuntimeExecutor } from '../executor';
9
- import logger from '../logger';
10
- import { nextId } from '../utils/task-id';
11
- import { resourceManager } from './resource-blocklet';
12
- export class AIGNERuntime {
13
- project;
14
- static async load(options) {
15
- const projectFilePath = join(options.path, 'project.yaml');
16
- const project = parse((await readFile(projectFilePath)).toString());
17
- // TODO: validate parsed project
18
- const agentFilePaths = await glob(join(options.path, 'prompts', '**/*.yaml'));
19
- const agents = await Promise.all(agentFilePaths.map(async (filename) => {
20
- const agent = parse((await readFile(filename)).toString());
21
- // TODO: validate parsed agent
22
- return agent;
23
- }));
24
- const memoryFilePath = join(options.path, 'config/variable.yaml');
25
- const memories = parse((await readFile(memoryFilePath)).toString())?.variables;
26
- // TODO: validate parsed memories
27
- const p = {
28
- ...project,
29
- agents,
30
- memories,
31
- };
32
- return new AIGNERuntime(p);
33
- }
34
- constructor(project) {
35
- this.project = project;
36
- }
37
- async runAgent(agentId, inputs) {
38
- const agent = this.project.agents?.find((a) => a.id === agentId);
39
- if (!agent)
40
- throw new Error(`Agent ${agentId} not found`);
41
- const taskId = nextId();
42
- const messageId = nextId();
43
- const callAI = async ({ input }) => {
44
- return await chatCompletions({ ...input, model: input.model || defaultTextModel });
45
- };
46
- const callAIImage = async ({ assistant, input }) => {
47
- const imageAssistant = assistant.type === 'image' ? assistant : undefined;
48
- const supportImages = await getSupportedImagesModels();
49
- const imageModel = supportImages.find((i) => i.model === (imageAssistant?.model || defaultImageModel));
50
- const model = {
51
- model: input.model || imageModel?.model,
52
- n: input.n || imageModel?.nDefault,
53
- quality: input.quality || imageModel?.qualityDefault,
54
- style: input.style || imageModel?.styleDefault,
55
- size: input.size || imageModel?.sizeDefault,
56
- };
57
- return imageGenerations({
58
- ...input,
59
- ...model,
60
- responseFormat: 'url',
61
- });
62
- };
63
- const executor = new RuntimeExecutor({
64
- entry: { project: this.project },
65
- callback: () => { },
66
- callAI,
67
- callAIImage,
68
- getMemoryVariables: async (options) => {
69
- if (options.projectId === this.project.id)
70
- return this.project.memories ?? [];
71
- logger.warn('Unsupported to get memory variables from other projects');
72
- return [];
73
- },
74
- getAgent: async (options) => {
75
- const identity = parseIdentity(options.aid, { rejectWhenError: true });
76
- let agent;
77
- if (identity.blockletDid) {
78
- const { blockletDid, projectId, agentId } = identity;
79
- const res = await resourceManager.getAgent({ blockletDid, projectId, agentId });
80
- if (res) {
81
- agent = {
82
- ...res.agent,
83
- project: res.project,
84
- identity: {
85
- blockletDid,
86
- projectId,
87
- agentId,
88
- aid: stringifyIdentity({ blockletDid, projectId, agentId }),
89
- },
90
- };
91
- }
92
- }
93
- else if (identity.projectId === this.project.id) {
94
- const a = this.project.agents?.find((a) => a.id === identity.agentId);
95
- if (a) {
96
- agent = {
97
- ...a,
98
- project: this.project,
99
- identity: {
100
- projectId: this.project.id,
101
- agentId: a.id,
102
- aid: stringifyIdentity({ projectId: this.project.id, agentId: a.id }),
103
- },
104
- };
105
- }
106
- }
107
- if (options.rejectOnEmpty && !agent)
108
- throw new Error('No such agent');
109
- return agent;
110
- },
111
- entryProjectId: this.project.id,
112
- sessionId: this.project.id,
113
- messageId,
114
- clientTime: new Date().toISOString(),
115
- queryCache: async ({ aid, cacheKey }) => {
116
- // TODO: implement cache
117
- return null;
118
- },
119
- setCache: async ({ aid, cacheKey, inputs, outputs }) => {
120
- // TODO: implement cache
121
- },
122
- }, {
123
- ...agent,
124
- identity: {
125
- projectId: this.project.id,
126
- agentId: agent.id,
127
- aid: stringifyIdentity({ projectId: this.project.id, agentId: agent.id }),
128
- },
129
- project: this.project,
130
- }, {
131
- inputs,
132
- taskId,
133
- });
134
- return executor.execute();
135
- }
136
- }
@@ -1,9 +0,0 @@
1
- export { default as Mustache } from './mustache/mustache';
2
- export * from './mustache/directive';
3
- export var OnTaskCompletion;
4
- (function (OnTaskCompletion) {
5
- OnTaskCompletion["EXIT"] = "EXIT";
6
- })(OnTaskCompletion || (OnTaskCompletion = {}));
7
- export function isUserInputParameter(parameter) {
8
- return parameter.type !== 'source';
9
- }
@@ -1,63 +0,0 @@
1
- import { ReadableStream } from 'stream/web';
2
- import fastq from 'fastq';
3
- import { renderMessage } from '../../../utils/render-message';
4
- export function renderMustacheStream(template, context) {
5
- return new ReadableStream({
6
- async start(controller) {
7
- try {
8
- // 异步任务队列,每个任务完成之后都会重新渲染模板并返回最新的结果到流中
9
- const queue = fastq.promise(async (p) => {
10
- await p;
11
- await render();
12
- }, 100);
13
- let reject;
14
- const errorPromise = new Promise((_, rej) => {
15
- reject = rej;
16
- });
17
- queue.error((error) => {
18
- if (error)
19
- reject?.(error);
20
- });
21
- // 任务缓存,每个任务的 key 为渲染后的子模板(其中可能包含参数)
22
- const cache = new Map();
23
- const ctx = context((fn) => {
24
- return async (template, render) => {
25
- const rendered = await render(template);
26
- const key = rendered;
27
- let task = cache.get(key);
28
- if (!task) {
29
- const res = fn(template, render, rendered);
30
- if (res instanceof Promise) {
31
- task = { promise: res };
32
- res
33
- .then((value) => {
34
- task.result = { data: value };
35
- })
36
- .catch((error) => {
37
- task.error = { error };
38
- });
39
- queue.push(res);
40
- }
41
- else {
42
- task = { result: { data: res } };
43
- }
44
- cache.set(key, task);
45
- }
46
- if (task.error)
47
- throw task.error.error;
48
- // 返回 promise 完成后的数据,没完成则返回 undefined,避免阻塞 mustache 渲染
49
- return task.result?.data;
50
- };
51
- });
52
- const render = async () => controller.enqueue(await renderMessage(template, ctx, { escapeJsonSymbols: true }));
53
- await render();
54
- // wait for all promise in the queue to be resolved
55
- await Promise.race([queue.drained(), errorPromise]);
56
- }
57
- catch (error) {
58
- controller.error(error);
59
- }
60
- controller.close();
61
- },
62
- });
63
- }
@@ -1,29 +0,0 @@
1
- import Mustache from './mustache';
2
- export function parseDirectives(...content) {
3
- return content.flatMap((content) => {
4
- // 捕获 api/{{var/api/task/{{list}} 这种错误
5
- try {
6
- const spans = Mustache.parse(content);
7
- const directives = [];
8
- for (const span of spans) {
9
- switch (span[0]) {
10
- case 'name': {
11
- const name = span[1];
12
- if (name)
13
- directives.push({ type: 'variable', name });
14
- break;
15
- }
16
- case 'text': {
17
- break;
18
- }
19
- default:
20
- console.warn('Unknown directive', span);
21
- }
22
- }
23
- return directives;
24
- }
25
- catch (error) {
26
- return [];
27
- }
28
- });
29
- }