Skip to content
openevidence-sdk-patterns logo

OpenEvidence SDK Patterns

openevidence-sdk-patterns

OpenEvidence SDK patterns and best practices for clinical AI integration. Use when implementing advanced SDK features, optimizing API usage, or following clinical decision support best practices. Trigger with phrases like "openevidence patterns", "openevidence best practices", "openevidence sdk",...

SKILL.md

Full skill instructions

OpenEvidence SDK Patterns

Overview

Best practices and design patterns for building production clinical decision support with OpenEvidence.

Prerequisites

  • Completed openevidence-install-auth setup
  • Understanding of async/​await patterns
  • Familiarity with clinical workflows

Core Patterns

Pattern 1: Client Singleton with Dependency Injection

// src/​openevidence/​client-factory.ts
import { OpenEvidenceClient } from '@openevidence/​sdk';

export interface OpenEvidenceConfig {
  apiKey: string;
  orgId: string;
  baseUrl?: string;
  timeout?: number;
  retries?: number;
}

export class OpenEvidenceClientFactory {
  private static instance: OpenEvidenceClient;
  private static config: OpenEvidenceConfig;

  static configure(config: OpenEvidenceConfig): void {
    this.config = config;
    this.instance = null!; // Reset on reconfigure
  }

  static getClient(): OpenEvidenceClient {
    if (!this.instance) {
      if (!this.config) {
        throw new Error('OpenEvidence client not configured. Call configure() first.');
      }
      this.instance = new OpenEvidenceClient(this.config);
    }
    return this.instance;
  }

  // For testing
  static setClient(client: OpenEvidenceClient): void {
    this.instance = client;
  }
}

Pattern 2: Typed Clinical Queries

// src/​openevidence/​types.ts
export type ClinicalSpecialty =
  | 'internal-medicine'
  | 'emergency-medicine'
  | 'cardiology'
  | 'oncology'
  | 'neurology'
  | 'pediatrics'
  | 'psychiatry'
  | 'surgery'
  | 'family-medicine'
  | 'pharmacology';

export type QueryUrgency = 'stat' | 'urgent' | 'routine' | 'research';

export interface ClinicalContext {
  specialty: ClinicalSpecialty;
  urgency: QueryUrgency;
  patientAge?: number;
  patientSex?: 'male' | 'female' | 'other';
  relevantConditions?: string[];
  currentMedications?: string[];
}

export interface QueryOptions {
  maxCitations?: number;
  includeGuidelines?: boolean;
  includeDrugInfo?: boolean;
  preferredSources?: string[];
}

export interface TypedClinicalQuery {
  question: string;
  context: ClinicalContext;
  options?: QueryOptions;
}

Pattern 3: Query Builder Pattern

// src/​openevidence/​query-builder.ts
import { TypedClinicalQuery, ClinicalContext, QueryOptions } from './​types';

export class ClinicalQueryBuilder {
  private query: Partial<TypedClinicalQuery> = {};

  question(q: string): this {
    this.query.question = q;
    return this;
  }

  specialty(s: ClinicalContext['specialty']): this {
    this.query.context = { ...this.query.context, specialty: s } as ClinicalContext;
    return this;
  }

  urgency(u: ClinicalContext['urgency']): this {
    this.query.context = { ...this.query.context, urgency: u } as ClinicalContext;
    return this;
  }

  withPatient(age: number, sex: 'male' | 'female' | 'other'): this {
    this.query.context = {
      ...this.query.context,
      patientAge: age,
      patientSex: sex,
    } as ClinicalContext;
    return this;
  }

  withConditions(conditions: string[]): this {
    this.query.context = {
      ...this.query.context,
      relevantConditions: conditions,
    } as ClinicalContext;
    return this;
  }

  withMedications(meds: string[]): this {
    this.query.context = {
      ...this.query.context,
      currentMedications: meds,
    } as ClinicalContext;
    return this;
  }

  maxCitations(n: number): this {
    this.query.options = { ...this.query.options, maxCitations: n };
    return this;
  }

  includeGuidelines(): this {
    this.query.options = { ...this.query.options, includeGuidelines: true };
    return this;
  }

  build(): TypedClinicalQuery {
    if (!this.query.question) throw new Error('Question is required');
    if (!this.query.context?.specialty) throw new Error('Specialty is required');
    if (!this.query.context?.urgency) throw new Error('Urgency is required');

    return this.query as TypedClinicalQuery;
  }
}

// Usage
const query = new ClinicalQueryBuilder()
  .question('What is the recommended statin dosing for secondary prevention?')
  .specialty('cardiology')
  .urgency('routine')
  .withPatient(65, 'male')
  .withConditions(['prior MI', 'hyperlipidemia'])
  .includeGuidelines()
  .maxCitations(5)
  .build();

