Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): structured completion endpoint with agent (#3429)
Eric Hayesa4e8b6c234cc
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex d1f7dd7403..7bd4794f6b 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -271,7 +271,6 @@ function ChatInner(props: {}><ChatDebugIcon />- {/*{showStreamDebug() ? 'Hide' : 'Show'} Stream Debug*/}</Button></Show></SplitToolbarLeft>diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex 5cb54a959b..f6e3095ed5 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -27,6 +27,8 @@ import type { StartAuthResponse } from './generated/schemas/startAuthResponse';import type { StopChatStreamRequest } from './generated/schemas/stopChatStreamRequest';import type { StopChatStreamResponse } from './generated/schemas/stopChatStreamResponse';import type { StringIDResponse } from './generated/schemas/stringIDResponse';+import type { StructuredCompletionRequest } from './generated/schemas/structuredCompletionRequest';+import type { StructuredCompletionResponse } from './generated/schemas/structuredCompletionResponse';import type { UpdateServerRequest } from './generated/schemas/updateServerRequest';import type * as toolTypes from './generated/tools/tool.ts';@@ -354,6 +356,15 @@ export const cognitionApiServiceClient = {})).map((result) => result);},++ async structuredCompletion(args: StructuredCompletionRequest) {+ return (+ await dcsFetch<StructuredCompletionResponse>(`/structured-completion`, {+ method: 'POST',+ body: JSON.stringify(args),+ })+ ).map((result) => result);+ },};export async function generateTitle(text: string): Promise<string | undefined> {diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex c1891ad7df..20bfd20e99 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -35,6 +35,9 @@ import type {StopChatStreamRequest,StopChatStreamResponse,StringIDResponse,+ StructuredCompletionError,+ StructuredCompletionRequest,+ StructuredCompletionResponse,UpdateServerRequest,UpdateToolCallRequest,UpdateToolResponseRequest,@@ -1628,3 +1631,72 @@ export const stopChatStream = async (headers: res.headers,} as stopChatStreamResponse;};++export type structuredCompletionResponse200 = {+ data: StructuredCompletionResponse;+ status: 200;+};++export type structuredCompletionResponse400 = {+ data: StructuredCompletionError;+ status: 400;+};++export type structuredCompletionResponse401 = {+ data: void;+ status: 401;+};++export type structuredCompletionResponse402 = {+ data: void;+ status: 402;+};++export type structuredCompletionResponse500 = {+ data: StructuredCompletionError;+ status: 500;+};++export type structuredCompletionResponseSuccess =+ structuredCompletionResponse200 & {+ headers: Headers;+ };+export type structuredCompletionResponseError = (+ | structuredCompletionResponse400+ | structuredCompletionResponse401+ | structuredCompletionResponse402+ | structuredCompletionResponse500+) & {+ headers: Headers;+};++export type structuredCompletionResponse =+ | structuredCompletionResponseSuccess+ | structuredCompletionResponseError;++export const getStructuredCompletionUrl = () => {+ return `/structured-completion`;+};++export const structuredCompletion = async (+ structuredCompletionRequest: StructuredCompletionRequest,+ options?: RequestInit+): Promise<structuredCompletionResponse> => {+ const res = await fetch(getStructuredCompletionUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(structuredCompletionRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: structuredCompletionResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as structuredCompletionResponse;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchema.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchema.tsnew file mode 100644index 0000000000..1ec8022d11--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchema.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { DynamicSchemaDescription } from './dynamicSchemaDescription';++export interface DynamicSchema {+ description?: DynamicSchemaDescription;+ name: string;+ schema: unknown;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchemaDescription.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchemaDescription.tsnew file mode 100644index 0000000000..0db1eb44f7--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/dynamicSchemaDescription.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export type DynamicSchemaDescription = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.tsindex 168d0bf465..5b81949174 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts@@ -113,6 +113,8 @@ export * from './documentReferenceOneOf';export * from './documentReferenceOneOfAllOf';export * from './documentReferenceOneOfAllOfKind';export * from './documentTextPart';+export * from './dynamicSchema';+export * from './dynamicSchemaDescription';export * from './entity';export * from './entityType';export * from './errorResponse';@@ -179,6 +181,10 @@ export * from './streamErrorOneOfStreamError';export * from './streamErrorOneOfThree';export * from './streamErrorOneOfThreeStreamError';export * from './stringIDResponse';+export * from './structuredCompletionError';+export * from './structuredCompletionRequest';+export * from './structuredCompletionRequestAdditionalInstructions';+export * from './structuredCompletionResponse';export * from './toolSchema';export * from './toolSchemas';export * from './toolSet';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionError.tsnew file mode 100644index 0000000000..cf8b797c58--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export interface StructuredCompletionError {+ error: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.tsnew file mode 100644index 0000000000..f8039a6053--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++import type { DynamicSchema } from './dynamicSchema';+import type { Model } from './model';+import type { StructuredCompletionRequestAdditionalInstructions } from './structuredCompletionRequestAdditionalInstructions';+import type { ToolSet } from './toolSet';++export interface StructuredCompletionRequest {+ additional_instructions?: StructuredCompletionRequestAdditionalInstructions;+ model: Model;+ output_schema: DynamicSchema;+ prompt: string;+ toolset?: ToolSet;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequestAdditionalInstructions.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequestAdditionalInstructions.tsnew file mode 100644index 0000000000..964334e056--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequestAdditionalInstructions.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export type StructuredCompletionRequestAdditionalInstructions = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionResponse.tsnew file mode 100644index 0000000000..c10c83fbbf--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionResponse.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export interface StructuredCompletionResponse {+ result: unknown;+}diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex 0d8ac71094..35de63541b 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -1351,6 +1351,60 @@}}}+ },+ "/structured-completion": {+ "post": {+ "tags": ["structured_completion"],+ "operationId": "structured_completion",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StructuredCompletionRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Structured completion result",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StructuredCompletionResponse"+ }+ }+ }+ },+ "400": {+ "description": "Bad request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StructuredCompletionError"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "Payment required"+ },+ "500": {+ "description": "Internal error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StructuredCompletionError"+ }+ }+ }+ }+ }+ }}},"components": {@@ -2286,6 +2340,19 @@}}},+ "DynamicSchema": {+ "type": "object",+ "required": ["schema", "name"],+ "properties": {+ "description": {+ "type": ["string", "null"]+ },+ "name": {+ "type": "string"+ },+ "schema": {}+ }+ },"Entity": {"type": "object","description": "The Entity describes the minimum amount of information required to describe a unique thing in Macro\nThis contains the type of the entity [EntityType] and the string id of that entity",@@ -3366,6 +3433,43 @@}}},+ "StructuredCompletionError": {+ "type": "object",+ "required": ["error"],+ "properties": {+ "error": {+ "type": "string"+ }+ }+ },+ "StructuredCompletionRequest": {+ "type": "object",+ "required": ["prompt", "model", "output_schema"],+ "properties": {+ "additional_instructions": {+ "type": ["string", "null"]+ },+ "model": {+ "$ref": "#/components/schemas/Model"+ },+ "output_schema": {+ "$ref": "#/components/schemas/DynamicSchema"+ },+ "prompt": {+ "type": "string"+ },+ "toolset": {+ "$ref": "#/components/schemas/ToolSet"+ }+ }+ },+ "StructuredCompletionResponse": {+ "type": "object",+ "required": ["result"],+ "properties": {+ "result": {}+ }+ },"ToolSchema": {"type": "object","description": "Schema information for a single tool, serializable for API responses.",diff --git a/rust/cloud-storage/ai/src/structured_output_v2.rs b/rust/cloud-storage/ai/src/structured_output_v2.rsindex 4233ef8a29..24a9195821 100644--- a/rust/cloud-storage/ai/src/structured_output_v2.rs+++ b/rust/cloud-storage/ai/src/structured_output_v2.rs@@ -1,8 +1,21 @@use crate::traits::Metadata;use crate::types::{ChatCompletionRequest, OpenRouterClient};use anyhow::{Context, Result};+use async_openai::types::chat::{+ CreateChatCompletionRequestArgs, ResponseFormat, ResponseFormatJsonSchema,+};use schemars::JsonSchema;+use serde::{Deserialize, Serialize};use serde_json;+use utoipa::ToSchema;++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct DynamicSchema {+ pub schema: serde_json::Value,+ pub name: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+}/// this doesn't work with anything that serialized as "OneOf" / "AnyOf" (enums)#[tracing::instrument]@@ -35,3 +48,45 @@ whereanyhow::bail!("Expected structured response")}++#[tracing::instrument(skip(request), err)]+pub async fn dynamic_structured_completion(+ request: ChatCompletionRequest,+ schema: DynamicSchema,+) -> Result<serde_json::Value> {+ let response_format = ResponseFormat::JsonSchema {+ json_schema: ResponseFormatJsonSchema {+ description: schema.description,+ name: schema.name,+ schema: Some(schema.schema),+ strict: Some(true),+ },+ };++ let model = request.model();+ let openai_request = CreateChatCompletionRequestArgs::default()+ .model(format!("{}/{}", model.to_provider_model_string().0, model))+ .messages(request.openai_messages())+ .response_format(response_format)+ .build()+ .context("Could not build structured completion request")?;++ let client = OpenRouterClient::new();+ let response = client.chat().create(openai_request).await;++ match response {+ Ok(chat_response) => {+ for choice in chat_response.choices {+ if let Some(content) = choice.message.content {+ return serde_json::from_str::<serde_json::Value>(&content)+ .context("Failed to parse structured output as JSON");+ }+ }+ anyhow::bail!("Structured completion returned no content")+ }+ Err(e) => {+ tracing::error!(error=?e, "Structured completion API call failed");+ anyhow::bail!("Structured completion failed: {}", e)+ }+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex c6a7e09cda..7b817ad187 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -25,6 +25,7 @@ pub mod utils;mod attachments;mod chats;+pub mod structured_completion;#[tracing::instrument(err, skip(state))]pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {@@ -77,6 +78,19 @@ fn api_router(api_context: ApiContext) -> Router {let internal_router = Router::new().nest("/chats", chats::router(api_context.clone())).nest("/stream", stream::router(api_context.clone()))+ .route(+ "/structured-completion",+ post(structured_completion::structured_completion).layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::auth::ensure_user_exists::handler,+ ))+ .layer(axum::middleware::from_fn_with_state(+ api_context.clone(),+ macro_middleware::user_permissions::attach_user_permissions::handler,+ )),+ ),+ ).nest("/attachments", attachments::router()).nest("/citations", citations::router()).nest("/preview", preview::router())diff --git a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rsnew file mode 100644index 0000000000..e49c4c5d9b--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs@@ -0,0 +1,168 @@+use crate::api::context::ApiContext;+use crate::core::constants::DEFAULT_MAX_TOKENS;+use crate::model::stream::ToolSet;+use ai::structured_output_v2::DynamicSchema;+use ai::tool::ToolLoop;+use ai::types::{MessageBuilder, Model, RequestBuilder, Role};+use ai_tools::RequestContext;+use axum::Json;+use axum::extract::{Extension, State};+use axum::http::StatusCode;+use axum::response::IntoResponse;+use chat::inbound::http::extractors::ChatModelAccess;+use futures::StreamExt;+use macro_user_id::user_id::MacroUserIdStr;+use mcp_client::domain::ports::McpServerStore;+use model::user::UserContext;+use serde::{Deserialize, Serialize};+use std::fmt;+use std::sync::Arc;+use utoipa::ToSchema;++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StructuredCompletionRequest {+ pub prompt: String,+ pub model: Model,+ pub output_schema: DynamicSchema,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub additional_instructions: Option<String>,+ #[serde(default)]+ pub toolset: ToolSet,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StructuredCompletionResponse {+ pub result: serde_json::Value,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StructuredCompletionError {+ pub error: String,+ #[serde(skip)]+ pub status: StatusCode,+}++impl fmt::Display for StructuredCompletionError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.error)+ }+}++impl IntoResponse for StructuredCompletionError {+ fn into_response(self) -> axum::response::Response {+ (self.status, Json(self)).into_response()+ }+}++#[utoipa::path(+ post,+ path = "/structured-completion",+ request_body = StructuredCompletionRequest,+ responses(+ (status = 200, description = "Structured completion result", body = StructuredCompletionResponse),+ (status = 400, description = "Bad request", body = StructuredCompletionError),+ (status = 401, description = "Unauthorized"),+ (status = 402, description = "Payment required"),+ (status = 500, description = "Internal error", body = StructuredCompletionError),+ )+)]+#[tracing::instrument(skip(state, _model_access, user_context, request), fields(user_id = %user_context.user_id), err)]+pub async fn structured_completion(+ State(state): State<ApiContext>,+ _model_access: ChatModelAccess,+ Extension(user_context): Extension<UserContext>,+ Json(request): Json<StructuredCompletionRequest>,+) -> Result<Json<StructuredCompletionResponse>, StructuredCompletionError> {+ let ctx = Arc::new(state);++ let user_id = MacroUserIdStr::try_from(user_context.user_id.clone()).map_err(|_| {+ StructuredCompletionError {+ error: "Invalid user ID".to_string(),+ status: StatusCode::BAD_REQUEST,+ }+ })?;++ let tools_prompt = match request.toolset {+ ToolSet::All => ctx.all_tools_prompt,+ ToolSet::None => ai_tools::prompts::BASE_PROMPT,+ };++ let system_prompt = match &request.additional_instructions {+ Some(instructions) => format!("{}\n{}", tools_prompt, instructions),+ None => tools_prompt.to_string(),+ };++ let ai_request = RequestBuilder::new()+ .model(request.model)+ .user_message(&request.prompt)+ .system_prompt(system_prompt.clone())+ .max_tokens(DEFAULT_MAX_TOKENS)+ .build();++ // Phase 1: Run agent loop to gather information+ let mcp_store = ctx.mcp_state.store();+ let mcp_records = mcp_store.list(&user_id).await.unwrap_or_default();+ let toolset = Arc::new(+ mcp_client::domain::service::CombinedToolSet::new(ctx.all_tools.clone(), &mcp_records)+ .await,+ );+ let client = ToolLoop::new(toolset, ctx.tool_service_context.clone());+ let mut chat = client.chat();++ let request_context = RequestContext {+ user_id: user_id.clone(),+ };+ let mut stream = chat+ .send_message(ai_request, request_context, user_id.as_ref().to_string())+ .await+ .map_err(|e| StructuredCompletionError {+ error: format!("Agent loop failed: {e}"),+ status: StatusCode::INTERNAL_SERVER_ERROR,+ })?;++ while let Some(item) = stream.next().await {+ if let Err(e) = item {+ return Err(StructuredCompletionError {+ error: format!("Agent loop error: {e}"),+ status: StatusCode::INTERNAL_SERVER_ERROR,+ });+ }+ }+ drop(stream);++ // Phase 2: Structured completion with the gathered context+ let new_messages = chat.get_new_conversation_messages();++ let mut all_messages = vec![+ MessageBuilder::new()+ .role(Role::User)+ .content(request.prompt)+ .build(),+ ];+ all_messages.extend(new_messages);+ all_messages.push(+ MessageBuilder::new()+ .role(Role::User)+ .content("Based on the information gathered above, produce a structured response matching the required schema.")+ .build(),+ );++ let structured_request = RequestBuilder::new()+ .model(request.model)+ .messages(all_messages)+ .system_prompt(system_prompt)+ .max_tokens(DEFAULT_MAX_TOKENS)+ .build();++ let result = ai::structured_output_v2::dynamic_structured_completion(+ structured_request,+ request.output_schema,+ )+ .await+ .map_err(|e| StructuredCompletionError {+ error: format!("Structured completion failed: {e}"),+ status: StatusCode::INTERNAL_SERVER_ERROR,+ })?;++ Ok(Json(StructuredCompletionResponse { result }))+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex b5cbd43622..1ab40f9d26 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -10,6 +10,9 @@ use crate::api::{stream::stop::{self as stream_stop, StopChatStreamError, StopChatStreamRequest, StopChatStreamResponse,},+ structured_completion::{+ self, StructuredCompletionError, StructuredCompletionRequest, StructuredCompletionResponse,+ },};use crate::model::{response::{@@ -80,6 +83,7 @@ use utoipa::OpenApi;chat_history_batch_messages::get_chat_history_batch_messages_handler,chat_message::send_chat_message,stream_stop::stop_chat_stream,+ structured_completion::structured_completion,memory_api::get_memory_handler,mcp_api::list_servers,mcp_api::add_server,@@ -163,6 +167,10 @@ use utoipa::OpenApi;StopChatStreamError,StreamError,ToolSet,+ StructuredCompletionRequest,+ StructuredCompletionResponse,+ StructuredCompletionError,+ ai::structured_output_v2::DynamicSchema,// MemoryMemoryResponse,