Skip to content

Connect drchrono to AI Agents: Manage Billing and Medical Records

Sidharth Verma Sidharth Verma 9 min read AI & Agents
TrutoFor teams building AI agents

Give your AI agent drchrono tools.

Connect drchrono to your AI agent framework using Truto's /tools endpoint. Bypass custom integration builds, manage clinical workflows, and properly handle API rate limits.

In this guide

  1. 01Fetch Tools
  2. 02Bind Tools
  3. 03Implement Retry Logic
  4. 04Orchestrate Workflows

The guide

Learn how to connect drchrono to AI agents using Truto. Bind medical and billing API tools to LangChain, handle rate limits, and automate clinical workflows.

You want to connect drchrono to an AI agent so your system can independently lookup patient records, manage medical billing, generate lab orders, and update clinical notes based on historical context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build a custom Electronic Health Record (EHR) integration from scratch.

Giving a Large Language Model (LLM) read and write access to your drchrono instance is an engineering headache. You either spend weeks building, securing, and maintaining a custom connector, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting drchrono to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting drchrono to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for drchrono, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex clinical and revenue operations workflows. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.

Why a Unified Tool Layer Matters for Clinical Agents

Before writing a line of integration code, decide what layer your agent talks to. This choice determines how safe and deterministic your production system will be.

Direct API tools - writing one bespoke function per raw drchrono endpoint - look convenient in a quick prototype, but they push provider-specific quirks directly into the LLM's context window. The model has to remember exactly which nested JSON structures drchrono expects, how the specific pagination cursors work, and how to link disparate entities like patients, doctors, and offices. Every one of those quirks is a hallucination waiting to happen.

By leveraging a tool layer, your agent consumes proxy APIs. Truto maps integration schemas into standardized proxy APIs and exposes them as function-calling tools. This gives you several concrete engineering advantages:

  1. Smaller attack surface for hallucination. The LLM chooses from clearly defined function names with strict JSON schemas. Invalid arguments are rejected before they ever hit the EHR.
  2. Isolated authentication. Your agent never sees the OAuth tokens or API keys. The infrastructure layer injects credentials securely at runtime.
  3. Normalized metadata. The agent does not need to learn custom pagination logic for every platform; the tool layer handles structural normalization.

The Engineering Reality of the drchrono API

Giving an LLM access to external EHR data sounds simple. You write a Node.js function that makes a fetch request and wrap it in a tool decorator. In production against complex healthcare systems, this approach collapses.

The drchrono API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent logic, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.

Relational Complexity in Scheduling and Billing

In drchrono, an appointment is not a standalone object. It is a highly relational nexus connecting a patient, a doctor, an office, and an exam_room. When your agent wants to schedule a follow-up, it cannot just send a payload with a timestamp. It must resolve all of these foreign keys first.

Similarly, billing drchrono_line_items requires strict formatting. A line item must include diagnosis_pointers mapping back to specific ICD-10 codes, and a procedure_type. If your agent hallucinates a string instead of an array of diagnosis pointers, the API will reject the payload, and your revenue operations workflow will fail. Strict JSON schemas via a tool layer enforce this structure before the network request is made.

The Immutable Nature of Medical Records

Clinical notes and patient communications are often immutable or require specific amendment workflows for compliance reasons. You cannot simply overwrite a clinical note field if it has been locked. Your agent must understand the difference between creating a new drchrono_amendment and attempting to execute a PUT request on a finalized drchrono_clinical_note_field_value. Exposing these actions as discrete, well-documented tools prevents the agent from attempting illegal state transitions.

The Hard Truth About Rate Limits

drchrono enforces strict rate limits to protect its infrastructure. A common misconception in agent engineering is that the integration platform will magically absorb these limits.

Here is the factual engineering reality: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream drchrono API returns an HTTP 429 (Too Many Requests), Truto passes that error directly to the caller.

However, Truto does normalize the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification. The caller - your agent framework - is entirely responsible for reading these headers, sleeping the thread, and retrying. Do not assume your infrastructure layer will block and wait; you must design your agent loop to handle 429s gracefully.

Hero Tools for AI Agents

Truto exposes drchrono's endpoints as discrete, typed tools. Rather than overwhelming your LLM with the entire API surface area, you should selectively bind only the tools necessary for the workflow. Here are the highest-leverage tools for clinical and billing automation.

list_all_drchrono_patients

Retrieves or searches for patient records. This is the foundational tool for almost every clinical workflow, as you must resolve the patient's internal drchrono ID before taking action on their chart.

"Find the patient ID for Jane Doe, who had her first appointment in 2023. I need her ID to look up her recent lab orders."