Pattern 4: Response Transformer

// src/​openevidence/​response-transformer.ts
interface RawOpenEvidenceResponse {
  answer: string;
  citations: any[];
  confidence: number;
  raw_data: any;
}

export interface FormattedClinicalAnswer {
  summary: string;
  detailedAnswer: string;
  keyPoints: string[];
  evidence: {
    source: string;
    strength: 'high' | 'moderate' | 'low';
    year: number;
  }[];
  confidence: {
    score: number;
    level: 'high' | 'moderate' | 'low';
  };
  disclaimer: string;
}

export function transformResponse(raw: RawOpenEvidenceResponse): FormattedClinicalAnswer {
  const keyPoints = extractKeyPoints(raw.answer);

  return {
    summary: raw.answer.split('.')[0] + '.',
    detailedAnswer: raw.answer,
    keyPoints,
    evidence: raw.citations.map(c => ({
      source: c.source,
      strength: determineEvidenceStrength(c),
      year: c.year,
    })),
    confidence: {
      score: raw.confidence,
      level: raw.confidence > 0.9 ? 'high' : raw.confidence > 0.7 ? 'moderate' : 'low',
    },
    disclaimer: 'Clinical answers are for informational purposes. Always verify with current guidelines.',
  };
}

function extractKeyPoints(answer: string): string[] {
  // Extract bullet points or numbered items from the answer
  const lines = answer.split('\n');
  return lines
    .filter(l => /^[-•*\d]/​.test(l.trim()))
    .map(l => l.replace(/^[-•*\d.)\]]+\s*/, '').trim())
    .filter(l => l.length > 0);
}

function determineEvidenceStrength(citation: any): 'high' | 'moderate' | 'low' {
  const highImpactSources = ['NEJM', 'JAMA', 'Lancet', 'BMJ', 'NCCN'];
  if (highImpactSources.some(s => citation.source?.includes(s))) return 'high';
  if (citation.year >= new Date().getFullYear() - 2) return 'moderate';
  return 'low';
}

Pattern 5: Caching Strategy

// src/​openevidence/​cache.ts
import { createHash } from 'crypto';

interface CacheEntry<T> {
  data: T;
  timestamp: number;
  ttl: number;
}

export class ClinicalQueryCache {
  private cache = new Map<string, CacheEntry<any>>();
  private defaultTTL = 3600000; // 1 hour for clinical data

  private generateKey(query: any): string {
    const normalized = JSON.stringify(query, Object.keys(query).sort());
    return createHash('sha256').update(normalized).digest('hex');
  }

  get<T>(query: any): T | null {
    const key = this.generateKey(query);
    const entry = this.cache.get(key);

    if (!entry) return null;

    if (Date.now() - entry.timestamp > entry.ttl) {
      this.cache.delete(key);
      return null;
    }

    return entry.data as T;
  }

  set<T>(query: any, data: T, ttl?: number): void {
    const key = this.generateKey(query);
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      ttl: ttl || this.defaultTTL,
    });
  }

  invalidate(query: any): void {
    const key = this.generateKey(query);
    this.cache.delete(key);
  }

  clear(): void {
    this.cache.clear();
  }
}

Output

  • Typed client factory with DI support
  • Query builder for complex clinical queries
  • Response transformer for consistent output
  • Caching layer for performance

Error Handling

PatternUse CaseBenefit
SingletonSingle client instanceMemory efficiency
BuilderComplex queriesType safety, readability
TransformerResponse normalizationConsistent UI layer
CacheRepeated queriesReduced API calls, latency

Examples

Complete Service Implementation

// src/​services/​clinical-evidence.ts
import { OpenEvidenceClientFactory } from '../​openevidence/​client-factory';
import { ClinicalQueryBuilder } from '../​openevidence/​query-builder';
import { transformResponse, FormattedClinicalAnswer } from '../​openevidence/​response-transformer';
import { ClinicalQueryCache } from '../​openevidence/​cache';

const cache = new ClinicalQueryCache();

export async function getClinicalEvidence(
  question: string,
  specialty: string,
  options?: { useCache?: boolean }
): Promise<FormattedClinicalAnswer> {
  const query = new ClinicalQueryBuilder()
    .question(question)
    .specialty(specialty as any)
    .urgency('routine')
    .includeGuidelines()
    .build();

  // Check cache first
  if (options?.useCache !== false) {
    const cached = cache.get<FormattedClinicalAnswer>(query);
    if (cached) return cached;
  }

  // Query API
  const client = OpenEvidenceClientFactory.getClient();
  const response = await client.query(query);

  // Transform and cache
  const formatted = transformResponse(response);
  cache.set(query, formatted);

  return formatted;
}

Resources

Next Steps

For core clinical query workflow, see openevidence-core-workflow-a.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View