Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): create generated object utility (#3023)

teo8498a7b3c5d7
diff --git a/js/app/packages/core/client/structuredOutput.ts b/js/app/packages/core/client/structuredOutput.ts
deleted file mode 100644
index 6e4136dfcc..0000000000
--- a/js/app/packages/core/client/structuredOutput.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { isErr } from '@core/util/maybeResult';
-import { dcsCompletion } from '@service-cognition/client';
-
-type StructuredOutputSchema = {
- type: string;
- properties: Record<string, any>;
- required: string[];
- additionalProperties: boolean;
-};
-
-/**
- * Sends a structured output completion to the dcs
- *
- * @type T - The type of the completion
- * @param prompt - The prompt to send to the dcs
- * @param schema - A valid openai structured output schema
- * @param schema_name - The name of the schema (should be formatted using snake case)
- *
- * @returns The completion response
- *
- * @example
- * ```tsx
- * const completion = await structuredOutputCompletion<string>(
- * 'Hello world',
- * {
- * type: 'object',
- * properties: {
- * greeting: { type: 'string' },
- * name: { type: 'string' },
- * },
- * required: ['greeting', 'name'],
- * },
- * 'greeting_and_name'
- * );
- *
- * return <div>{completion}</div>
- * ```
- */
-export async function structuredOutputCompletion<T>(
- prompt: string,
- schema: StructuredOutputSchema,
- schema_name: string
-): Promise<T | undefined> {
- const response = await dcsCompletion({
- model: 'gpt-4o-mini',
- messages: [{ role: 'user', content: prompt }],
- response_format: {
- type: 'json_schema',
- json_schema: {
- name: schema_name,
- strict: true,
- schema,
- },
- },
- });
-
- if (isErr(response)) {
- console.error('Error in structured output completion');
- return;
- }
-
- const content = response[1].choices[0]?.message?.content;
- if (!content) {
- console.error('No completion in structured output completion');
- return undefined;
- }
-
- return JSON.parse(content) as T;
-}
diff --git a/js/app/packages/queries/ai/createAIObject.ts b/js/app/packages/queries/ai/createAIObject.ts
new file mode 100644
index 0000000000..f6315d61b8
--- /dev/null
+++ b/js/app/packages/queries/ai/createAIObject.ts
@@ -0,0 +1,319 @@
+import { isErr } from '@core/util/maybeResult';
+import { dcsCompletion } from '@service-cognition/client';
+import {
+ type SolidMutationOptions,
+ type UseMutationResult,
+ useMutation,
+} from '@tanstack/solid-query';
+import type OpenAI from 'openai';
+import { z } from 'zod';
+
+type ChatMessage = OpenAI.ChatCompletionMessageParam;
+type ChatModel = OpenAI.ChatModel | (string & {});
+type JsonObject = Record<string, unknown>;
+
+export type AIObjectSchemaViolation = {
+ path: string;
+ message: string;
+};
+
+export class AIObjectSchemaError extends Error {
+ constructor(public readonly violations: readonly AIObjectSchemaViolation[]) {
+ super(
+ [
+ 'Zod schema is not compatible with OpenAI strict structured outputs.',
+ ...violations.map((violation) => `- ${violation.message}`),
+ ].join('\n')
+ );
+ this.name = 'AIObjectSchemaError';
+ }
+}
+
+export class AIObjectParseError extends Error {
+ constructor(
+ public readonly content: string,
+ public readonly parseError: unknown
+ ) {
+ super('AI object completion returned invalid JSON');
+ this.name = 'AIObjectParseError';
+ }
+}
+
+export class AIObjectValidationError<T> extends Error {
+ constructor(public readonly zodError: z.ZodError<T>) {
+ super(zodError.message);
+ this.name = 'AIObjectValidationError';
+ }
+}
+
+export type CreateAIObjectOptions<
+ Schema extends z.ZodType,
+ Variables = string,
+ OnMutateResult = unknown,
+> = Omit<
+ SolidMutationOptions<z.infer<Schema>, Error, Variables, OnMutateResult>,
+ 'mutationFn'
+> & {
+ /**
+ * Zod v4 schema used for OpenAI structured outputs and final validation.
+ *
+ * OpenAI `strict: true` requires every object property to be required. Use
+ * `.nullable()` for values the model may omit semantically; `.optional()` is
+ * rejected before sending the request.
+ */
+ schema: Schema;
+ /** Name sent to OpenAI for the json_schema response format. */
+ schemaName?: string;
+ /** Model for the DCS `/chat/completions` proxy. */
+ model?: ChatModel;
+ /** Optional system message prepended to generated messages. */
+ system?: string;
+ /** Static prompt or prompt factory. Defaults to the submitted variables. */
+ prompt?: string | ((variables: Variables) => string);
+ /** Static messages or message factory. Overrides `system` and `prompt`. */
+ messages?: ChatMessage[] | ((variables: Variables) => ChatMessage[]);
+ temperature?: number;
+ maxTokens?: number;
+};
+
+export type CreateAIObjectResult<
+ Schema extends z.ZodType,
+ Variables = string,
+ OnMutateResult = unknown,
+> = UseMutationResult<z.infer<Schema>, Error, Variables, OnMutateResult>;
+
+function defaultSchemaName(schema: z.ZodType): string {
+ return (
+ schema.description
+ ?.toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^_+|_+$/g, '') || 'ai_object'
+ );
+}
+
+function isJsonObject(value: unknown): value is JsonObject {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function formatJsonPath(path: readonly string[]): string {
+ if (path.length === 0) {
+ return '$';
+ }
+
+ return `$${path.map((part) => `.${part}`).join('')}`;
+}
+
+function collectStrictSchemaViolations(
+ schema: unknown,
+ path: readonly string[] = []
+): AIObjectSchemaViolation[] {
+ if (!isJsonObject(schema)) {
+ return [];
+ }
+
+ const violations: AIObjectSchemaViolation[] = [];
+ const properties = schema.properties;
+ const type = schema.type;
+ const isObjectSchema =
+ type === 'object' || (Array.isArray(type) && type.includes('object'));
+
+ if (isObjectSchema) {
+ if (schema.additionalProperties !== false) {
+ violations.push({
+ path: formatJsonPath(path),
+ message: `${formatJsonPath(path)} must set additionalProperties: false.`,
+ });
+ }
+
+ if (isJsonObject(properties)) {
+ const required = schema.required;
+ const requiredProperties = new Set(
+ Array.isArray(required)
+ ? required.filter(
+ (property): property is string => typeof property === 'string'
+ )
+ : []
+ );
+
+ for (const property of Object.keys(properties)) {
+ if (!requiredProperties.has(property)) {
+ violations.push({
+ path: formatJsonPath([...path, property]),
+ message: `${formatJsonPath([
+ ...path,
+ property,
+ ])} is optional. OpenAI strict structured outputs require every object property to be required; use .nullable() instead of .optional().`,
+ });
+ }
+ }
+ }
+ }
+
+ if (isJsonObject(properties)) {
+ for (const [property, propertySchema] of Object.entries(properties)) {
+ violations.push(
+ ...collectStrictSchemaViolations(propertySchema, [...path, property])
+ );
+ }
+ }
+
+ const items = schema.items;
+ if (isJsonObject(items)) {
+ violations.push(...collectStrictSchemaViolations(items, [...path, '[]']));
+ } else if (Array.isArray(items)) {
+ for (const [index, item] of items.entries()) {
+ violations.push(
+ ...collectStrictSchemaViolations(item, [...path, `[${index}]`])
+ );
+ }
+ }
+
+ for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
+ const schemas = schema[key];
+ if (!Array.isArray(schemas)) {
+ continue;
+ }
+
+ for (const childSchema of schemas) {
+ violations.push(...collectStrictSchemaViolations(childSchema, path));
+ }
+ }
+
+ for (const key of ['$defs', 'definitions'] as const) {
+ const definitions = schema[key];
+ if (!isJsonObject(definitions)) {
+ continue;
+ }
+
+ for (const [name, definition] of Object.entries(definitions)) {
+ violations.push(
+ ...collectStrictSchemaViolations(definition, [...path, key, name])
+ );
+ }
+ }
+
+ return violations;
+}
+
+function toJsonSchema(schema: z.ZodType) {
+ const jsonSchema = z.toJSONSchema(schema, {
+ target: 'draft-07',
+ unrepresentable: 'throw',
+ cycles: 'throw',
+ reused: 'inline',
+ });
+
+ const violations = collectStrictSchemaViolations(jsonSchema);
+ if (violations.length > 0) {
+ throw new AIObjectSchemaError(violations);
+ }
+
+ return jsonSchema;
+}
+
+function stringifyVariables(variables: unknown): string {
+ return typeof variables === 'string' ? variables : JSON.stringify(variables);
+}
+
+function buildMessages<Variables>(
+ options: CreateAIObjectOptions<z.ZodType, Variables>,
+ variables: Variables
+): ChatMessage[] {
+ if (typeof options.messages === 'function') {
+ return options.messages(variables);
+ }
+
+ if (options.messages) {
+ return options.messages;
+ }
+
+ const prompt =
+ typeof options.prompt === 'function'
+ ? options.prompt(variables)
+ : (options.prompt ?? stringifyVariables(variables));
+
+ const messages: ChatMessage[] = [];
+ if (options.system) {
+ messages.push({ role: 'system', content: options.system });
+ }
+ messages.push({ role: 'user', content: prompt });
+ return messages;
+}
+
+async function generateAIObject<Schema extends z.ZodType, Variables>(
+ options: CreateAIObjectOptions<Schema, Variables>,
+ variables: Variables
+): Promise<z.infer<Schema>> {
+ const response = await dcsCompletion({
+ model: options.model ?? 'gpt-4o-mini',
+ messages: buildMessages(options, variables),
+ ...(options.temperature === undefined
+ ? {}
+ : { temperature: options.temperature }),
+ ...(options.maxTokens === undefined
+ ? {}
+ : { max_tokens: options.maxTokens }),
+ response_format: {
+ type: 'json_schema',
+ json_schema: {
+ name: options.schemaName ?? defaultSchemaName(options.schema),
+ strict: true,
+ schema: toJsonSchema(options.schema),
+ },
+ },
+ });
+
+ if (isErr(response)) {
+ throw new Error(response[0].map((error) => error.message).join(', '));
+ }
+
+ const content = response[1].choices[0]?.message?.content;
+ if (!content) {
+ throw new Error('AI object completion returned no content');
+ }
+
+ let parsedJson: unknown;
+ try {
+ parsedJson = JSON.parse(content);
+ } catch (error) {
+ throw new AIObjectParseError(content, error);
+ }
+
+ const parsedObject = options.schema.safeParse(parsedJson);
+ if (!parsedObject.success) {
+ throw new AIObjectValidationError(parsedObject.error);
+ }
+
+ return parsedObject.data;
+}
+
+/**
+ * TanStack mutation for DCS structured object generation.
+ *
+ * This behaves like `useMutation`: pass standard mutation options (`onSuccess`,
+ * `onError`, `onSettled`, `retry`, etc.) and call `mutate` or `mutateAsync`.
+ *
+ * @example
+ * ```tsx
+ * const mutation = createAIObject({
+ * schema: z.object({ title: z.string() }),
+ * prompt: (text: string) => `Generate a title for: ${text}`,
+ * onSuccess: (object) => console.log(object.title),
+ * });
+ *
+ * mutation.mutate('Quarterly planning notes');
+ * mutation.data?.title;
+ * ```
+ */
+export function createAIObject<
+ Schema extends z.ZodType,
+ Variables = string,
+ OnMutateResult = unknown,
+>(
+ options: CreateAIObjectOptions<Schema, Variables, OnMutateResult>
+): CreateAIObjectResult<Schema, Variables, OnMutateResult> {
+ return useMutation<z.infer<Schema>, Error, Variables, OnMutateResult>(() => ({
+ ...options,
+ mutationFn: async (variables) => await generateAIObject(options, variables),
+ }));
+}
diff --git a/js/app/packages/queries/ai/index.ts b/js/app/packages/queries/ai/index.ts
new file mode 100644
index 0000000000..f3044e7ced
--- /dev/null
+++ b/js/app/packages/queries/ai/index.ts
@@ -0,0 +1,9 @@
+export {
+ AIObjectParseError,
+ AIObjectSchemaError,
+ AIObjectValidationError,
+ createAIObject,
+ type AIObjectSchemaViolation,
+ type CreateAIObjectOptions,
+ type CreateAIObjectResult,
+} from './createAIObject';
diff --git a/rust/cloud-storage/ai/src/constants.rs b/rust/cloud-storage/ai/src/constants.rs
deleted file mode 100644
index 7869307d3e..0000000000
--- a/rust/cloud-storage/ai/src/constants.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub const DEFAULT_MAX_TOKENS: u32 = 8192;
diff --git a/rust/cloud-storage/ai/src/lib.rs b/rust/cloud-storage/ai/src/lib.rs
index bfb795c054..05195a0dcb 100644
--- a/rust/cloud-storage/ai/src/lib.rs
+++ b/rust/cloud-storage/ai/src/lib.rs
@@ -1,11 +1,9 @@
pub mod chat_completion;
pub mod chat_stream;
-mod constants;
pub mod model_selection;
mod openai_toolset;
pub mod prompts;
pub mod simple_completion;
-pub mod structured_output;
pub mod structured_output_v2;
pub mod tool;
pub mod traits;
diff --git a/rust/cloud-storage/ai/src/structured_output.rs b/rust/cloud-storage/ai/src/structured_output.rs
deleted file mode 100644
index 65d6681fd4..0000000000
--- a/rust/cloud-storage/ai/src/structured_output.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use anyhow::{Context, Result};
-use async_openai::types::chat::{
- ChatCompletionRequestSystemMessage, ChatCompletionRequestUserMessage,
- CreateChatCompletionRequestArgs, ResponseFormat, ResponseFormatJsonSchema,
-};
-
-use serde_json::Value;
-
-use crate::{constants::DEFAULT_MAX_TOKENS, types::Model, types::OpenRouterClient};
-
-pub async fn structured_output_completion(
- user_request: &str,
- system_prompt: &str,
- schema: Value,
- schema_name: &str,
-) -> Result<String> {
- let client = OpenRouterClient::new();
-
- let json_schema = ResponseFormatJsonSchema {
- description: None,
- name: schema_name.to_string(),
- schema: Some(schema),
- strict: Some(true),
- };
-
- let response_format = ResponseFormat::JsonSchema { json_schema };
-
- let request = CreateChatCompletionRequestArgs::default()
- .max_tokens(DEFAULT_MAX_TOKENS)
- .model(Model::Claude45Haiku.to_string())
- .messages([
- ChatCompletionRequestSystemMessage::from(system_prompt).into(),
- ChatCompletionRequestUserMessage::from(user_request).into(),
- ])
- .response_format(response_format)
- .build()?;
-
- let response = client.chat().create(request).await?;
-
- let first_choice = response.choices.first().context("no choices found")?;
-
- if let Some(content) = &first_choice.message.content {
- return Ok(content.to_string());
- }
-
- Err(anyhow::anyhow!("no content found"))
-}
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
index d9a6e98eee..659c30a897 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
@@ -1,3 +1,5 @@
+#![allow(dead_code)]
+
use super::MAX_RECURSIONS;
use crate::openai_toolset::OpenAIToolSetExt;
use crate::tool::types::{