All files / api/src/utils embeddings.ts

38.43% Statements 98/255
87.09% Branches 27/31
80% Functions 4/5
38.43% Lines 98/255

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 3191x 1x     1x 1x 1x             1x 1x   1x 1x 1x 1x 1x 1x   2x 2x 2x 2x 2x   2x 1x 1x 1x 1x 1x 1x 1x 1x   1x 2x                                                                                                                       2x 1x 1x   2x 2x   1x 6x       6x 6x 6x 3x 6x 1x 6x 2x 6x 6x   1x 9x 9x 9x 9x   14x 14x 13x   9x 9x 12x 12x   12x 12x 11x 12x 1x 1x   12x 10x 12x 1x 1x 2x 2x 2x   1x 1x 1x 1x       12x 1x 1x 1x               1x 1x 1x 1x 1x     12x 1x 1x   12x 7x 7x 2x 2x 2x     9x 9x 9x 9x                                                                                                                                                                                                                                                        
import { isAPIKeyRequiredForProvider } from '@api/ai-providers';
import { getApiUrl, getBearerToken } from '@api/constants';
import type { UserDataStorageConnector } from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import { resolveEmbeddingModelConfig } from '@api/utils/evaluation-model-resolver';
import { warn } from '@shared/console-logging';
import {
  type ChatCompletionRequestData,
  FunctionName,
  type ResponsesRequestData,
  type StreamChatCompletionRequestData,
} from '@shared/types/api/request';
import type { ChatCompletionMessage } from '@shared/types/api/routes/shared/messages';
import { ChatCompletionMessageRole } from '@shared/types/api/routes/shared/messages';
import { nanoid } from 'nanoid';
 
export class RequestEmbeddingError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'RequestEmbeddingError';
  }
}
 
function extractMessagesFromResponsesRequest(
  saRequestData: ResponsesRequestData,
): ChatCompletionMessage[] {
  const input = saRequestData.requestBody.input;
  let messages: ChatCompletionMessage[] = [];
 
  if (typeof input === 'string') {
    messages = [
      {
        role: ChatCompletionMessageRole.USER,
        content: input,
      },
    ];
  } else {
    const idMap = new Map<string, string>();
 
    input.forEach((message) => {
      if (!('role' in message)) {
        if (
          'name' in message &&
          'call_id' in message &&
          message.type === 'function'
        ) {
          let id = idMap.get(message.call_id);
          if (!id) {
            id = nanoid(3);
            idMap.set(message.call_id, id);
          }
          messages.push({
            role: ChatCompletionMessageRole.ASSISTANT,
            tool_calls: [
              {
                id: id,
                type: 'function',
                function: {
                  name: message.name,
                  arguments: JSON.stringify(message.arguments),
                },
              },
            ],
          });
        } else if ('output' in message && 'call_id' in message) {
          let id = idMap.get(message.call_id);
          if (!id) {
            id = nanoid(3);
            idMap.set(message.call_id, id);
          }
          messages.push({
            role: ChatCompletionMessageRole.TOOL,
            tool_call_id: id,
            content: message.output,
          });
        } else if (message.type === 'mcp_call' && 'server_label' in message) {
          const id = nanoid(3);
          messages.push({
            role: ChatCompletionMessageRole.ASSISTANT,
            tool_calls: [
              {
                id: id,
                type: 'mcp_call',
                function: {
                  name: message.name,
                  arguments: JSON.stringify(message.arguments),
                },
              },
            ],
          });
          messages.push({
            role: ChatCompletionMessageRole.TOOL,
            tool_call_id: id,
            content: message.output ?? message.error ?? 'success',
          });
        }
 
        // If there is no role, we likely don't want to embed the message
        return;
      }
      messages.push(message);
    });
  }
 
  return messages;
}
 
export function extractMessagesFromRequestData(
  saRequestData:
    | ChatCompletionRequestData
    | StreamChatCompletionRequestData
    | ResponsesRequestData,
): ChatCompletionMessage[] {
  switch (saRequestData.functionName) {
    case FunctionName.CHAT_COMPLETE:
      return saRequestData.requestBody.messages;
    case FunctionName.STREAM_CHAT_COMPLETE:
      return saRequestData.requestBody.messages;
    case FunctionName.CREATE_MODEL_RESPONSE:
      return extractMessagesFromResponsesRequest(saRequestData);
  }
}
 
export function formatMessagesForEmbedding(
  messages: ChatCompletionMessage[],
): string {
  return messages
    .filter((message) => {
      // Exclude system and developer messages from embeddings
      return (
        message.role !== ChatCompletionMessageRole.SYSTEM &&
        message.role !== ChatCompletionMessageRole.DEVELOPER
      );
    })
    .map((message) => {
      const role = message.role;
      let content = '';
 
      if (
        role === ChatCompletionMessageRole.TOOL ||
        role === ChatCompletionMessageRole.FUNCTION
      ) {
        return `Tool Call ${message.tool_call_id} Output: ${content}`;
      }
 
      if (typeof message.content === 'string') {
        content += message.content;
      } else if (Array.isArray(message.content)) {
        content += message.content
          .map((item) => {
            if (typeof item === 'object' && item.text) {
              return item.text;
            }
            return '';
          })
          .filter(Boolean)
          .join(' ');
      } else if (message.content) {
        content += String(message.content);
      }
 
      if (message.tool_calls && message.tool_calls.length > 0) {
        const tools = message.tool_calls
          .map((tool) => {
            const parsedTool = tool as {
              id: string;
              type: 'mcp_call';
              function: {
                name: string;
                arguments: string;
              };
            };
            return `Tool Call ID: ${parsedTool.id}\nTool Call Name: ${parsedTool.function.name}\nTool Call Arguments: ${parsedTool.function.arguments}`;
          })
          .join(', ');
        return `Assistant Tool Calls:\n${tools}`;
      }
 
      // Only include messages with non-empty content after trimming
      if (!content.trim()) {
        return '';
      }
 
      if (role === ChatCompletionMessageRole.USER) {
        return `User: ${content}`.trim();
      }
      if (role === ChatCompletionMessageRole.ASSISTANT) {
        return `Assistant: ${content}`.trim();
      }
 
      return `${role}: ${content}`.trim();
    })
    .filter(Boolean)
    .join('\n\n\n');
}
 
export async function generateEmbeddingForRequest(
  c: AppContext,
  saRequestData:
    | ChatCompletionRequestData
    | StreamChatCompletionRequestData
    | ResponsesRequestData,
  connector: UserDataStorageConnector,
): Promise<number[]> {
  // Resolve embedding model from system settings (includes dimensions)
  const embeddingConfig = await resolveEmbeddingModelConfig(c, connector);
 
  if (!embeddingConfig) {
    warn('[EMBEDDING] No embedding model configured in system settings');
    throw new RequestEmbeddingError(
      'No embedding model configured in system settings',
    );
  }
 
  // Look up the provider to get the API key
  const providers = await connector.getAIProviderAPIKeys(c, {
    id: embeddingConfig.model.ai_provider_id,
  });
  if (providers.length === 0) {
    warn(
      `[EMBEDDING] Provider not found for model: ${embeddingConfig.model.ai_provider_id}`,
    );
    throw new RequestEmbeddingError('Embedding model provider not found');
  }
  const providerConfig = providers[0];
 
  // Self-hosted providers such as Ollama are configured without a key, so only
  // the providers that need one are held to it.
  if (
    !providerConfig.api_key &&
    isAPIKeyRequiredForProvider(providerConfig.ai_provider)
  ) {
    warn(
      `[EMBEDDING] No API key configured for provider: ${embeddingConfig.model.ai_provider_id}`,
    );
    throw new RequestEmbeddingError(
      'No API key configured for embedding provider',
    );
  }
 
  try {
    const messages = extractMessagesFromRequestData(saRequestData);
    const inputText = formatMessagesForEmbedding(messages);
 
    if (!inputText.trim()) {
      throw new RequestEmbeddingError(
        'No valid text content found in messages',
      );
    }
 
    const saConfig = {
      targets: [
        {
          provider: providerConfig.ai_provider,
          model: embeddingConfig.model.model_name,
          ...(providerConfig.api_key
            ? { api_key: providerConfig.api_key }
            : {}),
          // Same reason as the other internal skills: without this a
          // self-hosted embedding provider is sent to its vendor default.
          ...(providerConfig.custom_fields?.custom_host
            ? { custom_host: providerConfig.custom_fields.custom_host }
            : {}),
        },
      ],
      agent_name: 'super-agents',
      skill_name: 'embedding',
    };
 
    // We use the fetch instead of the openai library because the openai
    // library attempts to automatically truncate the embeddings to fit their models'
    // dimensions.
    const response = await fetch(`${getApiUrl(c)}/v1/embeddings`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getBearerToken(c)}`,
        'sa-config': JSON.stringify(saConfig),
      },
      body: JSON.stringify({
        model: embeddingConfig.model.model_name,
        input: inputText,
        dimensions: embeddingConfig.dimensions,
      }),
    });
 
    if (!response.ok) {
      const errorText = await response.text();
      throw new RequestEmbeddingError(
        `Embedding API returned ${response.status}: ${errorText}`,
      );
    }
 
    const data = (await response.json()) as {
      data?: { embedding: number[] }[];
    };
 
    if (!data.data || data.data.length === 0) {
      throw new RequestEmbeddingError(
        'No embedding data returned from AI Provider',
      );
    }
 
    const embeddingData = data.data[0];
 
    return embeddingData.embedding;
  } catch (error) {
    if (error instanceof RequestEmbeddingError) {
      throw error;
    }
    if (error instanceof Error) {
      throw new RequestEmbeddingError(
        `Failed to generate embedding: ${error.message}`,
      );
    }
    throw new RequestEmbeddingError(`Unknown error generating embedding`);
  }
}