File size: 4,199 Bytes
3f76ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837e3ac
3f76ff4
 
 
 
 
 
837e3ac
3f76ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837e3ac
 
 
3f76ff4
 
 
 
 
 
 
 
 
837e3ac
 
 
 
 
 
 
 
 
 
 
3f76ff4
 
837e3ac
3f76ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  isAnthropicCompatibleBaseUrl,
  normalizeLlmConfig,
  type LlmConfig,
} from "./llm-config";
import { compactTracePreview } from "./chat-trace";

export type LlmCallResult = {
  text: string;
  endpoint: string;
  requestPreview: string;
  responsePreview: string;
};

function extractJsonText(value: unknown): string | undefined {
  if (typeof value === "string") return value;
  if (Array.isArray(value)) {
    const joined = value
      .map((item) => {
        if (typeof item === "string") return item;
        if (
          item &&
          typeof item === "object" &&
          "type" in item &&
          "text" in item &&
          item.type === "text" &&
          typeof item.text === "string"
        ) {
          return item.text;
        }
        return "";
      })
      .filter(Boolean)
      .join("\n");
    return joined || undefined;
  }
  return undefined;
}

function extractOpenAiText(payload: unknown): string | undefined {
  const data = payload as
    | {
        choices?: Array<{
          message?: { content?: unknown };
          text?: unknown;
        }>;
      }
    | undefined;

  const choice = data?.choices?.[0];
  return extractJsonText(choice?.message?.content) ?? extractJsonText(choice?.text);
}

function extractAnthropicText(payload: unknown): string | undefined {
  const data = payload as
    | {
        content?: Array<{
          type?: string;
          text?: string;
        }>;
      }
    | undefined;

  return data?.content
    ?.filter((item) => item.type === "text" && typeof item.text === "string")
    .map((item) => item.text)
    .join("\n");
}

export async function generateLlmText(args: {
  config: LlmConfig;
  systemPrompt: string;
  userPrompt: string;
  temperature?: number;
  maxTokens?: number;
  responseFormat?: "json_object";
}): Promise<LlmCallResult> {
  const { systemPrompt, userPrompt } = args;
  const config = normalizeLlmConfig(args.config);
  const temperature = args.temperature ?? 0.2;
  const maxTokens = args.maxTokens ?? 2200;
  const anthropicStyle = isAnthropicCompatibleBaseUrl(config.baseUrl);
  const responseFormat = args.responseFormat;

  const endpoint = anthropicStyle
    ? `${config.baseUrl}/v1/messages`
    : `${config.baseUrl}/chat/completions`;

  const response = await fetch(endpoint, {
    method: "POST",
    headers: anthropicStyle
      ? {
          "content-type": "application/json",
          "x-api-key": config.apiKey,
          "anthropic-version": "2023-06-01",
        }
      : {
          "content-type": "application/json",
          authorization: `Bearer ${config.apiKey}`,
        },
    body: JSON.stringify(
      anthropicStyle
        ? {
            model: config.model,
            max_tokens: maxTokens,
            temperature,
            system: systemPrompt,
            messages: [
              {
                role: "user",
                content: [
                  {
                    type: "text",
                    text: userPrompt,
                  },
                ],
              },
            ],
          }
        : {
            model: config.model,
            temperature,
            messages: [
              { role: "system", content: systemPrompt },
              { role: "user", content: userPrompt },
            ],
            ...(responseFormat
              ? { response_format: { type: responseFormat } }
              : {}),
          },
    ),
  });

  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new Error(`LLM request failed (${response.status}): ${text}`.slice(0, 1200));
  }

  const rawText = await response.text();
  let payload: unknown = null;

  if (rawText.trim()) {
    try {
      payload = JSON.parse(rawText);
    } catch {
      payload = null;
    }
  }

  const text = anthropicStyle
    ? extractAnthropicText(payload)
    : extractOpenAiText(payload) ?? rawText.trim();

  if (!text) {
    throw new Error("LLM returned an empty response.");
  }

  return {
    text,
    endpoint,
    requestPreview: compactTracePreview(
      `SYSTEM:\n${systemPrompt}\n\nUSER:\n${userPrompt}`,
    ),
    responsePreview: compactTracePreview(text),
  };
}