CSV fix again

This commit is contained in:
2026-05-11 23:34:57 -04:00
parent aa8a2b9475
commit 70cd0d6015
+3 -32
View File
@@ -41,16 +41,11 @@ const MODEL = process.env.ANTHROPIC_MODEL || 'claude-sonnet-4-5'
// File uploaded to the Anthropic Console / Files API that the agent should
// consult on every call.
const KNOWLEDGE_FILE_ID =
process.env.ANTHROPIC_KNOWLEDGE_FILE_ID || 'file_011Cawv1SPNaknuMmyDtM1S7'
process.env.ANTHROPIC_KNOWLEDGE_FILE_ID || 'file_011CawyAEnxwp1oXg79g2Fjx'
// ---------------------------------------------------------------------------
// Module-scoped singletons (reused across warm Lambda invocations)
// Anthropic client (reused across warm Lambda invocations)
// ---------------------------------------------------------------------------
// Netlify keeps the function process alive between invocations as long as it
// stays warm, so anything declared at module scope persists. We lazily build
// the Anthropic client and download the knowledge file exactly once per
// cold start, then reuse them for the lifetime of the container.
let _client
function getClient() {
if (_client) return _client
@@ -65,22 +60,6 @@ function getClient() {
return _client
}
// Cache the in-flight promise so concurrent requests during a cold start
// share a single download instead of fetching the CSV N times.
let _knowledgeFilePromise
function loadKnowledgeFile() {
if (_knowledgeFilePromise) return _knowledgeFilePromise
_knowledgeFilePromise = (async () => {
const resp = await getClient().beta.files.download(KNOWLEDGE_FILE_ID)
return await resp.text()
})().catch((err) => {
// Reset on failure so the next request can retry.
_knowledgeFilePromise = undefined
throw err
})
return _knowledgeFilePromise
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
@@ -112,12 +91,8 @@ export default async (req /*, context */) => {
}
let client
let knowledgeFileText
try {
client = getClient()
// First call after a cold start awaits the download; subsequent calls
// resolve immediately from the cached promise.
knowledgeFileText = await loadKnowledgeFile()
} catch (err) {
return new Response(
`Failed to initialize agent: ${err.message || err}`,
@@ -150,11 +125,7 @@ Please draft the funding outlook brief described in your instructions.`
content: [
{
type: 'document',
source: {
type: 'text',
media_type: 'text/plain',
data: knowledgeFileText,
},
source: { type: 'file', file_id: KNOWLEDGE_FILE_ID },
title: 'Funder knowledge base (CSV)',
citations: { enabled: true },
// Cache the tokenized CSV on Anthropic's side for ~5 minutes