@tanstack/ai 0.0.2 → 0.1.0

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 (147) hide show
  1. package/README.md +26 -0
  2. package/dist/esm/activities/chat/adapter.d.ts +100 -0
  3. package/dist/esm/activities/chat/adapter.js +14 -0
  4. package/dist/esm/activities/chat/adapter.js.map +1 -0
  5. package/dist/esm/{utilities → activities/chat}/agent-loop-strategies.d.ts +4 -4
  6. package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -0
  7. package/dist/esm/activities/chat/index.d.ts +165 -0
  8. package/dist/esm/{core/chat.js → activities/chat/index.js} +131 -33
  9. package/dist/esm/activities/chat/index.js.map +1 -0
  10. package/dist/esm/{message-converters.d.ts → activities/chat/messages.d.ts} +1 -1
  11. package/dist/esm/{message-converters.js → activities/chat/messages.js} +7 -7
  12. package/dist/esm/activities/chat/messages.js.map +1 -0
  13. package/dist/esm/activities/chat/stream/json-parser.js.map +1 -0
  14. package/dist/esm/{stream → activities/chat/stream}/message-updaters.d.ts +1 -1
  15. package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -0
  16. package/dist/esm/{stream → activities/chat/stream}/processor.d.ts +1 -1
  17. package/dist/esm/{stream → activities/chat/stream}/processor.js +1 -1
  18. package/dist/esm/activities/chat/stream/processor.js.map +1 -0
  19. package/dist/esm/activities/chat/stream/strategies.js.map +1 -0
  20. package/dist/esm/{stream → activities/chat/stream}/types.d.ts +2 -9
  21. package/dist/esm/{tools → activities/chat/tools}/tool-calls.d.ts +1 -1
  22. package/dist/esm/{tools → activities/chat/tools}/tool-calls.js +9 -5
  23. package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -0
  24. package/dist/esm/{tools → activities/chat/tools}/tool-definition.d.ts +14 -14
  25. package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -0
  26. package/dist/esm/activities/chat/tools/zod-converter.d.ts +69 -0
  27. package/dist/esm/activities/chat/tools/zod-converter.js +99 -0
  28. package/dist/esm/activities/chat/tools/zod-converter.js.map +1 -0
  29. package/dist/esm/activities/generateImage/adapter.d.ts +68 -0
  30. package/dist/esm/activities/generateImage/adapter.js +14 -0
  31. package/dist/esm/activities/generateImage/adapter.js.map +1 -0
  32. package/dist/esm/activities/generateImage/index.d.ts +89 -0
  33. package/dist/esm/activities/generateImage/index.js +15 -0
  34. package/dist/esm/activities/generateImage/index.js.map +1 -0
  35. package/dist/esm/activities/generateSpeech/adapter.d.ts +62 -0
  36. package/dist/esm/activities/generateSpeech/adapter.js +14 -0
  37. package/dist/esm/activities/generateSpeech/adapter.js.map +1 -0
  38. package/dist/esm/activities/generateSpeech/index.d.ts +69 -0
  39. package/dist/esm/activities/generateSpeech/index.js +15 -0
  40. package/dist/esm/activities/generateSpeech/index.js.map +1 -0
  41. package/dist/esm/activities/generateTranscription/adapter.d.ts +62 -0
  42. package/dist/esm/activities/generateTranscription/adapter.js +14 -0
  43. package/dist/esm/activities/generateTranscription/adapter.js.map +1 -0
  44. package/dist/esm/activities/generateTranscription/index.d.ts +71 -0
  45. package/dist/esm/activities/generateTranscription/index.js +15 -0
  46. package/dist/esm/activities/generateTranscription/index.js.map +1 -0
  47. package/dist/esm/activities/generateVideo/adapter.d.ts +80 -0
  48. package/dist/esm/activities/generateVideo/adapter.js +14 -0
  49. package/dist/esm/activities/generateVideo/adapter.js.map +1 -0
  50. package/dist/esm/activities/generateVideo/index.d.ts +136 -0
  51. package/dist/esm/activities/generateVideo/index.js +47 -0
  52. package/dist/esm/activities/generateVideo/index.js.map +1 -0
  53. package/dist/esm/activities/index.d.ts +22 -0
  54. package/dist/esm/activities/index.js +34 -0
  55. package/dist/esm/activities/index.js.map +1 -0
  56. package/dist/esm/activities/summarize/adapter.d.ts +74 -0
  57. package/dist/esm/activities/summarize/adapter.js +14 -0
  58. package/dist/esm/activities/summarize/adapter.js.map +1 -0
  59. package/dist/esm/activities/summarize/index.d.ts +100 -0
  60. package/dist/esm/activities/summarize/index.js +90 -0
  61. package/dist/esm/activities/summarize/index.js.map +1 -0
  62. package/dist/esm/event-client.d.ts +4 -45
  63. package/dist/esm/event-client.js +0 -49
  64. package/dist/esm/event-client.js.map +1 -1
  65. package/dist/esm/index.d.ts +16 -14
  66. package/dist/esm/index.js +28 -19
  67. package/dist/esm/stream-to-response.d.ts +95 -0
  68. package/dist/esm/stream-to-response.js +118 -0
  69. package/dist/esm/stream-to-response.js.map +1 -0
  70. package/dist/esm/types.d.ts +347 -129
  71. package/package.json +6 -2
  72. package/src/activities/chat/adapter.ts +150 -0
  73. package/src/{utilities → activities/chat}/agent-loop-strategies.ts +4 -4
  74. package/src/{core/chat.ts → activities/chat/index.ts} +427 -79
  75. package/src/{message-converters.ts → activities/chat/messages.ts} +10 -13
  76. package/src/{stream → activities/chat/stream}/message-updaters.ts +1 -1
  77. package/src/{stream → activities/chat/stream}/processor.ts +2 -5
  78. package/src/{stream → activities/chat/stream}/types.ts +8 -18
  79. package/src/{tools → activities/chat/tools}/tool-calls.ts +36 -11
  80. package/src/{tools → activities/chat/tools}/tool-definition.ts +36 -27
  81. package/src/activities/chat/tools/zod-converter.ts +235 -0
  82. package/src/activities/generateImage/adapter.ts +104 -0
  83. package/src/activities/generateImage/index.ts +162 -0
  84. package/src/activities/generateSpeech/adapter.ts +87 -0
  85. package/src/activities/generateSpeech/index.ts +122 -0
  86. package/src/activities/generateTranscription/adapter.ts +89 -0
  87. package/src/activities/generateTranscription/index.ts +132 -0
  88. package/src/activities/generateVideo/adapter.ts +116 -0
  89. package/src/activities/generateVideo/index.ts +261 -0
  90. package/src/activities/index.ts +164 -0
  91. package/src/activities/summarize/adapter.ts +107 -0
  92. package/src/activities/summarize/index.ts +287 -0
  93. package/src/event-client.ts +5 -101
  94. package/src/index.ts +58 -15
  95. package/src/stream-to-response.ts +237 -0
  96. package/src/types.ts +404 -280
  97. package/dist/esm/base-adapter.d.ts +0 -36
  98. package/dist/esm/base-adapter.js +0 -12
  99. package/dist/esm/base-adapter.js.map +0 -1
  100. package/dist/esm/core/chat-common-options.d.ts +0 -52
  101. package/dist/esm/core/chat.d.ts +0 -30
  102. package/dist/esm/core/chat.js.map +0 -1
  103. package/dist/esm/core/embedding.d.ts +0 -8
  104. package/dist/esm/core/embedding.js +0 -33
  105. package/dist/esm/core/embedding.js.map +0 -1
  106. package/dist/esm/core/summarize.d.ts +0 -9
  107. package/dist/esm/core/summarize.js +0 -36
  108. package/dist/esm/core/summarize.js.map +0 -1
  109. package/dist/esm/message-converters.js.map +0 -1
  110. package/dist/esm/stream/json-parser.js.map +0 -1
  111. package/dist/esm/stream/message-updaters.js.map +0 -1
  112. package/dist/esm/stream/processor.js.map +0 -1
  113. package/dist/esm/stream/strategies.js.map +0 -1
  114. package/dist/esm/tools/tool-calls.js.map +0 -1
  115. package/dist/esm/tools/tool-definition.js.map +0 -1
  116. package/dist/esm/tools/zod-converter.d.ts +0 -30
  117. package/dist/esm/tools/zod-converter.js +0 -36
  118. package/dist/esm/tools/zod-converter.js.map +0 -1
  119. package/dist/esm/utilities/agent-loop-strategies.js.map +0 -1
  120. package/dist/esm/utilities/chat-options.d.ts +0 -6
  121. package/dist/esm/utilities/chat-options.js +0 -7
  122. package/dist/esm/utilities/chat-options.js.map +0 -1
  123. package/dist/esm/utilities/messages.d.ts +0 -30
  124. package/dist/esm/utilities/messages.js +0 -7
  125. package/dist/esm/utilities/messages.js.map +0 -1
  126. package/dist/esm/utilities/stream-to-response.d.ts +0 -48
  127. package/dist/esm/utilities/stream-to-response.js +0 -62
  128. package/dist/esm/utilities/stream-to-response.js.map +0 -1
  129. package/src/base-adapter.ts +0 -86
  130. package/src/core/chat-common-options.ts +0 -55
  131. package/src/core/embedding.ts +0 -54
  132. package/src/core/summarize.ts +0 -56
  133. package/src/tools/zod-converter.ts +0 -85
  134. package/src/utilities/chat-options.ts +0 -35
  135. package/src/utilities/messages.ts +0 -63
  136. package/src/utilities/stream-to-response.ts +0 -116
  137. /package/dist/esm/{utilities → activities/chat}/agent-loop-strategies.js +0 -0
  138. /package/dist/esm/{stream → activities/chat/stream}/index.d.ts +0 -0
  139. /package/dist/esm/{stream → activities/chat/stream}/json-parser.d.ts +0 -0
  140. /package/dist/esm/{stream → activities/chat/stream}/json-parser.js +0 -0
  141. /package/dist/esm/{stream → activities/chat/stream}/message-updaters.js +0 -0
  142. /package/dist/esm/{stream → activities/chat/stream}/strategies.d.ts +0 -0
  143. /package/dist/esm/{stream → activities/chat/stream}/strategies.js +0 -0
  144. /package/dist/esm/{tools → activities/chat/tools}/tool-definition.js +0 -0
  145. /package/src/{stream → activities/chat/stream}/index.ts +0 -0
  146. /package/src/{stream → activities/chat/stream}/json-parser.ts +0 -0
  147. /package/src/{stream → activities/chat/stream}/strategies.ts +0 -0
