import Groq from "groq-sdk";
import { validateAgainstSchema } from "./validate.js";
const DEFAULT_MODEL = "llama-3.3-70b-versatile";
async function callGroq(opts, apiKey) {
  const client = new Groq({ apiKey });
  const model = opts.modelOverride ?? DEFAULT_MODEL;
  const start = Date.now();
  const messages = [
    { role: "user", content: buildPrompt(opts.prompt, opts.jsonSchema) }
  ];
  const first = await runOnce(client, model, messages, opts.signal);
  let errors = validateAgainstSchema(first.values, opts.jsonSchema);
  if (errors.length === 0) {
    return done(first.values, first.responseModel ?? model, start);
  }
  messages.push({ role: "assistant", content: first.raw });
  messages.push({ role: "user", content: retryPrompt(errors) });
  const second = await runOnce(client, model, messages, opts.signal);
  errors = validateAgainstSchema(second.values, opts.jsonSchema);
  if (errors.length > 0) {
    throw new Error(
      `groq: response failed schema validation after retry: ${formatErrors(errors)}`
    );
  }
  return done(second.values, second.responseModel ?? model, start);
}
async function runOnce(client, model, messages, signal) {
  const response = await client.chat.completions.create(
    {
      model,
      messages,
      response_format: { type: "json_object" }
    },
    { signal }
  );
  const content = response.choices?.[0]?.message?.content;
  if (!content) {
    throw new Error("groq: empty content in response");
  }
  let values;
  try {
    values = JSON.parse(content);
  } catch (e) {
    throw new Error(`groq: invalid JSON in response: ${e.message}`);
  }
  return { values, raw: content, responseModel: response.model };
}
function buildPrompt(prompt, schema) {
  return `${prompt}

Return JSON matching this schema:
${JSON.stringify(schema)}`;
}
function retryPrompt(errors) {
  return `Your previous response failed schema validation:
${formatErrors(errors)}
Return corrected JSON only.`;
}
function formatErrors(errors) {
  return errors.map((e) => `${e.path}: ${e.message}`).join("; ");
}
function done(values, model, start) {
  return {
    values,
    provider: "groq",
    model,
    cached: false,
    latencyMs: Date.now() - start
  };
}
export {
  callGroq
};
//# sourceMappingURL=groq.js.map