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
add /v1/completions proxy (#1705)
Eric Hayes2433b2bfccad
diff --git a/js/app/bun.lock b/js/app/bun.lockindex ff2a462527..afd081479d 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -142,6 +142,7 @@"json-schema-to-zod": "^2.6.1","lightningcss": "^1.30.2","mock-socket": "^9.3.1",+ "openai": "^6.25.0","orval": "^7.13.0","solid-devtools": "^0.34.3","typescript": "^5.9.3",@@ -2662,6 +2663,8 @@"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],+ "openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-mEh6VZ2ds2AGGokWARo18aPISI1OhlgdEIC1ewhkZr8pSIT31dec0ecr9Nhxx0JlybyOgoAT1sWeKtwPZzJyww=="],+"openapi-types": ["[email protected]", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],"openapi3-ts": ["[email protected]", "", { "dependencies": { "yaml": "^2.8.0" } }, "sha512-jaL+HgTq2Gj5jRcfdutgRGLosCy/hT8sQf6VOy+P+g36cZOjI1iukdPnijC+4CmeRzg/jEllJUboEic2FhxhtQ=="],diff --git a/js/app/package.json b/js/app/package.jsonindex e3ac76747e..ebdda9dd24 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -151,6 +151,7 @@"bebop": "^3.1.3","bebop-tools": "^3.1.3","biome": "^0.3.3",+ "openai": "^6.25.0","concurrently": "^9.2.1","deepmerge": "^4.3.1","json-refs": "^3.0.15",diff --git a/js/app/packages/block-md/component/MarkdownPopup.tsx b/js/app/packages/block-md/component/MarkdownPopup.tsxindex 7571075136..45bf20064b 100644--- a/js/app/packages/block-md/component/MarkdownPopup.tsx+++ b/js/app/packages/block-md/component/MarkdownPopup.tsx@@ -2,7 +2,7 @@ import { useSplitLayout } from '@app/component/split-layout/layout';import { useIsAuthenticated } from '@core/auth';import { useBlockId } from '@core/block';import type { Completion } from '@core/client/completion';-import { structuredOutputCompletion } from '@core/client/structuredOutput';+import { generateTitle } from '@service-cognition/client';import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';// import { AskAi } from '@core/component/GeneralizedPopup/AskAI';@@ -261,41 +261,6 @@ export function MarkdownPopup(props: {}};- async function generateTitleForMarkdown(markdownText: string) {- try {- const schema = {- type: 'object',- properties: {- title: {- type: 'string',- description:- 'A concise and informative title that describes the following text excerpt',- },- },- required: ['title'],- additionalProperties: false,- };-- const result = await structuredOutputCompletion(- `Generate a concise and informative title that describes the following markdown text:\n\n${markdownText}`,- schema,- 'markdown_title_generator'- );-- if (- typeof result === 'object' &&- result !== null &&- 'title' in result &&- typeof result.title === 'string'- ) {- return result.title;- }- } catch (e) {- console.error(e);- }- return undefined;- }-const handleReplaceText = createCallback(async (newText: string) => {editor.dispatchCommand(POPUP_REPLACE_TEXT, newText);setPopupVisible(false);@@ -309,7 +274,7 @@ export function MarkdownPopup(props: {return;}- const title: string | undefined = await generateTitleForMarkdown(content);+ const title = await generateTitle(content);const documentId = await createMarkdownFile({content,title: title ?? `${name()} - AI Explanation`,diff --git a/js/app/packages/block-pdf/component/PDFPopup.tsx b/js/app/packages/block-pdf/component/PDFPopup.tsxindex ea904c1ba0..43a69c8229 100644--- a/js/app/packages/block-pdf/component/PDFPopup.tsx+++ b/js/app/packages/block-pdf/component/PDFPopup.tsx@@ -2,7 +2,7 @@ import type { IHighlight } from '@block-pdf/model/Highlight';import { withAnalytics } from '@coparse/analytics';import { useIsAuthenticated } from '@core/auth';import { useBlockId } from '@core/block';-import { structuredOutputCompletion } from '@core/client/structuredOutput';+import { generateTitle } from '@service-cognition/client';import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';@@ -162,41 +162,6 @@ export function PDFPopup(props: PDFPopupProps) {}};- async function generateTitleForMarkdown(markdownText: string) {- try {- const schema = {- type: 'object',- properties: {- title: {- type: 'string',- description:- 'A concise and informative title that describes the following text excerpt',- },- },- required: ['title'],- additionalProperties: false,- };-- const result = await structuredOutputCompletion(- `Generate a concise and informative title that describes the following markdown text:\n\n${markdownText}`,- schema,- 'markdown_title_generator'- );-- if (- typeof result === 'object' &&- result !== null &&- 'title' in result &&- typeof result.title === 'string'- ) {- return result.title;- }- } catch (e) {- console.error(e);- }- return undefined;- }-const name = useBlockDocumentName();const handleEditInMarkdown = createCallback(async () => {setIsLoading(true);@@ -205,7 +170,7 @@ export function PDFPopup(props: PDFPopupProps) {return;}- const title: string | undefined = await generateTitleForMarkdown(content);+ const title = await generateTitle(content);const documentId = await createMarkdownFile({content,title: title ?? `${name()} - AI Explanation`,diff --git a/js/app/packages/core/client/structuredOutput.ts b/js/app/packages/core/client/structuredOutput.tsindex dbd63c86e5..6e4136dfcc 100644--- a/js/app/packages/core/client/structuredOutput.ts+++ b/js/app/packages/core/client/structuredOutput.ts@@ -1,5 +1,5 @@import { isErr } from '@core/util/maybeResult';-import { cognitionApiServiceClient } from '@service-cognition/client';+import { dcsCompletion } from '@service-cognition/client';type StructuredOutputSchema = {type: string;@@ -41,10 +41,17 @@ export async function structuredOutputCompletion<T>(schema: StructuredOutputSchema,schema_name: string): Promise<T | undefined> {- let response = await cognitionApiServiceClient.structuredOuputCompletion({- prompt: prompt,- schema,- schema_name: schema_name,+ 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)) {@@ -52,11 +59,11 @@ export async function structuredOutputCompletion<T>(return;}- const completion = response.at(1)?.completion;- if (!completion) {+ const content = response[1].choices[0]?.message?.content;+ if (!content) {console.error('No completion in structured output completion');return undefined;}- return completion as T;+ return JSON.parse(content) as T;}diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsxindex 76aa16025c..a04848ff15 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx@@ -1,5 +1,5 @@import { useSplitLayout } from '@app/component/split-layout/layout';-import { structuredOutputCompletion } from '@core/client/structuredOutput';+import { generateTitle } from '@service-cognition/client';import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';import { RenderTool } from '@core/component/AI/component/tool/handler';import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';@@ -137,41 +137,6 @@ export function AssistantMessage(props: {}};- async function generateTitleForMarkdown(markdownText: string) {- try {- const schema = {- type: 'object',- properties: {- title: {- type: 'string',- description:- 'A concise and informative title that describes the following markdown text',- },- },- required: ['title'],- additionalProperties: false,- };-- const result = await structuredOutputCompletion(- `Generate a concise and informative title that describes the following markdown text:\n\n${markdownText}`,- schema,- 'markdown_title_generator'- );-- if (- typeof result === 'object' &&- result !== null &&- 'title' in result &&- typeof result.title === 'string'- ) {- return result.title;- }- } catch (e) {- console.error(e);- }- return undefined;- }-// TODO correctly convert to MDconst handleEditInMarkdown = createCallback(async () => {const { replaceOrInsertSplit } = useSplitLayout();@@ -180,9 +145,7 @@ export function AssistantMessage(props: {extractMessageText(props.message.content));- const title: string | undefined = await generateTitleForMarkdown(- content.replace(/\[\[.*?\]\]/g, '')- );+ const title = await generateTitle(content.replace(/\[\[.*?\]\]/g, ''));const documentId = await createMarkdownFile({content,diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsxindex 858ecce346..292989c4c0 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx@@ -1,4 +1,4 @@-import { structuredOutputCompletion } from '@core/client/structuredOutput';+import { generateTitle } from '@service-cognition/client';import {DEFAULT_MODEL,MODEL_PRETTYNAME,@@ -73,9 +73,7 @@ export function AssistantMessageActionAndMetadata(props: AssistantActionProps) {extractMessageText(props.message.content));- const title: string | undefined = await generateTitleForMarkdown(- content.replace(/\[\[.*?\]\]/g, '')- );+ const title = await generateTitle(content.replace(/\[\[.*?\]\]/g, ''));const documentId = await createMarkdownFile({content,@@ -95,41 +93,6 @@ export function AssistantMessageActionAndMetadata(props: AssistantActionProps) {setIsLoading(false);});- async function generateTitleForMarkdown(markdownText: string) {- try {- const schema = {- type: 'object',- properties: {- title: {- type: 'string',- description:- 'A concise and informative title that describes the following markdown text',- },- },- required: ['title'],- additionalProperties: false,- };-- const result = await structuredOutputCompletion(- `Generate a concise and informative title that describes the following markdown text:\n\n${markdownText}`,- schema,- 'markdown_title_generator'- );-- if (- typeof result === 'object' &&- result !== null &&- 'title' in result &&- typeof result.title === 'string'- ) {- return result.title;- }- } catch (e) {- console.error(e);- }- return undefined;- }-return (<div class="flex flex-row w-full justify-start items-center h-[32px] px-2 space-x-2"><div class="flex flex-row space-x-2 items-center text-xs text-ink-muted">diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex ef77a772e7..af2cb0cf4b 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -10,9 +10,13 @@ import {type MaybeError,type MaybeResult,mapOk,+ ok,+ err,type ObjectLike,} from '@core/util/maybeResult';+import { platformFetch } from '@core/util/platformFetch';import type { SafeFetchInit } from '@core/util/safeFetch';+import type OpenAI from 'openai';import type { DocumentTextPart } from '@service-cognition/generated/schemas/documentTextPart';import type { CreateChatRequest } from './generated/schemas/createChatRequest';import type { EmptyResponse } from './generated/schemas/emptyResponse';@@ -25,8 +29,6 @@ import type { HttpSendChatMessageRequest } from './generated/schemas/httpSendChaimport type { PatchChatRequestV2 } from './generated/schemas/patchChatRequestV2';import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';import type { StringIDResponse } from './generated/schemas/stringIDResponse';-import type { StructedOutputCompletionRequest } from './generated/schemas/structedOutputCompletionRequest';-import type { StructedOutputCompletionResponse } from './generated/schemas/structedOutputCompletionResponse';import type { SuccessResponse } from './generated/schemas/successResponse';const dcsHost: string = SERVER_HOSTS['cognition-service'];@@ -233,19 +235,6 @@ export const cognitionApiServiceClient = {(result) => result);},- async structuredOuputCompletion(args: StructedOutputCompletionRequest) {- return mapOk(- await dcsFetch<StructedOutputCompletionResponse>(- `/completions/structured_output`,- {- method: 'POST',- body: JSON.stringify(args),- }- ),- (result) => result as { completion: any }- );- },-/** Send a chat message via HTTP stream API. Response chunks arrive via connection_gateway. */async sendStreamChatMessage(args: HttpSendChatMessageRequest) {return mapOk(@@ -257,3 +246,56 @@ export const cognitionApiServiceClient = {);},};++export async function generateTitle(text: string): Promise<string | undefined> {+ const result = await dcsCompletion({+ model: 'gpt-4o-mini',+ messages: [+ {+ role: 'user',+ content: `Generate a concise and informative title that describes the following text. A title should never be longer than 4 words. Respond with only the title, nothing else.\n\n${text}`,+ },+ ],+ max_tokens: 100,+ });++ if (isErr(result)) {+ console.error('Error generating title');+ return undefined;+ }++ return result[1].choices[0]?.message?.content?.trim() || undefined;+}++type DcsCompletionErrorCode = 'NETWORK_ERROR' | 'OPENAI_ERROR';++export async function dcsCompletion(+ body: Omit<OpenAI.ChatCompletionCreateParamsNonStreaming, 'stream'>+): Promise<+ MaybeResult<+ FetchWithTokenErrorCode | DcsCompletionErrorCode,+ OpenAI.ChatCompletion+ >+> {+ let response: Response;+ try {+ response = await platformFetch(`${dcsHost}/chat/completions`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ...body, stream: false }),+ });+ } catch {+ return err('NETWORK_ERROR', 'Failed to reach completions proxy');+ }++ const data = await response.json();++ if (!response.ok) {+ const message =+ data?.error?.message ??+ `Completion failed with status ${response.status}`;+ return err('OPENAI_ERROR', message);+ }+ return ok(data as OpenAI.ChatCompletion);+}diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex 1c900f132b..73910795ab 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -21,8 +21,6 @@ import type {HttpSendChatMessageRequest,SendChatMessageResponse,StringIDResponse,- StructedOutputCompletionRequest,- StructedOutputCompletionResponse,SuccessResponse,} from './schemas';@@ -630,60 +628,6 @@ export const getCitationHandler = async (} as getCitationHandlerResponse;};-export type handlerResponse200 = {- data: StructedOutputCompletionResponse;- status: 200;-};--export type handlerResponse401 = {- data: string;- status: 401;-};--export type handlerResponse404 = {- data: string;- status: 404;-};--export type handlerResponse500 = {- data: string;- status: 500;-};--export type handlerResponseSuccess = handlerResponse200 & {- headers: Headers;-};-export type handlerResponseError = (- | handlerResponse401- | handlerResponse404- | handlerResponse500-) & {- headers: Headers;-};--export type handlerResponse = handlerResponseSuccess | handlerResponseError;--export const getHandlerUrl = () => {- return `/completions/structured_output`;-};--export const handler = async (- structedOutputCompletionRequest: StructedOutputCompletionRequest,- options?: RequestInit-): Promise<handlerResponse> => {- const res = await fetch(getHandlerUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(structedOutputCompletionRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: handlerResponse['data'] = body ? JSON.parse(body) : {};- return { data, status: res.status, headers: res.headers } as handlerResponse;-};-/*** @summary Health check*/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 ed05d2ffa6..3c872e25b5 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@@ -179,8 +179,6 @@ export * from './streamErrorOneOfStreamError';export * from './streamErrorOneOfThree';export * from './streamErrorOneOfThreeStreamError';export * from './stringIDResponse';-export * from './structedOutputCompletionRequest';-export * from './structedOutputCompletionResponse';export * from './successResponse';export * from './toolSchema';export * from './toolSchemas';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionRequest.tsdeleted file mode 100644index bf38bbee16..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionRequest.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface StructedOutputCompletionRequest {- prompt: string;- schema: unknown;- schema_name: string;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionResponse.tsdeleted file mode 100644index b2d5693120..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/structedOutputCompletionResponse.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface StructedOutputCompletionResponse {- completion: unknown;-}diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex b176775645..19792bb28f 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -583,64 +583,6 @@}}},- "/completions/structured_output": {- "post": {- "tags": ["structured_output"],- "operationId": "handler",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StructedOutputCompletionRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StructedOutputCompletionResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },- "404": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },- "500": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- }- }- }- },"/health": {"get": {"tags": ["health"],@@ -2762,26 +2704,6 @@}}},- "StructedOutputCompletionRequest": {- "type": "object",- "required": ["prompt", "schema", "schema_name"],- "properties": {- "prompt": {- "type": "string"- },- "schema": {},- "schema_name": {- "type": "string"- }- }- },- "StructedOutputCompletionResponse": {- "type": "object",- "required": ["completion"],- "properties": {- "completion": {}- }- },"SuccessResponse": {"type": "object","required": ["error", "data"],diff --git a/rust/cloud-storage/document_cognition_service/src/api/completions.rs b/rust/cloud-storage/document_cognition_service/src/api/completions.rsnew file mode 100644index 0000000000..cc29743b78--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/completions.rs@@ -0,0 +1,37 @@+use axum::{extract, response::IntoResponse};++const OPENAI_CHAT_COMPLETIONS_URL: &str = "https://api.openai.com/v1/chat/completions";++/// A non-streaming proxy to the chatgpt api+#[tracing::instrument(err(Debug), skip(body))]+pub async fn handler(+ extract::Json(mut body): extract::Json<serde_json::Value>,+) -> impl IntoResponse {+ if let Some(obj) = body.as_object_mut() {+ obj.insert("stream".to_string(), serde_json::Value::Bool(false));+ }++ let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_default();++ let response = reqwest::Client::new()+ .post(OPENAI_CHAT_COMPLETIONS_URL)+ .bearer_auth(api_key)+ .json(&body)+ .send()+ .await+ .inspect_err(|err| tracing::error!(error=?err, "failed to proxy chat completion"))+ .map_err(|err| (axum::http::StatusCode::BAD_GATEWAY, err.to_string()))?;++ let status = axum::http::StatusCode::from_u16(response.status().as_u16())+ .unwrap_or(axum::http::StatusCode::OK);+ let bytes = response.bytes().await.map_err(|err| {+ tracing::error!(error=?err, "failed to read chat completion response");+ (axum::http::StatusCode::BAD_GATEWAY, err.to_string())+ })?;++ Ok::<_, (axum::http::StatusCode, String)>((+ status,+ [(axum::http::header::CONTENT_TYPE, "application/json")],+ bytes,+ ))+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/completions/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/completions/mod.rsdeleted file mode 100644index fe91867020..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/completions/mod.rs+++ /dev/null@@ -1,12 +0,0 @@-pub mod structured_output;-use axum::{Router, routing::post};-use tower::ServiceBuilder;--pub fn router() -> Router {- Router::new().route(- "/structured_output",- post(structured_output::handler).layer(ServiceBuilder::new().layer(- axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),- )),- )-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/completions/structured_output.rs b/rust/cloud-storage/document_cognition_service/src/api/completions/structured_output.rsdeleted file mode 100644index e5ca6cf038..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/completions/structured_output.rs+++ /dev/null@@ -1,69 +0,0 @@-use anyhow::{Context, Result};-use axum::{extract::Json, http::StatusCode};-use serde::{Deserialize, Serialize};-use serde_json::Value;-use utoipa::ToSchema;--#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct StructedOutputCompletionRequest {- pub prompt: String,- pub schema: Value,- pub schema_name: String,-}--#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct StructedOutputCompletionResponse {- pub completion: Value,-}--#[utoipa::path(- post,- path = "/completions/structured_output",- responses(- (status = 200, body=StructedOutputCompletionResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- )- )]-#[tracing::instrument()]-pub async fn handler(- request: Json<StructedOutputCompletionRequest>,-) -> Result<(StatusCode, Json<StructedOutputCompletionResponse>), (StatusCode, String)> {- let completion = ai::structured_output::structured_output_completion(- &request.prompt,- ai_tools::prompts::BASE_PROMPT,- request.schema.clone(),- &request.schema_name,- )- .await- .map_err(|err| {- tracing::error!(- error = %err,- schema_name = %request.schema_name,- "failed to complete structured output"- );- (- StatusCode::INTERNAL_SERVER_ERROR,- "failed to complete structured output".to_string(),- )- })?;-- let response = StructedOutputCompletionResponse {- completion: serde_json::from_str(&completion)- .context("failed to parse completion")- .map_err(|err| {- tracing::error!(- error = %err,- schema_name = %request.schema_name,- "failed to parse completion"- );- (- StatusCode::INTERNAL_SERVER_ERROR,- "failed to parse completion".to_string(),- )- })?,- };-- Ok((StatusCode::OK, Json(response)))-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex bb5923ad02..aae004de58 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -2,6 +2,7 @@ use crate::api::context::ApiContext;use anyhow::Context;use axum::Router;use axum::extract::DefaultBodyLimit;+use axum::routing::post;use context::GLOBAL_CONTEXT;use model::version::{ServiceNameState, VersionedApiServiceName, validate_api_version};use tower::ServiceBuilder;@@ -77,7 +78,12 @@ fn api_router(api_context: ApiContext) -> Router {.nest("/preview", preview::router()).nest("/id_mapping", id_mapping::router()).with_state(api_context.clone())- .nest("/completions", completions::router())+ .route(+ "/chat/completions",+ post(completions::handler).layer(ServiceBuilder::new().layer(+ axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),+ )),+ ).nest("/models", models::router()).layer(ServiceBuilder::new()diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex 16a400be24..ef2ff81164 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -5,11 +5,7 @@ use crate::{chat_history, chat_history_batch_messages, copy_chat, create_user_chat, delete_chat,get_chat, get_chat_permissions, revert_delete_chat,},- citations,- completions::structured_output::{- self, StructedOutputCompletionRequest, StructedOutputCompletionResponse,- },- health,+ citations, health,models::get_models,preview::get_batch_preview,stream::chat_message::{@@ -72,7 +68,6 @@ use utoipa::OpenApi;get_chats_for_attachment::get_chats_for_attachment_handler,citations::get_citation_handler,get_batch_preview::handler,- structured_output::handler,revert_delete_chat::handler,chat_history::get_chat_history_handler,chat_history_batch_messages::get_chat_history_batch_messages_handler,@@ -140,10 +135,6 @@ use utoipa::OpenApi;GetBatchPreviewRequest,GetBatchPreviewResponse,- // Completions- StructedOutputCompletionRequest,- StructedOutputCompletionResponse,-// Stream HTTP APIHttpSendChatMessageRequest,SendChatMessageResponse,