create_a_drchrono_appointment

Creates a new appointment on a doctor's calendar. The agent must provide the required foreign keys (office, scheduled_time, doctor, patient, exam_room) to successfully block the time.

"Schedule a follow-up appointment for patient 10456 with Dr. Smith at the Downtown office next Tuesday at 10:00 AM in Exam Room 2."

create_a_drchrono_lab_order

Initiates a lab order so the doctor can track it within drchrono. This tool requires the patient ID, doctor ID, and the specific sublab (vendor) ID.

"Generate a new lab order for patient 10456 under Dr. Smith, sending the requisition to Quest Diagnostics (sublab ID 883)."

list_all_drchrono_line_items

Retrieves billing line items. Crucial for revenue operations agents auditing unpaid balances, checking insurance payouts, or validating diagnosis pointers.

"Fetch all billing line items for appointment 998877 and check if the insurance portion has been marked as paid."

create_a_drchrono_line_item

Generates a new billing line item for an appointment. The agent must format the ICD diagnosis pointers correctly to ensure clean claim submission.

"Add a billing line item for a routine checkup (procedure type CPT) to appointment 998877, pointing to diagnosis code Z00.00."

create_a_drchrono_clinical_note_field_value

Creates a value for a specific field within a clinical note. This allows an agent to automatically draft chart notes based on transcribed audio or patient intake forms.

"Update the clinical note for appointment 998877 by adding the patient's reported blood pressure to the vital signs field."

To view the complete schema definitions and the full list of available tools, visit the drchrono integration page.

Workflows in Action

Individual tools are useful, but chaining them together creates autonomous revenue and clinical operations. Here is how specific personas utilize these tools in production.

1. The Autonomous Front Desk

Front desk staff spend hours coordinating follow-ups. An AI agent can handle scheduling requests via natural language, verifying the correct patient and facility before booking.

"Book John Doe for a 30-minute follow-up with Dr. Smith at the main clinic next Monday morning."

Tool Execution Sequence:

  1. list_all_drchrono_patients - The agent queries the name "John Doe" to extract the primary patient ID.
  2. list_all_drchrono_offices - The agent retrieves the ID for the "main clinic".
  3. list_all_drchrono_appointments - The agent queries Dr. Smith's schedule for next Monday to find an open 30-minute slot.
  4. create_a_drchrono_appointment - The agent executes the booking, mapping all retrieved IDs into the required schema.

Result: The system books the appointment and returns a confirmation to the user, completely bypassing manual data entry.

2. The Medical Billing Auditor

Revenue cycle management requires constant auditing of unbilled appointments. An agent can sweep completed appointments and flag missing line items.

"Check Dr. Smith's completed appointments from yesterday. If any are missing billing line items, draft a standard evaluation charge."

Tool Execution Sequence:

  1. list_all_drchrono_appointments - The agent fetches yesterday's appointments filtered by Dr. Smith's ID and "Complete" status.
  2. list_all_drchrono_line_items - The agent iterates through the appointments, checking for existing billing data.
  3. create_a_drchrono_line_item - For any appointment lacking charges, the agent injects a standard evaluation code using the appointment ID.

Result: The billing pipeline remains watertight, capturing revenue that might have otherwise slipped through the cracks.

3. The Clinical Intake Processor

When patients fill out digital intake forms, that unstructured data needs to end up in specific clinical note fields.

"Take this patient intake summary and update Jane Doe's clinical note for today's visit with her current medications and allergies."

Tool Execution Sequence:

  1. list_all_drchrono_patients - The agent identifies Jane Doe.
  2. list_all_drchrono_appointments - The agent isolates her appointment for today.
  3. create_a_drchrono_clinical_note_field_value - The agent maps the unstructured intake data into the structured note fields.
  4. create_a_drchrono_allergy - The agent distinctly registers any new allergies mentioned in the summary.

Result: The physician walks into the exam room with the chart already populated from the patient's intake form.

Building Multi-Step Workflows

To build a resilient agent, you must construct an execution loop that binds the tools to the LLM, handles tool execution, and strictly manages API rate limits.

Truto exposes proxy APIs via the /tools endpoint. SDKs like the truto-langchainjs-toolset wrap this endpoint, dynamically generating framework-native tools. Because Truto normalizes the rate limit headers, you can build a deterministic retry loop directly into your agent's execution path.

Below is a conceptual architecture demonstrating how to bind Truto tools to an agent and explicitly handle HTTP 429 rate limit responses.

