import { ToolLoopAgent, tool, createAgentUIStreamResponse } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'
import { z } from 'zod'
import { getSession } from '@/lib/session'
// Sample ViewDefinition — customize columns or create additional
// ViewDefinitions for other resource types (Coverage, Observation, etc.)
const claimsView = {
resourceType: 'ViewDefinition',
name: 'claims_summary',
status: 'active',
resource: 'ExplanationOfBenefit',
select: [{
column: [
{ name: 'claim_id', path: 'id' },
{ name: 'type', path: "type.coding.where(system='http://terminology.hl7.org/CodeSystem/claim-type').code.first()" },
{ name: 'service_date', path: 'billablePeriod.start' },
{ name: 'provider', path: 'provider.display' },
{ name: 'total_billed', path: "total.where(category.coding.code='submitted').amount.value.first()" },
{ name: 'you_paid', path: "total.where(category.coding.code='memberliability').amount.value.first()" },
{ name: 'diagnosis_codes', path: 'diagnosis.diagnosisCodeableConcept.coding.code.distinct()', collection: true },
// Add more columns as needed — see the parsing guide for FHIRPath examples
]
}]
}
async function runViewDefinition(
accessToken: string,
viewDefinition: Record<string, unknown>,
) {
const response = await fetch(
'https://api.flexpa.com/fhir/ViewDefinition/$run',
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
resourceType: 'Parameters',
parameter: [{ name: 'viewResource', resource: viewDefinition }],
}),
},
)
if (!response.ok) {
const errorText = await response.text()
console.error(
`ViewDefinition/$run failed (${response.status}):`,
errorText,
)
return { error: `API returned ${response.status}`, details: errorText }
}
return response.json()
}
export async function POST(req: Request) {
const session = await getSession()
if (!session?.accessToken) {
return new Response('Unauthorized', { status: 401 })
}
const { messages } = await req.json()
const agent = new ToolLoopAgent({
model: anthropic('claude-sonnet-4-6'),
instructions: 'You are a helpful health records assistant. Answer questions about the patient\'s health records. Be concise and translate medical jargon into plain language.',
tools: {
search_records: tool({
description: 'Search the patient\'s health records',
inputSchema: z.object({}),
execute: async () => runViewDefinition(session.accessToken, claimsView),
}),
},
})
return createAgentUIStreamResponse({
agent,
uiMessages: messages,
})
}