@@ -0,0 +1,69 @@
1
+ import { SchemaInput } from '../../../types.js';
2
+ /**
3
+ * Options for schema conversion
4
+ */
5
+ export interface ConvertSchemaOptions {
6
+ /**
7
+ * When true, transforms the schema to be compatible with OpenAI's structured output requirements:
8
+ * - All properties are added to the `required` array
9
+ * - Optional fields get null added to their type union
10
+ * - additionalProperties is set to false for all objects
11
+ *
12
+ * @default false
13
+ */
14
+ forStructuredOutput?: boolean;
15
+ }
16
+ /**
17
+ * Converts a schema (Zod or JSONSchema) to JSON Schema format compatible with LLM providers.
18
+ * If the input is already a JSONSchema object, it is returned as-is.
19
+ * If the input is a Zod schema, it is converted to JSON Schema.
20
+ *
21
+ * @param schema - Zod schema or JSONSchema object to convert
22
+ * @param options - Conversion options
23
+ * @returns JSON Schema object that can be sent to LLM providers
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * import { z } from 'zod';
28
+ *
29
+ * // Using Zod schema
30
+ * const zodSchema = z.object({
31
+ * location: z.string().describe('City name'),
32
+ * unit: z.enum(['celsius', 'fahrenheit']).optional()
33
+ * });
34
+ *
35
+ * const jsonSchema = convertZodToJsonSchema(zodSchema);
36
+ * // Returns:
37
+ * // {
38
+ * // type: 'object',
39
+ * // properties: {
40
+ * // location: { type: 'string', description: 'City name' },
41
+ * // unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
42
+ * // },
43
+ * // required: ['location']
44
+ * // }
45
+ *
46
+ * // For OpenAI structured output (all fields required, optional fields nullable)
47
+ * const structuredSchema = convertZodToJsonSchema(zodSchema, { forStructuredOutput: true });
48
+ * // Returns:
49
+ * // {
50
+ * // type: 'object',
51
+ * // properties: {
52
+ * // location: { type: 'string', description: 'City name' },
53
+ * // unit: { type: ['string', 'null'], enum: ['celsius', 'fahrenheit'] }
54
+ * // },
55
+ * // required: ['location', 'unit'],
56
+ * // additionalProperties: false
57
+ * // }
58
+ *
59
+ * // Using JSONSchema directly (passes through unchanged)
60
+ * const rawSchema = {
61
+ * type: 'object',
62
+ * properties: { location: { type: 'string' } },
63
+ * required: ['location']
64
+ * };
65
+ * const result = convertZodToJsonSchema(rawSchema);
66
+ * // Returns the same object
67
+ * ```
68
+ */
69
+ export declare function convertZodToJsonSchema(schema: SchemaInput | undefined, options?: ConvertSchemaOptions): Record<string, any> | undefined;
@@ -0,0 +1,99 @@
1
+ import { toJSONSchema } from "zod";
2
+ function isZodSchema(schema) {
3
+ return typeof schema === "object" && schema !== null && "_zod" in schema && typeof schema._zod === "object";
4
+ }
5
+ function makeStructuredOutputCompatible(schema, originalRequired = []) {
6
+ const result = { ...schema };
7
+ if (result.type === "object" && result.properties) {
8
+ const properties = { ...result.properties };
9
+ const allPropertyNames = Object.keys(properties);
10
+ for (const propName of allPropertyNames) {
11
+ const prop = properties[propName];
12
+ const wasOptional = !originalRequired.includes(propName);
13
+ if (prop.type === "object" && prop.properties) {
14
+ properties[propName] = makeStructuredOutputCompatible(
15
+ prop,
16
+ prop.required || []
17
+ );
18
+ } else if (prop.type === "array" && prop.items) {
19
+ properties[propName] = {
20
+ ...prop,
21
+ items: makeStructuredOutputCompatible(
22
+ prop.items,
23
+ prop.items.required || []
24
+ )
25
+ };
26
+ } else if (wasOptional) {
27
+ if (prop.type && !Array.isArray(prop.type)) {
28
+ properties[propName] = {
29
+ ...prop,
30
+ type: [prop.type, "null"]
31
+ };
32
+ } else if (Array.isArray(prop.type) && !prop.type.includes("null")) {
33
+ properties[propName] = {
34
+ ...prop,
35
+ type: [...prop.type, "null"]
36
+ };
37
+ }
38
+ }
39
+ }
40
+ result.properties = properties;
41
+ result.required = allPropertyNames;
42
+ result.additionalProperties = false;
43
+ }
44
+ if (result.type === "array" && result.items) {
45
+ result.items = makeStructuredOutputCompatible(
46
+ result.items,
47
+ result.items.required || []
48
+ );
49
+ }
50
+ return result;
51
+ }
52
+ function convertZodToJsonSchema(schema, options = {}) {
53
+ if (!schema) return void 0;
54
+ const { forStructuredOutput = false } = options;
55
+ if (!isZodSchema(schema)) {
56
+ if (forStructuredOutput && typeof schema === "object") {
57
+ return makeStructuredOutputCompatible(
58
+ schema,
59
+ schema.required || []
60
+ );
61
+ }
62
+ return schema;
63
+ }
64
+ const jsonSchema = toJSONSchema(schema, {
65
+ target: "openapi-3.0",
66
+ reused: "ref"
67
+ });
68
+ let result = jsonSchema;
69
+ if (typeof result === "object" && "$schema" in result) {
70
+ const { $schema, ...rest } = result;
71
+ result = rest;
72
+ }
73
+ if (typeof result === "object") {
74
+ const isZodObject = typeof schema === "object" && "def" in schema && schema.def.type === "object";
75
+ if (isZodObject && !result.type) {
76
+ result.type = "object";
77
+ }
78
+ if (Object.keys(result).length === 0) {
79
+ result.type = "object";
80
+ }
81
+ if ("properties" in result && !result.type) {
82
+ result.type = "object";
83
+ }
84
+ if (result.type === "object" && !("properties" in result)) {
85
+ result.properties = {};
86
+ }
87
+ if (result.type === "object" && !("required" in result)) {
88
+ result.required = [];
89
+ }
90
+ if (forStructuredOutput) {
91
+ result = makeStructuredOutputCompatible(result, result.required || []);
92
+ }
93
+ }
94
+ return result;
95
+ }
96
+ export {
97
+ convertZodToJsonSchema
98
+ };
99
+ //# sourceMappingURL=zod-converter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod-converter.js","sources":["../../../../../src/activities/chat/tools/zod-converter.ts"],"sourcesContent":["import { toJSONSchema } from 'zod'\nimport type { z } from 'zod'\nimport type { SchemaInput } from '../../../types'\n\n/**\n * Check if a value is a Zod schema by looking for Zod-specific internals.\n * Zod schemas have a `_zod` property that contains metadata.\n */\nfunction isZodSchema(schema: unknown): schema is z.ZodType {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '_zod' in schema &&\n typeof (schema as any)._zod === 'object'\n )\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nfunction makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired: Array<string> = [],\n): Record<string, any> {\n const result = { ...schema }\n\n // Handle object types\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n // Transform each property\n for (const propName of allPropertyNames) {\n const prop = properties[propName]\n const wasOptional = !originalRequired.includes(propName)\n\n // Recursively transform nested objects/arrays\n if (prop.type === 'object' && prop.properties) {\n properties[propName] = makeStructuredOutputCompatible(\n prop,\n prop.required || [],\n )\n } else if (prop.type === 'array' && prop.items) {\n properties[propName] = {\n ...prop,\n items: makeStructuredOutputCompatible(\n prop.items,\n prop.items.required || [],\n ),\n }\n } else if (wasOptional) {\n // Make optional fields nullable by adding null to the type\n if (prop.type && !Array.isArray(prop.type)) {\n properties[propName] = {\n ...prop,\n type: [prop.type, 'null'],\n }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n properties[propName] = {\n ...prop,\n type: [...prop.type, 'null'],\n }\n }\n }\n }\n\n result.properties = properties\n // ALL properties must be required for OpenAI structured output\n result.required = allPropertyNames\n // additionalProperties must be false\n result.additionalProperties = false\n }\n\n // Handle array types with object items\n if (result.type === 'array' && result.items) {\n result.items = makeStructuredOutputCompatible(\n result.items,\n result.items.required || [],\n )\n }\n\n return result\n}\n\n/**\n * Options for schema conversion\n */\nexport interface ConvertSchemaOptions {\n /**\n * When true, transforms the schema to be compatible with OpenAI's structured output requirements:\n * - All properties are added to the `required` array\n * - Optional fields get null added to their type union\n * - additionalProperties is set to false for all objects\n *\n * @default false\n */\n forStructuredOutput?: boolean\n}\n\n/**\n * Converts a schema (Zod or JSONSchema) to JSON Schema format compatible with LLM providers.\n * If the input is already a JSONSchema object, it is returned as-is.\n * If the input is a Zod schema, it is converted to JSON Schema.\n *\n * @param schema - Zod schema or JSONSchema object to convert\n * @param options - Conversion options\n * @returns JSON Schema object that can be sent to LLM providers\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n *\n * // Using Zod schema\n * const zodSchema = z.object({\n * location: z.string().describe('City name'),\n * unit: z.enum(['celsius', 'fahrenheit']).optional()\n * });\n *\n * const jsonSchema = convertZodToJsonSchema(zodSchema);\n * // Returns:\n * // {\n * // type: 'object',\n * // properties: {\n * // location: { type: 'string', description: 'City name' },\n * // unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }\n * // },\n * // required: ['location']\n * // }\n *\n * // For OpenAI structured output (all fields required, optional fields nullable)\n * const structuredSchema = convertZodToJsonSchema(zodSchema, { forStructuredOutput: true });\n * // Returns:\n * // {\n * // type: 'object',\n * // properties: {\n * // location: { type: 'string', description: 'City name' },\n * // unit: { type: ['string', 'null'], enum: ['celsius', 'fahrenheit'] }\n * // },\n * // required: ['location', 'unit'],\n * // additionalProperties: false\n * // }\n *\n * // Using JSONSchema directly (passes through unchanged)\n * const rawSchema = {\n * type: 'object',\n * properties: { location: { type: 'string' } },\n * required: ['location']\n * };\n * const result = convertZodToJsonSchema(rawSchema);\n * // Returns the same object\n * ```\n */\nexport function convertZodToJsonSchema(\n schema: SchemaInput | undefined,\n options: ConvertSchemaOptions = {},\n): Record<string, any> | undefined {\n if (!schema) return undefined\n\n const { forStructuredOutput = false } = options\n\n // If it's not a Zod schema, assume it's already a JSONSchema and pass through\n if (!isZodSchema(schema)) {\n // Still apply structured output transformation if requested\n if (forStructuredOutput && typeof schema === 'object') {\n return makeStructuredOutputCompatible(\n schema,\n (schema as any).required || [],\n )\n }\n return schema\n }\n\n // Use Alcyone Labs fork which is compatible with Zod v4\n const jsonSchema = toJSONSchema(schema, {\n target: 'openapi-3.0',\n reused: 'ref',\n })\n\n // Remove $schema property as it's not needed for LLM providers\n let result = jsonSchema\n if (typeof result === 'object' && '$schema' in result) {\n const { $schema, ...rest } = result\n result = rest\n }\n\n // Ensure object schemas always have type: \"object\"\n // This fixes cases where zod-to-json-schema doesn't set type for empty objects\n if (typeof result === 'object') {\n // Check if the input schema is a ZodObject by inspecting its internal structure\n const isZodObject =\n typeof schema === 'object' &&\n 'def' in schema &&\n schema.def.type === 'object'\n\n // If we know it's a ZodObject but result doesn't have type, set it\n if (isZodObject && !result.type) {\n result.type = 'object'\n }\n\n // If result is completely empty (no keys), it's likely an empty object schema\n if (Object.keys(result).length === 0) {\n result.type = 'object'\n }\n\n // If it has properties (even empty), it should be an object type\n if ('properties' in result && !result.type) {\n result.type = 'object'\n }\n\n // Ensure properties exists for object types (even if empty)\n if (result.type === 'object' && !('properties' in result)) {\n result.properties = {}\n }\n\n // Ensure required exists for object types (even if empty array)\n if (result.type === 'object' && !('required' in result)) {\n result.required = []\n }\n\n // Apply structured output transformation if requested\n if (forStructuredOutput) {\n result = makeStructuredOutputCompatible(result, result.required || [])\n }\n }\n\n return result\n}\n"],"names":[],"mappings":";AAQA,SAAS,YAAY,QAAsC;AACzD,SACE,OAAO,WAAW,YAClB,WAAW,QACX,UAAU,UACV,OAAQ,OAAe,SAAS;AAEpC;AAaA,SAAS,+BACP,QACA,mBAAkC,IACb;AACrB,QAAM,SAAS,EAAE,GAAG,OAAA;AAGpB,MAAI,OAAO,SAAS,YAAY,OAAO,YAAY;AACjD,UAAM,aAAa,EAAE,GAAG,OAAO,WAAA;AAC/B,UAAM,mBAAmB,OAAO,KAAK,UAAU;AAG/C,eAAW,YAAY,kBAAkB;AACvC,YAAM,OAAO,WAAW,QAAQ;AAChC,YAAM,cAAc,CAAC,iBAAiB,SAAS,QAAQ;AAGvD,UAAI,KAAK,SAAS,YAAY,KAAK,YAAY;AAC7C,mBAAW,QAAQ,IAAI;AAAA,UACrB;AAAA,UACA,KAAK,YAAY,CAAA;AAAA,QAAC;AAAA,MAEtB,WAAW,KAAK,SAAS,WAAW,KAAK,OAAO;AAC9C,mBAAW,QAAQ,IAAI;AAAA,UACrB,GAAG;AAAA,UACH,OAAO;AAAA,YACL,KAAK;AAAA,YACL,KAAK,MAAM,YAAY,CAAA;AAAA,UAAC;AAAA,QAC1B;AAAA,MAEJ,WAAW,aAAa;AAEtB,YAAI,KAAK,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI,GAAG;AAC1C,qBAAW,QAAQ,IAAI;AAAA,YACrB,GAAG;AAAA,YACH,MAAM,CAAC,KAAK,MAAM,MAAM;AAAA,UAAA;AAAA,QAE5B,WAAW,MAAM,QAAQ,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,MAAM,GAAG;AAClE,qBAAW,QAAQ,IAAI;AAAA,YACrB,GAAG;AAAA,YACH,MAAM,CAAC,GAAG,KAAK,MAAM,MAAM;AAAA,UAAA;AAAA,QAE/B;AAAA,MACF;AAAA,IACF;AAEA,WAAO,aAAa;AAEpB,WAAO,WAAW;AAElB,WAAO,uBAAuB;AAAA,EAChC;AAGA,MAAI,OAAO,SAAS,WAAW,OAAO,OAAO;AAC3C,WAAO,QAAQ;AAAA,MACb,OAAO;AAAA,MACP,OAAO,MAAM,YAAY,CAAA;AAAA,IAAC;AAAA,EAE9B;AAEA,SAAO;AACT;AAsEO,SAAS,uBACd,QACA,UAAgC,IACC;AACjC,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,EAAE,sBAAsB,MAAA,IAAU;AAGxC,MAAI,CAAC,YAAY,MAAM,GAAG;AAExB,QAAI,uBAAuB,OAAO,WAAW,UAAU;AACrD,aAAO;AAAA,QACL;AAAA,QACC,OAAe,YAAY,CAAA;AAAA,MAAC;AAAA,IAEjC;AACA,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,aAAa,QAAQ;AAAA,IACtC,QAAQ;AAAA,IACR,QAAQ;AAAA,EAAA,CACT;AAGD,MAAI,SAAS;AACb,MAAI,OAAO,WAAW,YAAY,aAAa,QAAQ;AACrD,UAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAC7B,aAAS;AAAA,EACX;AAIA,MAAI,OAAO,WAAW,UAAU;AAE9B,UAAM,cACJ,OAAO,WAAW,YAClB,SAAS,UACT,OAAO,IAAI,SAAS;AAGtB,QAAI,eAAe,CAAC,OAAO,MAAM;AAC/B,aAAO,OAAO;AAAA,IAChB;AAGA,QAAI,OAAO,KAAK,MAAM,EAAE,WAAW,GAAG;AACpC,aAAO,OAAO;AAAA,IAChB;AAGA,QAAI,gBAAgB,UAAU,CAAC,OAAO,MAAM;AAC1C,aAAO,OAAO;AAAA,IAChB;AAGA,QAAI,OAAO,SAAS,YAAY,EAAE,gBAAgB,SAAS;AACzD,aAAO,aAAa,CAAA;AAAA,IACtB;AAGA,QAAI,OAAO,SAAS,YAAY,EAAE,cAAc,SAAS;AACvD,aAAO,WAAW,CAAA;AAAA,IACpB;AAGA,QAAI,qBAAqB;AACvB,eAAS,+BAA+B,QAAQ,OAAO,YAAY,CAAA,CAAE;AAAA,IACvE;AAAA,EACF;AAEA,SAAO;AACT;"}
@@ -0,0 +1,68 @@
1
+ import { ImageGenerationOptions, ImageGenerationResult } from '../../types.js';
2
+ /**
3
+ * Configuration for image adapter instances
4
+ */
5
+ export interface ImageAdapterConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ maxRetries?: number;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * Image adapter interface with pre-resolved generics.
14
+ *
15
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
16
+ * All type resolution happens at the provider call site, not in this interface.
17
+ *
18
+ * Generic parameters:
19
+ * - TModel: The specific model name (e.g., 'dall-e-3')
20
+ * - TProviderOptions: Base provider-specific options (already resolved)
21
+ * - TModelProviderOptionsByName: Map from model name to its specific provider options
22
+ * - TModelSizeByName: Map from model name to its supported sizes
23
+ */
24
+ export interface ImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string> = Record<string, string>> {
25
+ /** Discriminator for adapter kind - used by generate() to determine API shape */
26
+ readonly kind: 'image';
27
+ /** Adapter name identifier */
28
+ readonly name: string;
29
+ /** The model this adapter is configured for */
30
+ readonly model: TModel;
31
+ /**
32
+ * @internal Type-only properties for inference. Not assigned at runtime.
33
+ */
34
+ '~types': {
35
+ providerOptions: TProviderOptions;
36
+ modelProviderOptionsByName: TModelProviderOptionsByName;
37
+ modelSizeByName: TModelSizeByName;
38
+ };
39
+ /**
40
+ * Generate images from a prompt
41
+ */
42
+ generateImages: (options: ImageGenerationOptions<TProviderOptions>) => Promise<ImageGenerationResult>;
43
+ }
44
+ /**
45
+ * An ImageAdapter with any/unknown type parameters.
46
+ * Useful as a constraint in generic functions and interfaces.
47
+ */
48
+ export type AnyImageAdapter = ImageAdapter<any, any, any, any>;
49
+ /**
50
+ * Abstract base class for image generation adapters.
51
+ * Extend this class to implement an image adapter for a specific provider.
52
+ *
53
+ * Generic parameters match ImageAdapter - all pre-resolved by the provider function.
54
+ */
55
+ export declare abstract class BaseImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string> = Record<string, string>> implements ImageAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName> {
56
+ readonly kind: "image";
57
+ abstract readonly name: string;
58
+ readonly model: TModel;
59
+ '~types': {
60
+ providerOptions: TProviderOptions;
61
+ modelProviderOptionsByName: TModelProviderOptionsByName;
62
+ modelSizeByName: TModelSizeByName;
63
+ };
64
+ protected config: ImageAdapterConfig;
65
+ constructor(config: ImageAdapterConfig | undefined, model: TModel);
66
+ abstract generateImages(options: ImageGenerationOptions<TProviderOptions>): Promise<ImageGenerationResult>;
67
+ protected generateId(): string;
68
+ }
@@ -0,0 +1,14 @@
1
+ class BaseImageAdapter {
2
+ constructor(config = {}, model) {
3
+ this.kind = "image";
4
+ this.config = config;
5
+ this.model = model;
6
+ }
7
+ generateId() {
8
+ return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
9
+ }
10
+ }
11
+ export {
12
+ BaseImageAdapter
13
+ };
14
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type { ImageGenerationOptions, ImageGenerationResult } from '../../types'\n\n/**\n * Configuration for image adapter instances\n */\nexport interface ImageAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Image adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'dall-e-3')\n * - TProviderOptions: Base provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n */\nexport interface ImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string> = Record<string, string>,\n> {\n /** Discriminator for adapter kind - used by generate() to determine API shape */\n readonly kind: 'image'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n }\n\n /**\n * Generate images from a prompt\n */\n generateImages: (\n options: ImageGenerationOptions<TProviderOptions>,\n ) => Promise<ImageGenerationResult>\n}\n\n/**\n * An ImageAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyImageAdapter = ImageAdapter<any, any, any, any>\n\n/**\n * Abstract base class for image generation adapters.\n * Extend this class to implement an image adapter for a specific provider.\n *\n * Generic parameters match ImageAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string> = Record<string, string>,\n> implements ImageAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName\n> {\n readonly kind = 'image' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n }\n\n protected config: ImageAdapterConfig\n\n constructor(config: ImageAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract generateImages(\n options: ImageGenerationOptions<TProviderOptions>,\n ): Promise<ImageGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AAmEO,MAAe,iBAUpB;AAAA,EAcA,YAAY,SAA6B,CAAA,GAAI,OAAe;AAb5D,SAAS,OAAO;AAcd,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA,EAMU,aAAqB;AAC7B,WAAO,GAAG,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC;AAAA,EAC9E;AACF;"}
@@ -0,0 +1,89 @@
1
+ import { ImageAdapter } from './adapter.js';
2
+ import { ImageGenerationResult } from '../../types.js';
3
+ /** The adapter kind this activity handles */
4
+ export declare const kind: "image";
5
+ /**
6
+ * Extract model-specific provider options from an ImageAdapter via ~types.
7
+ * If the model has specific options defined in ModelProviderOptions (and not just via index signature),
8
+ * use those; otherwise fall back to base provider options.
9
+ */
10
+ export type ImageProviderOptionsForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any> ? string extends keyof ModelOptions ? BaseOptions : TModel extends keyof ModelOptions ? ModelOptions[TModel] : BaseOptions : object;
11
+ /**
12
+ * Extract model-specific size options from an ImageAdapter via ~types.
13
+ * If the model has specific sizes defined, use those; otherwise fall back to string.
14
+ */
15
+ export type ImageSizeForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, any, any, infer SizeByName> ? string extends keyof SizeByName ? string : TModel extends keyof SizeByName ? SizeByName[TModel] : string : string;
16
+ /**
17
+ * Options for the image activity.
18
+ * The model is extracted from the adapter's model property.
19
+ *
20
+ * @template TAdapter - The image adapter type
21
+ */
22
+ export interface ImageActivityOptions<TAdapter extends ImageAdapter<string, object, any, any>> {
23
+ /** The image adapter to use (must be created with a model) */
24
+ adapter: TAdapter & {
25
+ kind: typeof kind;
26
+ };
27
+ /** Text description of the desired image(s) */
28
+ prompt: string;
29
+ /** Number of images to generate (default: 1) */
30
+ numberOfImages?: number;
31
+ /** Image size in WIDTHxHEIGHT format (e.g., "1024x1024") */
32
+ size?: ImageSizeForModel<TAdapter, TAdapter['model']>;
33
+ /** Provider-specific options for image generation */
34
+ modelOptions?: ImageProviderOptionsForModel<TAdapter, TAdapter['model']>;
35
+ }
36
+ /** Result type for the image activity */
37
+ export type ImageActivityResult = Promise<ImageGenerationResult>;
38
+ /**
39
+ * Image activity - generates images from text prompts.
40
+ *
41
+ * Uses AI image generation models to create images based on natural language descriptions.
42
+ *
43
+ * @example Generate a single image
44
+ * ```ts
45
+ * import { generateImage } from '@tanstack/ai'
46
+ * import { openaiImage } from '@tanstack/ai-openai'
47
+ *
48
+ * const result = await generateImage({
49
+ * adapter: openaiImage('dall-e-3'),
50
+ * prompt: 'A serene mountain landscape at sunset'
51
+ * })
52
+ *
53
+ * console.log(result.images[0].url)
54
+ * ```
55
+ *
56
+ * @example Generate multiple images
57
+ * ```ts
58
+ * const result = await generateImage({
59
+ * adapter: openaiImage('dall-e-2'),
60
+ * prompt: 'A cute robot mascot',
61
+ * numberOfImages: 4,
62
+ * size: '512x512'
63
+ * })
64
+ *
65
+ * result.images.forEach((image, i) => {
66
+ * console.log(`Image ${i + 1}: ${image.url}`)
67
+ * })
68
+ * ```
69
+ *
70
+ * @example With provider-specific options
71
+ * ```ts
72
+ * const result = await generateImage({
73
+ * adapter: openaiImage('dall-e-3'),
74
+ * prompt: 'A professional headshot photo',
75
+ * size: '1024x1024',
76
+ * modelOptions: {
77
+ * quality: 'hd',
78
+ * style: 'natural'
79
+ * }
80
+ * })
81
+ * ```
82
+ */
83
+ export declare function generateImage<TAdapter extends ImageAdapter<string, object, any, any>>(options: ImageActivityOptions<TAdapter>): ImageActivityResult;
84
+ /**
85
+ * Create typed options for the generateImage() function without executing.
86
+ */
87
+ export declare function createImageOptions<TAdapter extends ImageAdapter<string, object, any, any>>(options: ImageActivityOptions<TAdapter>): ImageActivityOptions<TAdapter>;
88
+ export type { ImageAdapter, ImageAdapterConfig, AnyImageAdapter, } from './adapter.js';
89
+ export { BaseImageAdapter } from './adapter.js';
@@ -0,0 +1,15 @@
1
+ const kind = "image";
2
+ async function generateImage(options) {
3
+ const { adapter, ...rest } = options;
4
+ const model = adapter.model;
5
+ return adapter.generateImages({ ...rest, model });
6
+ }
7
+ function createImageOptions(options) {
8
+ return options;
9
+ }
10
+ export {
11
+ createImageOptions,
12
+ generateImage,
13
+ kind
14
+ };
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport type { ImageAdapter } from './adapter'\nimport type { ImageGenerationResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n */\nexport interface ImageActivityOptions<\n TAdapter extends ImageAdapter<string, object, any, any>,\n> {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** Text description of the desired image(s) */\n prompt: string\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /** Provider-specific options for image generation */\n modelOptions?: ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/** Result type for the image activity */\nexport type ImageActivityResult = Promise<ImageGenerationResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport async function generateImage<\n TAdapter extends ImageAdapter<string, object, any, any>,\n>(options: ImageActivityOptions<TAdapter>): ImageActivityResult {\n const { adapter, ...rest } = options\n const model = adapter.model\n\n return adapter.generateImages({ ...rest, model })\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, object, any, any>,\n>(options: ImageActivityOptions<TAdapter>): ImageActivityOptions<TAdapter> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"names":[],"mappings":"AAeO,MAAM,OAAO;AAsHpB,eAAsB,cAEpB,SAA8D;AAC9D,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAC7B,QAAM,QAAQ,QAAQ;AAEtB,SAAO,QAAQ,eAAe,EAAE,GAAG,MAAM,OAAO;AAClD;AASO,SAAS,mBAEd,SAAyE;AACzE,SAAO;AACT;"}
@@ -0,0 +1,62 @@
1
+ import { TTSOptions, TTSResult } from '../../types.js';
2
+ /**
3
+ * Configuration for TTS adapter instances
4
+ */
5
+ export interface TTSAdapterConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ maxRetries?: number;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * TTS adapter interface with pre-resolved generics.
14
+ *
15
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
16
+ * All type resolution happens at the provider call site, not in this interface.
17
+ *
18
+ * Generic parameters:
19
+ * - TModel: The specific model name (e.g., 'tts-1')
20
+ * - TProviderOptions: Provider-specific options (already resolved)
21
+ */
22
+ export interface TTSAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> {
23
+ /** Discriminator for adapter kind - used to determine API shape */
24
+ readonly kind: 'tts';
25
+ /** Adapter name identifier */
26
+ readonly name: string;
27
+ /** The model this adapter is configured for */
28
+ readonly model: TModel;
29
+ /**
30
+ * @internal Type-only properties for inference. Not assigned at runtime.
31
+ */
32
+ '~types': {
33
+ providerOptions: TProviderOptions;
34
+ };
35
+ /**
36
+ * Generate speech from text
37
+ */
38
+ generateSpeech: (options: TTSOptions<TProviderOptions>) => Promise<TTSResult>;
39
+ }
40
+ /**
41
+ * A TTSAdapter with any/unknown type parameters.
42
+ * Useful as a constraint in generic functions and interfaces.
43
+ */
44
+ export type AnyTTSAdapter = TTSAdapter<any, any>;
45
+ /**
46
+ * Abstract base class for text-to-speech adapters.
47
+ * Extend this class to implement a TTS adapter for a specific provider.
48
+ *
49
+ * Generic parameters match TTSAdapter - all pre-resolved by the provider function.
50
+ */
51
+ export declare abstract class BaseTTSAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> implements TTSAdapter<TModel, TProviderOptions> {
52
+ readonly kind: "tts";
53
+ abstract readonly name: string;
54
+ readonly model: TModel;
55
+ '~types': {
56
+ providerOptions: TProviderOptions;
57
+ };
58
+ protected config: TTSAdapterConfig;
59
+ constructor(config: TTSAdapterConfig | undefined, model: TModel);
60
+ abstract generateSpeech(options: TTSOptions<TProviderOptions>): Promise<TTSResult>;
61
+ protected generateId(): string;
62
+ }
@@ -0,0 +1,14 @@
1
+ class BaseTTSAdapter {
2
+ constructor(config = {}, model) {
3
+ this.kind = "tts";
4
+ this.config = config;
5
+ this.model = model;
6
+ }
7
+ generateId() {
8
+ return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
9
+ }
10
+ }
11
+ export {
12
+ BaseTTSAdapter
13
+ };
14
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateSpeech/adapter.ts"],"sourcesContent":["import type { TTSOptions, TTSResult } from '../../types'\n\n/**\n * Configuration for TTS adapter instances\n */\nexport interface TTSAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * TTS adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'tts-1')\n * - TProviderOptions: Provider-specific options (already resolved)\n */\nexport interface TTSAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'tts'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n }\n\n /**\n * Generate speech from text\n */\n generateSpeech: (options: TTSOptions<TProviderOptions>) => Promise<TTSResult>\n}\n\n/**\n * A TTSAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyTTSAdapter = TTSAdapter<any, any>\n\n/**\n * Abstract base class for text-to-speech adapters.\n * Extend this class to implement a TTS adapter for a specific provider.\n *\n * Generic parameters match TTSAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseTTSAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n> implements TTSAdapter<TModel, TProviderOptions> {\n readonly kind = 'tts' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n }\n\n protected config: TTSAdapterConfig\n\n constructor(config: TTSAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract generateSpeech(\n options: TTSOptions<TProviderOptions>,\n ): Promise<TTSResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AA2DO,MAAe,eAG4B;AAAA,EAYhD,YAAY,SAA2B,CAAA,GAAI,OAAe;AAX1D,SAAS,OAAO;AAYd,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA,EAMU,aAAqB;AAC7B,WAAO,GAAG,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC;AAAA,EAC9E;AACF;"}
@@ -0,0 +1,69 @@
1
+ import { TTSAdapter } from './adapter.js';
2
+ import { TTSResult } from '../../types.js';
3
+ /** The adapter kind this activity handles */
4
+ export declare const kind: "tts";
5
+ /**
6
+ * Extract provider options from a TTSAdapter via ~types.
7
+ */
8
+ export type TTSProviderOptions<TAdapter> = TAdapter extends TTSAdapter<any, any> ? TAdapter['~types']['providerOptions'] : object;
9
+ /**
10
+ * Options for the TTS activity.
11
+ * The model is extracted from the adapter's model property.
12
+ *
13
+ * @template TAdapter - The TTS adapter type
14
+ */
15
+ export interface TTSActivityOptions<TAdapter extends TTSAdapter<string, object>> {
16
+ /** The TTS adapter to use (must be created with a model) */
17
+ adapter: TAdapter & {
18
+ kind: typeof kind;
19
+ };
20
+ /** The text to convert to speech */
21
+ text: string;
22
+ /** The voice to use for generation */
23
+ voice?: string;
24
+ /** The output audio format */
25
+ format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';
26
+ /** The speed of the generated audio (0.25 to 4.0) */
27
+ speed?: number;
28
+ /** Provider-specific options for TTS generation */
29
+ modelOptions?: TTSProviderOptions<TAdapter>;
30
+ }
31
+ /** Result type for the TTS activity */
32
+ export type TTSActivityResult = Promise<TTSResult>;
33
+ /**
34
+ * TTS activity - generates speech from text.
35
+ *
36
+ * Uses AI text-to-speech models to create audio from natural language text.
37
+ *
38
+ * @example Generate speech from text
39
+ * ```ts
40
+ * import { generateSpeech } from '@tanstack/ai'
41
+ * import { openaiTTS } from '@tanstack/ai-openai'
42
+ *
43
+ * const result = await generateSpeech({
44
+ * adapter: openaiTTS('tts-1-hd'),
45
+ * text: 'Hello, welcome to TanStack AI!',
46
+ * voice: 'nova'
47
+ * })
48
+ *
49
+ * console.log(result.audio) // base64-encoded audio
50
+ * ```
51
+ *
52
+ * @example With format and speed options
53
+ * ```ts
54
+ * const result = await generateSpeech({
55
+ * adapter: openaiTTS('tts-1'),
56
+ * text: 'This is slower speech.',
57
+ * voice: 'alloy',
58
+ * format: 'wav',
59
+ * speed: 0.8
60
+ * })
61
+ * ```
62
+ */
63
+ export declare function generateSpeech<TAdapter extends TTSAdapter<string, object>>(options: TTSActivityOptions<TAdapter>): TTSActivityResult;
64
+ /**
65
+ * Create typed options for the generateSpeech() function without executing.
66
+ */
67
+ export declare function createSpeechOptions<TAdapter extends TTSAdapter<string, object>>(options: TTSActivityOptions<TAdapter>): TTSActivityOptions<TAdapter>;
68
+ export type { TTSAdapter, TTSAdapterConfig, AnyTTSAdapter } from './adapter.js';
69
+ export { BaseTTSAdapter } from './adapter.js';
@@ -0,0 +1,15 @@
1
+ const kind = "tts";
2
+ async function generateSpeech(options) {
3
+ const { adapter, ...rest } = options;
4
+ const model = adapter.model;
5
+ return adapter.generateSpeech({ ...rest, model });
6
+ }
7
+ function createSpeechOptions(options) {
8
+ return options;
9
+ }
10
+ export {
11
+ createSpeechOptions,
12
+ generateSpeech,
13
+ kind
14
+ };
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/activities/generateSpeech/index.ts"],"sourcesContent":["/**\n * TTS Activity\n *\n * Generates speech audio from text using text-to-speech models.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport type { TTSAdapter } from './adapter'\nimport type { TTSResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'tts' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a TTSAdapter via ~types.\n */\nexport type TTSProviderOptions<TAdapter> =\n TAdapter extends TTSAdapter<any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the TTS activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The TTS adapter type\n */\nexport interface TTSActivityOptions<\n TAdapter extends TTSAdapter<string, object>,\n> {\n /** The TTS adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** The text to convert to speech */\n text: string\n /** The voice to use for generation */\n voice?: string\n /** The output audio format */\n format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'\n /** The speed of the generated audio (0.25 to 4.0) */\n speed?: number\n /** Provider-specific options for TTS generation */\n modelOptions?: TTSProviderOptions<TAdapter>\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/** Result type for the TTS activity */\nexport type TTSActivityResult = Promise<TTSResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * TTS activity - generates speech from text.\n *\n * Uses AI text-to-speech models to create audio from natural language text.\n *\n * @example Generate speech from text\n * ```ts\n * import { generateSpeech } from '@tanstack/ai'\n * import { openaiTTS } from '@tanstack/ai-openai'\n *\n * const result = await generateSpeech({\n * adapter: openaiTTS('tts-1-hd'),\n * text: 'Hello, welcome to TanStack AI!',\n * voice: 'nova'\n * })\n *\n * console.log(result.audio) // base64-encoded audio\n * ```\n *\n * @example With format and speed options\n * ```ts\n * const result = await generateSpeech({\n * adapter: openaiTTS('tts-1'),\n * text: 'This is slower speech.',\n * voice: 'alloy',\n * format: 'wav',\n * speed: 0.8\n * })\n * ```\n */\nexport async function generateSpeech<\n TAdapter extends TTSAdapter<string, object>,\n>(options: TTSActivityOptions<TAdapter>): TTSActivityResult {\n const { adapter, ...rest } = options\n const model = adapter.model\n\n return adapter.generateSpeech({ ...rest, model })\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateSpeech() function without executing.\n */\nexport function createSpeechOptions<\n TAdapter extends TTSAdapter<string, object>,\n>(options: TTSActivityOptions<TAdapter>): TTSActivityOptions<TAdapter> {\n return options\n}\n\n// Re-export adapter types\nexport type { TTSAdapter, TTSAdapterConfig, AnyTTSAdapter } from './adapter'\nexport { BaseTTSAdapter } from './adapter'\n"],"names":[],"mappings":"AAeO,MAAM,OAAO;AAkFpB,eAAsB,eAEpB,SAA0D;AAC1D,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAC7B,QAAM,QAAQ,QAAQ;AAEtB,SAAO,QAAQ,eAAe,EAAE,GAAG,MAAM,OAAO;AAClD;AASO,SAAS,oBAEd,SAAqE;AACrE,SAAO;AACT;"}
@@ -0,0 +1,62 @@
1
+ import { TranscriptionOptions, TranscriptionResult } from '../../types.js';
2
+ /**
3
+ * Configuration for transcription adapter instances
4
+ */
5
+ export interface TranscriptionAdapterConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ maxRetries?: number;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * Transcription adapter interface with pre-resolved generics.
14
+ *
15
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
16
+ * All type resolution happens at the provider call site, not in this interface.
17
+ *
18
+ * Generic parameters:
19
+ * - TModel: The specific model name (e.g., 'whisper-1')
20
+ * - TProviderOptions: Provider-specific options (already resolved)
21
+ */
22
+ export interface TranscriptionAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> {
23
+ /** Discriminator for adapter kind - used to determine API shape */
24
+ readonly kind: 'transcription';
25
+ /** Adapter name identifier */
26
+ readonly name: string;
27
+ /** The model this adapter is configured for */
28
+ readonly model: TModel;
29
+ /**
30
+ * @internal Type-only properties for inference. Not assigned at runtime.
31
+ */
32
+ '~types': {
33
+ providerOptions: TProviderOptions;
34
+ };
35
+ /**
36
+ * Transcribe audio to text
37
+ */
38
+ transcribe: (options: TranscriptionOptions<TProviderOptions>) => Promise<TranscriptionResult>;
39
+ }
40
+ /**
41
+ * A TranscriptionAdapter with any/unknown type parameters.
42
+ * Useful as a constraint in generic functions and interfaces.
43
+ */
44
+ export type AnyTranscriptionAdapter = TranscriptionAdapter<any, any>;
45
+ /**
46
+ * Abstract base class for audio transcription adapters.
47
+ * Extend this class to implement a transcription adapter for a specific provider.
48
+ *
49
+ * Generic parameters match TranscriptionAdapter - all pre-resolved by the provider function.
50
+ */
51
+ export declare abstract class BaseTranscriptionAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> implements TranscriptionAdapter<TModel, TProviderOptions> {
52
+ readonly kind: "transcription";
53
+ abstract readonly name: string;
54
+ readonly model: TModel;
55
+ '~types': {
56
+ providerOptions: TProviderOptions;
57
+ };
58
+ protected config: TranscriptionAdapterConfig;
59
+ constructor(config: TranscriptionAdapterConfig | undefined, model: TModel);
60
+ abstract transcribe(options: TranscriptionOptions<TProviderOptions>): Promise<TranscriptionResult>;
61
+ protected generateId(): string;
62
+ }