Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

12.1 KB
Raw Blame
import { logWarn } from '../../audit/audit-log.logger';
import type {
  AiChatClient,
  AiChatEvent,
  AiChatMessage,
  AiChatRequest,
  AiFinishReason,
  AiImage,
  AiSource,
  AiToolCall,
} from '../ai-chat-client.interface';
import { AiProviderError, errorCodeOf, isReasoningEffortRefusal, providerFailure } from './provider-errors';
import {
  asCount,
  asRecord,
  asText,
  openProviderStream,
  parseEventData,
  parseToolArgs,
  toProviderSchema,
  type AiFetch,
} from './provider-http';
import { imageDataUrl, toolImageCaption, toolImagesEndingAt } from './provider-images';
import { readSseEvents } from './sse-lines';
import type { AiConnectionKind } from '@trek/shared';

/** The end of an OpenAI-compatible stream. */
const DONE = '[DONE]';

/** The host of Gemini's OpenAI-compatible endpoint, which an admin may also enter as their own server. */
const GEMINI_HOST = 'generativelanguage.googleapis.com';

function isGeminiHost(baseUrl: string): boolean {
  try {
    return new URL(baseUrl).hostname === GEMINI_HOST;
  } catch {
    return false;
  }
}

/**
 * The provider-neutral history as Chat Completions messages, the instructions
 * and the trip card first. A tool message takes no image, so the images of a
 * step's tool results follow its last result as one user message. `model` is
 * the one the request goes to: a thought signature goes back only to the model
 * that signed it, since another one cannot read it.
 */
export function toChatMessages(request: AiChatRequest, model?: string): Record<string, unknown>[] {
  const system = [request.system, request.context].filter(Boolean).join('\n\n');
  const out: Record<string, unknown>[] = [{ role: 'system', content: system }];
  request.messages.forEach((message, index) => {
    out.push(toChatMessage(message, model));
    const withImages = toolImagesEndingAt(request.messages, index);
    if (withImages.length === 0) return;
    const content = withImages.flatMap((tool) => [
      { type: 'text', text: toolImageCaption(tool) },
      ...(tool.images ?? []).map(imagePart),
    ]);
    out.push({ role: 'user', content });
  });
  return out;
}

function imagePart(image: AiImage): Record<string, unknown> {
  return { type: 'image_url', image_url: { url: imageDataUrl(image), detail: image.detail ?? 'high' } };
}

function toChatMessage(message: AiChatMessage, model: string | undefined): Record<string, unknown> {
  if (message.role === 'user') {
    if (!message.images?.length) return { role: 'user', content: message.text };
    return { role: 'user', content: [{ type: 'text', text: message.text }, ...message.images.map(imagePart)] };
  }
  if (message.role === 'tool') return { role: 'tool', tool_call_id: message.toolCallId, content: message.output };
  const state = message.providerState;
  const signatures = state?.adapter === 'openai-chat' && state.model === model ? state.signatures : {};
  return {
    role: 'assistant',
    content: message.text || null,
    ...(message.toolCalls.length > 0
      ? {
          tool_calls: message.toolCalls.map((call) => ({
            id: call.id,
            type: 'function',
            function: { name: call.name, arguments: JSON.stringify(call.args) },
            ...(signatures[call.id] ? { extra_content: { google: { thought_signature: signatures[call.id] } } } : {}),
          })),
        }
      : {}),
  };
}

/** Gemini signs a tool call on its first piece; the call has to go back with it or the next request is refused. */
function thoughtSignatureOf(piece: Record<string, unknown>): string {
  return asText(asRecord(asRecord(piece.extra_content).google).thought_signature);
}

/** The id a call goes on with; a provider that names none gets one from the call's position. */
function callId(index: number, id: string): string {
  return id || `call_${index}`;
}

const FINISH_REASONS: Record<string, AiFinishReason> = { tool_calls: 'tool-calls', length: 'length' };

