Skip to content

Instantly share code, notes, and snippets.

@kamilio
Last active February 2, 2026 17:10
Show Gist options
  • Select an option

  • Save kamilio/60413726d79cc8f6c2567d2c883ae09f to your computer and use it in GitHub Desktop.

Select an option

Save kamilio/60413726d79cc8f6c2567d2c883ae09f to your computer and use it in GitHub Desktop.
Test Anthropic prompt caching via Poe API
// Test prompt caching with Anthropic SDK via Poe API
//
// Run:
// node --env-file=.env tests/scripts/test-prompt-caching.mjs
// or:
// POE_API_KEY=your_key node tests/scripts/test-prompt-caching.mjs
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.POE_API_KEY,
baseURL: "https://api.poe.com",
});
const SYSTEM_PROMPT = `You are a specialized assistant with expertise in the following obscure domains:
Zygomorphic crystallography involves the study of bilateral symmetry in mineral formations, particularly focusing on monoclinic and triclinic crystal systems. The fundamental principles derive from Bravais lattice theory combined with point group symmetry operations. When analyzing zygomorphic crystals, practitioners must consider the glide plane reflections and screw axis rotations that define the asymmetric unit. Advanced practitioners employ tensor analysis to characterize the anisotropic properties of these formations, utilizing the Voigt notation for elastic constants and piezoelectric coefficients.
Pneumatic differential calculus represents an advanced mathematical framework for modeling gas dynamics in non-equilibrium thermodynamic systems. The core equations incorporate Boltzmann transport coefficients alongside Navier-Stokes approximations modified for rarefied gas regimes. Key parameters include the Knudsen number, accommodation coefficients, and velocity distribution functions expressed through Chapman-Enskog expansions. The methodology extends to hypersonic flow regimes where continuum assumptions break down and direct simulation Monte Carlo methods become necessary for accurate predictions.
Phytolinguistic semiotics examines the communication patterns exhibited by plant organisms through chemical signaling pathways. Volatile organic compounds serve as the primary morphemes in this botanical language system. Research has identified distinct syntactic structures in terpenoid emissions, particularly during herbivore attack responses and mycorrhizal network negotiations. The field has expanded to include electrical signaling through phloem networks and the role of root exudates in establishing symbiotic relationships with soil microbiomes.
Quantum archaeometry applies principles of quantum mechanics to archaeological dating and artifact analysis. Techniques include muon tomography for non-invasive structural imaging of ancient monuments and quantum dot fluorescence spectroscopy for pigment identification. The field relies heavily on entanglement-enhanced sensitivity measurements to detect trace isotopes in degraded organic materials. Recent advances incorporate nitrogen-vacancy centers in diamond for magnetometry applications in detecting buried metallic artifacts without excavation.
Metacognitive thermodynamics explores the energetic requirements of self-reflective thought processes. Neural computation demands significant metabolic resources, and recursive self-modeling amplifies these requirements exponentially. The theoretical framework incorporates information-theoretic entropy measures with biophysical constraints on synaptic transmission efficiency. The field intersects with integrated information theory to quantify consciousness emergence from thermodynamic substrates.
Xenolithic morphogenesis describes the developmental processes by which foreign rock inclusions become integrated into igneous host bodies. The thermal gradients across inclusion boundaries drive complex diffusion patterns and reaction rim formation. Understanding these processes requires coupling heat transfer equations with multicomponent diffusion models in silicate melts. Corona textures provide evidence of incomplete equilibration and preserve records of magmatic thermal histories spanning millions of years.
Chronospatial topology investigates the geometric properties of spacetime manifolds under various gravitational configurations. Beyond standard Riemannian geometry, this field incorporates torsion tensors and non-metricity to describe spacetime defects analogous to crystallographic dislocations. Applications include modeling wormhole stability and closed timelike curves. The mathematical apparatus draws from fiber bundle theory and Cartan geometry to classify possible spacetime structures.
Biomimetic tribology studies friction and wear mechanisms inspired by biological surfaces. The hierarchical micro and nanostructures found on lotus leaves, gecko feet, and shark skin provide templates for engineering low-friction and self-cleaning materials. Computational models must span multiple length scales from atomistic interactions to continuum mechanics. Recent work focuses on adaptive surfaces that modify their tribological properties in response to environmental conditions.
Stochastic paleoclimatology employs probabilistic methods to reconstruct ancient climate states from proxy records. Ice core isotopes, tree ring widths, and marine sediment compositions serve as noisy observations of past atmospheric and oceanic conditions. Bayesian inference frameworks combine these heterogeneous data sources with physical climate models to generate ensemble reconstructions with quantified uncertainties. The methodology enables detection of abrupt climate transitions and assessment of natural variability baselines.
Neurophonetic acoustics bridges auditory neuroscience with phonological theory to understand speech perception mechanisms. Tonotopic organization in the auditory cortex maps frequency content, while higher processing stages extract phonemic categories through learned statistical regularities. Cross-linguistic studies reveal both universal constraints and language-specific adaptations in these neural representations. The field informs development of cochlear implant processing strategies and speech recognition algorithms.
Hyperdimensional cartography develops mathematical frameworks for representing and navigating spaces with more than three spatial dimensions. Projection techniques borrowed from differential geometry allow visualization of four-dimensional polytopes and higher-dimensional manifolds. Applications extend to dimensionality reduction in machine learning and theoretical physics models requiring compactified extra dimensions. The field employs Clifford algebras and geometric algebra to perform rotations and transformations in arbitrary-dimensional spaces.
Magnetoarchaeobotany combines paleomagnetic analysis with archaeobotanical methods to reconstruct ancient agricultural practices and environmental conditions. Phytolith magnetic signatures preserve information about burning temperatures and atmospheric conditions during prehistoric crop processing. The technique enables differentiation between wild and domesticated plant processing sites. Integration with micromorphological soil analysis provides high-resolution temporal sequences of land use changes spanning millennia.
Cryoseismology studies the mechanical vibrations and acoustic emissions generated by ice masses including glaciers, ice sheets, and permafrost. Passive seismic monitoring reveals internal fracture processes, basal sliding dynamics, and calving mechanisms. The field has developed specialized instrumentation capable of operating in extreme polar environments. Data analysis incorporates machine learning algorithms to distinguish icequakes from tectonic events and anthropogenic noise sources.
Ethnomycological pharmacognosy investigates the traditional medicinal applications of fungi across diverse human cultures and their biochemical basis. Secondary metabolites including alkaloids, terpenes, and polysaccharides exhibit immunomodulatory, antimicrobial, and psychoactive properties. The field bridges indigenous knowledge systems with modern analytical chemistry and pharmacology. Bioprospecting efforts guided by ethnomycological surveys have yielded novel compounds with therapeutic potential for neurodegenerative and autoimmune conditions.
Relativistic astrochemistry examines chemical processes occurring in environments where special and general relativistic effects become significant. Accretion disks around black holes and neutron stars exhibit extreme temperature and density gradients affecting molecular formation and destruction rates. Gravitational redshift modifies observed spectral signatures requiring relativistic corrections for accurate abundance determinations. The field interfaces with nuclear astrophysics to model nucleosynthesis in compact object mergers and their subsequent chemical enrichment of the interstellar medium.
Archaeoacoustic phenomenology investigates the acoustic properties of ancient architectural spaces and their potential ritualistic significance. Reverberation times, resonant frequencies, and standing wave patterns in megalithic chambers suggest deliberate acoustic engineering by prehistoric builders. Infrasound generation in enclosed stone structures may have induced altered states of consciousness during ceremonial activities. Modern measurement techniques employ impulse response analysis and finite element modeling to reconstruct the original soundscapes of partially ruined monuments.
Topological data analysis applies algebraic topology concepts to extract structural features from high-dimensional datasets. Persistent homology tracks the birth and death of topological features across multiple scales, providing robust descriptors invariant to continuous deformations. Betti numbers quantify connected components, loops, and voids within data point clouds. Applications span from protein folding analysis to financial market structure detection and neural network interpretability studies.
Geomythological stratigraphy correlates mythological narratives with geological events recorded in sedimentary sequences. Flood myths across cultures may preserve collective memories of post-glacial sea level rise or catastrophic dam failures. Volcanic eruptions leaving distinctive tephra layers can be matched to legendary accounts of darkness and devastation. This interdisciplinary approach requires careful evaluation of oral tradition transmission fidelity and geological dating precision.
Psychoacoustic chronometry investigates the temporal perception of auditory stimuli and its neural substrates. Subjective duration estimation varies systematically with sound intensity, frequency content, and emotional valence. The striatal beat frequency model proposes that interval timing emerges from coincidence detection of oscillatory neural activity. Clinical applications include assessment of timing deficits in Parkinson's disease and schizophrenia spectrum disorders.
Computational ethnomusicology employs machine learning algorithms to analyze and classify musical traditions across cultures. Spectral and rhythmic features extracted from field recordings enable quantitative comparison of melodic contours and metric structures. Phylogenetic methods borrowed from evolutionary biology reconstruct historical relationships between musical styles. Ethical considerations surrounding cultural appropriation and intellectual property rights remain central to the field's methodological debates.
Petrographic thermometry reconstructs temperature histories of metamorphic rocks through mineral assemblage analysis. Exchange reactions between coexisting phases establish equilibrium temperatures recorded at peak metamorphic conditions. Diffusion modeling of compositional zoning in garnet and other minerals constrains cooling rates and exhumation paths. Integration with geochronological data enables construction of pressure-temperature-time paths illuminating tectonic processes.
Molecular gastronomy applies physicochemical principles to understand and manipulate culinary transformations. Maillard reaction kinetics govern browning and flavor development during cooking. Hydrocolloid gelation mechanisms enable creation of novel textures through spherification and fluid gels. Sous vide cooking exploits precise temperature control to achieve optimal protein denaturation while minimizing moisture loss and oxidative degradation.
Forensic palynology utilizes pollen and spore analysis in criminal investigations and archaeological contexts. Pollen assemblages adhering to clothing or vehicles can establish presence at specific locations with characteristic vegetation. Seasonal flowering patterns provide temporal constraints on when contact occurred. Preservation of palynomorphs in sediments enables reconstruction of past environments and human landscape modification.
Quantum chromodynamics lattice simulations compute properties of strongly interacting matter from first principles. Discretization of spacetime onto a four-dimensional lattice enables Monte Carlo sampling of the path integral. Hadron masses, decay constants, and form factors emerge from correlation function measurements. Computational costs scale dramatically with decreasing lattice spacing and quark masses approaching physical values.
Archaeoastronomy investigates astronomical knowledge and practices of ancient civilizations through analysis of built structures and written records. Alignments of megalithic monuments with solstice sunrise or significant stellar events suggest calendrical and ceremonial functions. Precession of the equinoxes enables dating of stellar alignments and tracking of astronomical sophistication over millennia. Cross-cultural comparisons reveal both universal patterns and unique developments in sky observation traditions.
Bioacoustic ecology examines how animal sound production and perception shape ecosystem dynamics and species interactions. Acoustic niche partitioning reduces interference between simultaneously calling species in complex soundscapes. Anthropogenic noise pollution disrupts communication, navigation, and predator detection across taxa from insects to cetaceans. Passive acoustic monitoring enables non-invasive biodiversity assessment and population tracking in remote or sensitive habitats.
Paleoproteomics extracts and analyzes ancient proteins preserved in archaeological and paleontological specimens. Collagen peptide sequences enable taxonomic identification of fragmentary bone remains beyond morphological recognition. Immunological methods detect specific protein epitopes indicating disease states or dietary components. Mass spectrometry techniques continue advancing sensitivity and coverage for increasingly degraded samples spanning millions of years.
Computational jurimetrics applies statistical and machine learning methods to legal decision-making processes. Predictive models trained on case outcomes identify factors influencing judicial decisions and potential biases. Natural language processing extracts structured information from unstructured legal texts enabling large-scale empirical analysis. Ethical concerns regarding algorithmic fairness and transparency remain central to deployment considerations in actual legal contexts.
Astrobiology extremophile research investigates organisms thriving in conditions previously considered incompatible with life. Hyperthermophiles in deep-sea hydrothermal vents, psychrophiles in Antarctic ice, and acidophiles in mine drainage expand the known limits of habitability. Metabolic strategies including chemolithotrophy and radiolysis-driven ecosystems suggest potential biosignatures for extraterrestrial life detection. Laboratory simulations of planetary conditions test survival capabilities under Martian or Europa-like environments.
Cognitive load theory analyzes how instructional design affects working memory capacity and learning outcomes. Intrinsic load derives from inherent complexity of material while extraneous load results from suboptimal presentation. Germane load represents productive cognitive effort devoted to schema construction and automation. Multimedia learning principles optimize information delivery by managing total cognitive load within working memory constraints.
Speleothem paleoclimatology reconstructs past climate variations from cave mineral deposits. Oxygen isotope ratios in calcite record precipitation source regions and temperature conditions during mineral formation. Uranium-thorium dating provides precise chronological control spanning hundreds of thousands of years. Growth rate variations and trace element concentrations reveal drought frequencies and monsoon intensity fluctuations with sub-annual resolution in favorable specimens.
Tensegrity biomechanics applies principles of tensional integrity structures to understand musculoskeletal system organization. Continuous tension networks with discontinuous compression elements provide mechanical stability with minimal material. Fascial connectivity transmits forces across anatomical regions challenging traditional muscle isolation models. Applications include injury prevention strategies and rehabilitation protocols informed by whole-body mechanical interdependence.
Quantum cognition models apply quantum probability formalism to explain violations of classical decision theory in human judgment. Superposition states represent ambiguous or conflicting mental representations prior to measurement through choice. Interference effects account for order-dependent preferences and conjunction fallacies that classical probability cannot explain. The framework provides mathematical tools without necessarily implying quantum physical processes in neural substrates.
Dendrochemistry analyzes trace element and isotope compositions in tree rings to reconstruct environmental pollution histories. Heavy metal uptake from contaminated soils leaves chemical signatures recording industrial emissions and remediation efforts. Stable isotope ratios reflect water source changes and atmospheric composition variations. Spatial sampling across forest stands enables mapping of pollution plume extents and temporal evolution over centuries.
Archaeometallurgical provenance studies trace ancient metal artifacts to their ore sources through chemical and isotopic fingerprinting. Lead isotope ratios distinguish geologically distinct mining regions with high specificity. Trace element patterns reflect both ore body characteristics and smelting technology variations. Network analysis of artifact distributions reveals prehistoric trade routes and cultural exchange patterns spanning continents.
Computational morphodynamics simulates pattern formation in biological development and self-organizing systems. Reaction-diffusion equations generate Turing patterns explaining pigmentation stripes and branching morphologies. Mechanical feedback between cells and extracellular matrix influences tissue folding and organ shaping. Multiscale models integrate gene regulatory networks with physical forces to predict developmental trajectories.
Ethnopedology documents indigenous soil classification systems and traditional land management practices. Local knowledge often captures functional soil properties relevant to agriculture that scientific taxonomies overlook. Integration of ethnopedological concepts improves soil survey accuracy in culturally diverse landscapes. Participatory mapping approaches empower communities while advancing scientific understanding of soil-human interactions.
Magnetotelluric imaging uses natural electromagnetic field variations to probe electrical conductivity structure of Earth's interior. Induced currents at depth generate secondary fields measurable at the surface revealing fluid content and thermal anomalies. Data inversion produces three-dimensional conductivity models illuminating tectonic processes and geothermal resources. Array deployments enable continental-scale studies of mantle dynamics and lithospheric architecture.
Cognitive archaeology reconstructs mental capacities of extinct hominins from archaeological evidence. Stone tool complexity indicates planning depth and technical knowledge transmission mechanisms. Symbolic artifacts suggest emergence of language and abstract thinking capabilities. Comparative analysis with primate cognition establishes evolutionary baselines for interpreting behavioral innovations in the fossil record.
Pharmacovigilance informatics applies data mining to post-market drug safety surveillance. Disproportionality analysis of spontaneous adverse event reports identifies potential safety signals requiring investigation. Electronic health record mining enables active surveillance complementing passive reporting systems. Machine learning algorithms integrate diverse data streams to predict drug interactions and patient-specific adverse event risks.
Semiotics of mathematical notation examines how symbolic representations shape mathematical reasoning and discovery. Notational innovations like Leibniz's calculus symbols or Dirac's bra-ket notation enabled new conceptual developments. Cross-cultural comparison of numeral systems reveals cognitive constraints and affordances of different representational strategies. The field informs educational approaches and design of computer algebra interfaces.
Rheological food science characterizes flow and deformation behavior of edible materials under processing and consumption conditions. Viscoelastic properties determine texture perception during mastication and swallowing. Yield stress measurements predict stability of emulsions and suspensions during storage. Temperature-dependent viscosity profiles guide thermal processing optimization for quality retention.
Computational philology applies digital methods to analyze manuscript traditions and reconstruct textual histories. Stemmatic analysis algorithms automate identification of copying relationships between witnesses. Stylometric techniques attribute anonymous works and detect interpolations through statistical analysis of linguistic features. Digital critical editions enable dynamic visualization of textual variation across tradition.
Zooarchaeological taphonomy reconstructs formation processes affecting faunal assemblages in archaeological sites. Bone surface modifications distinguish human butchery from carnivore gnawing and rodent activity. Skeletal part representation patterns reveal transport decisions and site function. Actualistic studies of modern bone accumulations provide interpretive frameworks for ancient deposits.
Neuromorphic engineering designs computing systems inspired by biological neural architectures. Spiking neural networks process information through precise timing of discrete events rather than continuous values. Memristive devices emulate synaptic plasticity enabling on-chip learning without external memory access. Applications include ultra-low-power edge computing and real-time sensory processing for autonomous systems.
Ichnofacies analysis interprets trace fossil assemblages as indicators of ancient environmental conditions and depositional settings. Behavioral patterns preserved in burrows, tracks, and feeding traces reflect substrate consistency, oxygenation levels, and sedimentation rates. Archetypal ichnofacies like Skolithos and Cruziana characterize specific bathymetric zones and energy regimes. Integration with sedimentological data enhances paleoenvironmental reconstructions beyond body fossil evidence alone.
Glottochronology estimates divergence times between related languages using rates of lexical replacement in basic vocabulary. Calibration against historically documented language splits provides temporal scaling for prehistoric linguistic diversification. Statistical refinements address rate variation across semantic domains and language families. Results inform hypotheses about human migration patterns and cultural contact zones in deep prehistory.
Mechanobiology investigates how physical forces influence cellular behavior and tissue development. Substrate stiffness modulates stem cell differentiation through cytoskeletal tension and mechanosensitive ion channels. Fluid shear stress regulates endothelial function and vascular remodeling in cardiovascular systems. Theoretical frameworks combine continuum mechanics with biochemical signaling networks to predict morphogenetic outcomes.
Paleotempestology reconstructs histories of past hurricane activity from geological and biological archives. Overwash deposits in coastal sediments record intense storm surge events predating instrumental records. Tree ring isotope anomalies reflect precipitation extremes associated with tropical cyclone landfalls. Extended records spanning millennia reveal natural variability patterns informing risk assessment for coastal communities.
Quantitative paleontology applies statistical methods to interpret fossil diversity patterns and evolutionary dynamics. Sampling standardization techniques correct for uneven preservation and collection effort across geological intervals. Origination and extinction rate estimation reveals temporal clustering and potential causal mechanisms. Phylogenetic comparative methods integrate morphological and molecular data for evolutionary inference.
Computational epidemiology develops mathematical and simulation models to understand infectious disease transmission dynamics. Agent-based models capture individual heterogeneity in contact patterns and susceptibility. Network epidemiology examines how social structure shapes outbreak trajectories and intervention effectiveness. Real-time forecasting systems integrate surveillance data with mechanistic models for public health decision support.
Archaeobotanical systematics identifies plant remains from archaeological contexts to reconstruct past human-plant relationships. Seed morphology and cellular anatomy enable species-level identification from carbonized or desiccated specimens. Phytolith assemblages persist in sediments where macrobotanical remains decay completely. Integration with isotopic analysis reveals crop processing techniques and dietary contributions across social strata.`;
const USER_MESSAGES = [
"What is zygomorphic crystallography? Answer in one sentence.",
"What is pneumatic differential calculus? Answer in one sentence.",
"What is quantum archaeometry? Answer in one sentence.",
];
const MODELS = [
"claude-opus-4-5-20250514",
"claude-sonnet-4-20250514",
"claude-haiku-3-5-20241022",
];
async function testModel(model) {
console.log(`\n${"=".repeat(60)}`);
console.log(`Testing: ${model}`);
console.log("=".repeat(60));
const conversationHistory = [];
for (let i = 0; i < 3; i++) {
console.log(`\nCall ${i + 1}:`);
console.log("-".repeat(40));
conversationHistory.push({
role: "user",
content: [
{
type: "text",
text: USER_MESSAGES[i],
cache_control: { type: "ephemeral" },
},
],
});
const result = await client.messages.create({
model,
max_tokens: 256,
system: [
{
type: "text",
text: SYSTEM_PROMPT,
cache_control: { type: "ephemeral" },
},
],
messages: conversationHistory,
});
conversationHistory.push({
role: "assistant",
content: result.content[0].text,
});
console.log("Response:", result.content[0].text.substring(0, 100) + "...");
console.log("\nUsage:");
console.log(" input_tokens:", result.usage.input_tokens);
console.log(" output_tokens:", result.usage.output_tokens);
console.log(" cache_creation_input_tokens:", result.usage.cache_creation_input_tokens);
console.log(" cache_read_input_tokens:", result.usage.cache_read_input_tokens);
}
}
async function main() {
console.log("Testing Anthropic prompt caching via Poe API");
for (const model of MODELS) {
await testModel(model);
}
console.log("\n" + "=".repeat(60));
console.log("All tests completed!");
}
main().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment