Update dependencies, enhance AI integration, and improve email content
Some checks failed
Deploy / deploy (push) Failing after 1h35m43s
Some checks failed
Deploy / deploy (push) Failing after 1h35m43s
- Added @google/genai dependency for enhanced AI capabilities. - Updated CI workflow to include new environment variables for AI integration. - Refactored AI client to support multiple providers and improved key management. - Enhanced email templates for better user engagement and clarity. - Updated error handling in AI-related functions to provide clearer feedback. - Made various improvements to the application structure and code clarity.
This commit is contained in:
158
src/lib/ai/cagri.ts
Normal file
158
src/lib/ai/cagri.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { z } from "zod";
|
||||
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
|
||||
import { ThinkingLevel } from "@google/genai";
|
||||
import {
|
||||
getAnthropic,
|
||||
getGemini,
|
||||
raporModeli,
|
||||
saglayici,
|
||||
sohbetModeli,
|
||||
} from "./client";
|
||||
|
||||
/**
|
||||
* Sağlayıcıdan bağımsız AI çağrı katmanı. Anthropic ve Gemini'nin SDK'ları
|
||||
* yapılandırılmış çıktı ve stream için farklı şekiller kullanıyor; rapor ve
|
||||
* sohbet kodu bu farkı görmesin diye tek arayüz burada toplanıyor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gemini JSON Schema'nın yalnızca bir alt kümesini destekliyor; zod'un ürettiği
|
||||
* $schema ve additionalProperties alanları isteği reddettiriyor, ayıklanıyor.
|
||||
*/
|
||||
function geminiSemasi(sema: z.ZodType): unknown {
|
||||
const temizle = (dugum: unknown): unknown => {
|
||||
if (Array.isArray(dugum)) return dugum.map(temizle);
|
||||
if (dugum && typeof dugum === "object") {
|
||||
const cikti: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(dugum as Record<string, unknown>)) {
|
||||
if (k === "$schema" || k === "additionalProperties") continue;
|
||||
cikti[k] = temizle(v);
|
||||
}
|
||||
return cikti;
|
||||
}
|
||||
return dugum;
|
||||
};
|
||||
return temizle(z.toJSONSchema(sema));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemini ücretsiz katmanı yoğunlukta 503/429 döndürüyor; bu geçici hatalarda
|
||||
* artan bekleme ile yeniden dene. Kalıcı hatalar (400, 403) olduğu gibi fırlar.
|
||||
*/
|
||||
const GECICI_KODLAR = new Set([429, 500, 502, 503, 504]);
|
||||
|
||||
async function geciciHatadaTekrarla<T>(
|
||||
islem: () => Promise<T>,
|
||||
denemeSayisi = 3,
|
||||
): Promise<T> {
|
||||
let sonHata: unknown;
|
||||
for (let i = 0; i < denemeSayisi; i++) {
|
||||
try {
|
||||
return await islem();
|
||||
} catch (hata) {
|
||||
const kod = (hata as { status?: number })?.status;
|
||||
if (kod == null || !GECICI_KODLAR.has(kod) || i === denemeSayisi - 1) {
|
||||
throw hata;
|
||||
}
|
||||
sonHata = hata;
|
||||
await new Promise((r) => setTimeout(r, 2000 * 2 ** i));
|
||||
}
|
||||
}
|
||||
throw sonHata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Şemaya uyan tek seferlik çıktı üretir. Şemaya uymayan yanıtta null döner
|
||||
* (çağıran taraf yeniden dener).
|
||||
*/
|
||||
export async function yapilandirilmisUret<T extends z.ZodType>(opts: {
|
||||
system: string;
|
||||
kullanici: string;
|
||||
sema: T;
|
||||
maxTokens: number;
|
||||
}): Promise<z.infer<T> | null> {
|
||||
if (saglayici() === "gemini") {
|
||||
const yanit = await geciciHatadaTekrarla(() =>
|
||||
getGemini().models.generateContent({
|
||||
model: raporModeli(),
|
||||
contents: opts.kullanici,
|
||||
config: {
|
||||
systemInstruction: opts.system,
|
||||
maxOutputTokens: opts.maxTokens,
|
||||
responseMimeType: "application/json",
|
||||
responseJsonSchema: geminiSemasi(opts.sema),
|
||||
thinkingConfig: { thinkingLevel: ThinkingLevel.HIGH },
|
||||
},
|
||||
}),
|
||||
);
|
||||
const metin = yanit.text;
|
||||
if (!metin) return null;
|
||||
try {
|
||||
const parsed = opts.sema.safeParse(JSON.parse(metin));
|
||||
return parsed.success ? parsed.data : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const yanit = await getAnthropic().messages.parse({
|
||||
model: raporModeli(),
|
||||
max_tokens: opts.maxTokens,
|
||||
thinking: { type: "adaptive" },
|
||||
system: opts.system,
|
||||
messages: [{ role: "user", content: opts.kullanici }],
|
||||
output_config: { format: zodOutputFormat(opts.sema) },
|
||||
});
|
||||
return yanit.parsed_output ?? null;
|
||||
}
|
||||
|
||||
export type SohbetMesaji = { role: "user" | "assistant"; content: string };
|
||||
|
||||
/**
|
||||
* Sohbet yanıtını parça parça üretir. Sağlayıcıya bakmaksızın düz metin
|
||||
* parçaları yield eder; çağıran taraf hem stream'ler hem biriktirip kaydeder.
|
||||
*/
|
||||
export async function* sohbetAkisi(opts: {
|
||||
system: string;
|
||||
mesajlar: SohbetMesaji[];
|
||||
maxTokens: number;
|
||||
}): AsyncGenerator<string> {
|
||||
if (saglayici() === "gemini") {
|
||||
const akis = await geciciHatadaTekrarla(() =>
|
||||
getGemini().models.generateContentStream({
|
||||
model: sohbetModeli(),
|
||||
contents: opts.mesajlar.map((m) => ({
|
||||
// Gemini "assistant" yerine "model" rolünü kullanır
|
||||
role: m.role === "assistant" ? "model" : "user",
|
||||
parts: [{ text: m.content }],
|
||||
})),
|
||||
config: {
|
||||
systemInstruction: opts.system,
|
||||
maxOutputTokens: opts.maxTokens,
|
||||
// Sohbet kısa ve hızlı olmalı; uzun düşünme adayı bekletiyor
|
||||
thinkingConfig: { thinkingLevel: ThinkingLevel.LOW },
|
||||
},
|
||||
}),
|
||||
);
|
||||
for await (const parca of akis) {
|
||||
const metin = parca.text;
|
||||
if (metin) yield metin;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const akis = getAnthropic().messages.stream({
|
||||
model: sohbetModeli(),
|
||||
max_tokens: opts.maxTokens,
|
||||
system: opts.system,
|
||||
messages: opts.mesajlar,
|
||||
});
|
||||
for await (const olay of akis) {
|
||||
if (
|
||||
olay.type === "content_block_delta" &&
|
||||
olay.delta.type === "text_delta"
|
||||
) {
|
||||
yield olay.delta.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user