/**
 * The OpenAI-compatible Chat Completions API, streamed: OpenAI itself, Gemini
 * (its `/v1beta/openai` endpoint), OpenRouter and an admin's own server. The
 * kind decides only what a request may carry: Gemini gets its narrower tool
 * schemas, also when an admin enters its endpoint as their own server, and
 * OpenAI the prompt cache key, which the others do not know. Gemini's thought
 * signatures come back as the turn's provider state.
 *
 * No request names a reasoning effort, since a server that does not reason may
 * refuse the field. A reasoning model that takes function tools only without
 * reasoning (Azure AI Foundry's deployments, #3043) refuses the default effort
 * by naming `reasoning_effort`; the request then goes out once more with
 * `reasoning_effort: "none"`, and so does every later request with tools on
 * this client, which lives for one turn.
 */
export class OpenAiChatClient implements AiChatClient {
  /** OpenRouter searches the web for any model through its web plugin; the others have no search here. */
  get webSearch(): boolean {
    return this.kind === 'openrouter';
  }

  /** The kind whose tool schemas the endpoint takes. */
  private readonly schemaKind: AiConnectionKind;

  /** Whether the server refused function tools with the model's reasoning, so they go out without it. */
  private toolsWithoutReasoning = false;

  constructor(
    readonly kind: AiConnectionKind,
    readonly model: string,
    private readonly baseUrl: string,
    private readonly apiKey: string | null,
    private readonly fetcher: AiFetch,
  ) {
    this.schemaKind = kind === 'custom' && isGeminiHost(baseUrl) ? 'gemini' : kind;
  }

  async *stream(request: AiChatRequest, signal: AbortSignal): AsyncGenerator<AiChatEvent> {
    const events = await this.open(request, signal);

    const turn = new ChatTurn();
    for await (const sse of readSseEvents(events)) {
      if (sse.data.trim() === DONE) {
        turn.done = true;
        break;
      }
      const chunk = parseEventData(sse.data);
      if (!chunk) continue;
      if (chunk.error) throw providerFailure(this.kind, 0, errorCodeOf(chunk));
      const delta = turn.apply(chunk);
      if (delta) yield { type: 'text-delta', delta };
      for (const source of turn.newSources()) yield { type: 'source', source };
    }
    if (!turn.done && !turn.reason) throw new AiProviderError('provider_unavailable', 0, true, undefined, 'stream_cut');
    for (const call of turn.calls()) yield { type: 'tool-call', call };
    yield {
      type: 'usage',
      inputTokens: turn.inputTokens,
      cachedInputTokens: turn.cachedInputTokens,
      outputTokens: turn.outputTokens,
    };
    const signatures = turn.signatures();
    if (Object.keys(signatures).length > 0) {
      yield { type: 'provider-state', state: { adapter: 'openai-chat', model: this.model, signatures } };
    }
    yield { type: 'finish', reason: turn.finishReason() };
  }

  /**
   * Opens the request's stream. A refusal of the model's reasoning effort for
   * a request with tools is answered once by asking again without reasoning.
   */
  private async open(request: AiChatRequest, signal: AbortSignal): Promise<ReadableStream<Uint8Array>> {
    try {
      return await this.send(request, signal);
    } catch (err) {
      if (this.toolsWithoutReasoning || request.tools.length === 0 || !isReasoningEffortRefusal(err)) throw err;
      this.toolsWithoutReasoning = true;
      logWarn(`[ai] ${this.kind} takes function tools only without reasoning: asking again with reasoning_effort none`);
      return this.send(request, signal);
    }
  }

  private send(request: AiChatRequest, signal: AbortSignal): Promise<ReadableStream<Uint8Array>> {
    const body = {
      model: this.model,
      stream: true,
      stream_options: { include_usage: true },
      messages: toChatMessages(request, this.model),
      ...(request.tools.length > 0
        ? {
            tools: request.tools.map((tool) => ({
              type: 'function',
              function: {
                name: tool.name,
                description: tool.description,
                parameters: toProviderSchema(tool.parameters, this.schemaKind),
              },
            })),
            tool_choice: request.toolChoice ?? 'auto',
          }
        : {}),
      ...(this.toolsWithoutReasoning && request.tools.length > 0 ? { reasoning_effort: 'none' } : {}),
      ...(this.kind === 'openai' && request.cacheKey ? { prompt_cache_key: request.cacheKey } : {}),
      ...(request.webSearch && this.webSearch ? { plugins: [{ id: 'web', max_results: 5 }] } : {}),
    };
    return openProviderStream(
      this.fetcher,
      this.kind,
      `${this.baseUrl}/chat/completions`,
      {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
          accept: 'text/event-stream',
          ...(this.apiKey ? { authorization: `Bearer ${this.apiKey}` } : {}),
        },
        body: JSON.stringify(body),
      },
      signal,
    );
  }
}

/** A tool call while it streams in: its id, name and arguments so far, and Gemini's signature. */
interface PendingCall {
  id: string;
  name: string;
  args: string;
  signature: string;
}

/**
 * What one streamed Chat Completions turn has said so far. A tool call
 * arrives in pieces keyed by its index (its id and name in the first, the
 * arguments spread over the rest), so the calls are only complete at the end.
 */
class ChatTurn {
  inputTokens = 0;
  cachedInputTokens = 0;
  outputTokens = 0;
  reason: string | null = null;
  done = false;
  private readonly pending = new Map<number, PendingCall>();
  private readonly cited = new Set<string>();
  private fresh: AiSource[] = [];

  /** Takes one chunk in; answers its text, if it carried any. */
  apply(chunk: Record<string, unknown>): string {
    const usage = asRecord(chunk.usage);
    if (chunk.usage) {
      this.inputTokens = asCount(usage.prompt_tokens);
      this.cachedInputTokens = asCount(asRecord(usage.prompt_tokens_details).cached_tokens);
      this.outputTokens = asCount(usage.completion_tokens);
    }
    const choice = asRecord(Array.isArray(chunk.choices) ? chunk.choices[0] : undefined);
    const finish = asText(choice.finish_reason);
    if (finish) this.reason = finish;
    const delta = asRecord(choice.delta);
    // OpenRouter's web plugin names the pages it read as URL annotations of the message.
    const annotations: unknown[] = Array.isArray(delta.annotations) ? delta.annotations : [];
    for (const raw of annotations) {
      const annotation = asRecord(raw);
      const cite = asRecord(annotation.url_citation);
      const url = asText(cite.url);
      if (annotation.type !== 'url_citation' || !/^https?:\/\//.test(url) || this.cited.has(url)) continue;
      this.cited.add(url);
      this.fresh.push({ url, title: asText(cite.title) || url });
    }
    const calls: unknown[] = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
    calls.forEach((raw, position) => {
      const piece = asRecord(raw);
      const index = typeof piece.index === 'number' ? piece.index : position;
      const fn = asRecord(piece.function);
      const call = this.pending.get(index) ?? { id: '', name: '', args: '', signature: '' };
      call.id ||= asText(piece.id);
      call.name ||= asText(fn.name);
      call.args += asText(fn.arguments);
      call.signature ||= thoughtSignatureOf(piece);
      this.pending.set(index, call);
    });
    return asText(delta.content);
  }

  /** The pages cited since the last ask, each once. */
  newSources(): AiSource[] {
    const out = this.fresh;
    this.fresh = [];
    return out;
  }

  calls(): AiToolCall[] {
    return this.named().map(([index, call]) => ({
      id: callId(index, call.id),
      name: call.name,
      args: parseToolArgs(call.args),
    }));
  }

  /** The thought signature of each signed call, by the id the call goes back with. */
  signatures(): Record<string, string> {
    return Object.fromEntries(
      this.named()
        .filter(([, call]) => call.signature)
        .map(([index, call]) => [callId(index, call.id), call.signature]),
    );
  }

  private named(): [number, PendingCall][] {
    return [...this.pending.entries()].sort(([a], [b]) => a - b).filter(([, call]) => call.name);
  }

  finishReason(): AiFinishReason {
    if (this.calls().length > 0) return 'tool-calls';
    return (this.reason && FINISH_REASONS[this.reason]) || 'stop';
  }
}