flowchart TD
    A["User Request"] --> B["Agent Orchestrator"]
    B --> C{"Select drchrono Tool"}
    C -->|"execute tool"| D["Truto Proxy API"]
    D -->|"API Request"| E["drchrono Upstream"]
    E -->|"429 Too Many Requests"| D
    D -->|"HTTP 429 + ratelimit-reset"| B
    B -->|"Sleep & Retry"| D
    E -->|"200 OK"| D
    D -->|"Normalized JSON"| B
    B --> F["Final LLM Response"]

Here is how you implement this in TypeScript using LangChain. We isolate the tool execution so that if the upstream drchrono API rate limits the request, our code reads the normalized ratelimit-reset header, pauses execution, and tries again.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { HumanMessage } from "@langchain/core/messages";
 
async function runClinicalAgent(prompt: string) {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({ 
    modelName: "gpt-4-turbo",
    temperature: 0
  });
 
  // 2. Fetch drchrono tools for this specific integrated account
  const toolManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
    accountId: "drchrono_account_id_123"
  });
 
  // Filter for specific tools to optimize context window
  const tools = await toolManager.getTools({
    names: [
      "list_all_drchrono_patients", 
      "create_a_drchrono_appointment",
      "create_a_drchrono_line_item"
    ]
  });
 
  // 3. Bind tools to the model
  const agentWithTools = llm.bindTools(tools);
 
  let messages = [new HumanMessage(prompt)];
  
  // 4. Standard agent execution loop
  while (true) {
    const response = await agentWithTools.invoke(messages);
    messages.push(response);
 
    if (!response.tool_calls || response.tool_calls.length === 0) {
      // The agent has finished reasoning
      console.log("Final Answer:", response.content);
      break;
    }
 
    // 5. Execute tools with rate limit handling
    for (const toolCall of response.tool_calls) {
      const selectedTool = tools.find(t => t.name === toolCall.name);
      if (!selectedTool) continue;
 
      let toolResult;
      let retryCount = 0;
      const maxRetries = 3;
 
      while (retryCount < maxRetries) {
        try {
          // Attempt tool execution
          toolResult = await selectedTool.invoke(toolCall.args);
          break; // Success, break retry loop
        } catch (error: any) {
          // Check if Truto passed through an upstream 429
          if (error.status === 429) {
            // Truto normalizes these headers per IETF spec
            const resetTime = error.headers['ratelimit-reset'];
            const sleepSeconds = resetTime ? 
                Math.max(1, parseInt(resetTime) - Math.floor(Date.now() / 1000)) : 5;
            
            console.warn(`Rate limited by drchrono. Sleeping for ${sleepSeconds}s...`);
            await new Promise(resolve => setTimeout(resolve, sleepSeconds * 1000));
            retryCount++;
          } else {
            // Fail fast on non-rate-limit errors (e.g., 400 Bad Request)
            toolResult = `Error executing tool: ${error.message}`;
            break;
          }
        }
      }
 
      // Pass the result back to the LLM's context
      messages.push({
        role: "tool",
        tool_call_id: toolCall.id,
        name: toolCall.name,
        content: typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult)
      });
    }
  }
}
 
// Execute a workflow
runClinicalAgent("Book John Doe for a follow-up with Dr. Smith next Tuesday.");

This pattern guarantees that your agent remains resilient. By catching the 429 error and explicitly reading Truto's standardized ratelimit-reset header, your system absorbs the API friction without hallucinating or crashing.

Moving to Production

Building an AI agent that integrates with drchrono is not an exercise in prompt engineering; it is an exercise in distributed systems and state management. If you attempt to hand-roll the integration, you will spend your engineering cycles reading API documentation, managing OAuth tokens, normalizing nested healthcare JSON schemas, and fighting with rate limits.

By routing your agent through a unified tool layer, you abstract the connectivity boilerplate. Your LLM interacts with a stable, documented set of functions, and your application code focuses entirely on clinical orchestration and error handling.

Two ways to put drchrono to work

Truto

For product teams

Give your agent drchrono tools

Your customers connect their own drchrono accounts. Your product gets one API and MCP tools for drchrono, through Truto.

FAQ

How do I handle drchrono rate limits with AI agents?
Truto normalizes upstream rate limit headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) but does not retry automatically. Your agent must inspect these headers on a 429 error and apply its own backoff.
Can I limit which drchrono tools the LLM can access?
Yes, you can filter available tools by method type (e.g., read-only) using Truto's /tools endpoint query parameters.
Which agent frameworks are supported?
You can use any framework, including LangChain, LangGraph, CrewAI, or Vercel AI SDK, since Truto tools are exposed as standardized JSON schemas.
d drchronoAI agent tools Get a sandbox

More from our Blog