DEV Community

shashank ms
shashank ms

Posted on

LLMs for Physics Research: A Primer

We are going to build a lightweight physics research assistant that reads raw LaTeX paper snippets, extracts key equations, checks dimensional consistency, and suggests follow-up context. This helps graduate students and researchers quickly triage papers without opening a full PDF stack. The whole thing runs against Oxlo.ai's flat per-request pricing, so a long multi-equation prompt costs the same as a one-line query.

What you'll need

Step 1: Initialize the Oxlo.ai client

I always start by verifying the connection. This snippet imports the SDK, points it at Oxlo.ai, and sends a short health check to Llama 3.3 70B.

from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[
        {"role": "user", "content": "Say 'Physics engine ready' and nothing else."}
    ],
    max_tokens=10
)

print(response.choices[0].message.content)

Step 2: Lock in the system prompt

The system prompt is the only bit of prompt engineering in the whole project. It forces JSON output and defines the exact schema we need for literature triage.

SYSTEM_PROMPT = """You are a physics research assistant. Your job is to analyze a raw LaTeX snippet from a physics paper and produce a structured JSON object with exactly these keys:

- summary: a one-sentence summary of the physical claim.
- equations: a list of each equation found, rewritten in clean LaTeX.
- quantities: a list of physical quantities mentioned, with their SI units if known.
- dimensional_check: a brief note on whether the left and right sides of each main equation appear dimensionally consistent.
- follow_up: one concrete question or experiment that would test the claim.

Rules:
- Output ONLY valid JSON. No markdown fences, no commentary.
- Be concise. Use standard physics notation.
- If units are ambiguous, state 'dimensionless' or 'unspecified'."""

Step 3: Build the JSON analysis function

Now we wrap the API call in a helper that accepts a raw snippet and returns parsed JSON. Oxlo.ai supports JSON mode on compatible models, so we set response_format to enforce valid output.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")

def analyze_physics_snippet(latex_snippet: str, model: str = "llama-3.3-70b"):
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": latex_snippet},
        ],
        response_format={"type": "json_object"},
        temperature=0.2,
        max_tokens=2048
    )
    
    raw = response.choices[0].message.content
    return json.loads(raw)

Step 4: Add a batch helper for multiple excerpts

Real literature reviews involve comparing several snippets. This loop runs each excerpt through the analyzer and collates the results. Because Oxlo.ai uses request-based pricing, five long LaTeX blocks cost the same as five short ones, which matters when you are processing entire appendix sections.

def batch_analyze(snippets: list[str], model: str = "llama-3.3-70b"):
    results = []
    for idx, snippet in enumerate(snippets, 1):
        print(f"Processing snippet {idx}/{len(snippets)}...")
        result = analyze_physics_snippet(snippet, model=model)
        result["id"] = idx
        results.append(result)
    return results

# Example usage with two short excerpts
snippets = [
    r"""The Lagrangian density for a scalar field $\phi$ is given by
    $\mathcal{L} = \frac{1}{2}\partial_\mu \phi \partial^\mu \phi - \frac{1}{2}m^2\phi^2$.
    The equation of motion follows from the Euler-Lagrange equations.""",
    
    r"""We propose a modified Friedmann equation:
    $H^2 = \frac{8\pi G}{3}\rho + \frac{\Lambda}{3}$,
    where $H$ is the Hubble parameter, $\rho$ is the energy density, and $\Lambda$ is the cosmological constant."""
]

findings = batch_analyze(snippets)
print(json.dumps(findings, indent=2))

Step 5: Pretty-print a lab notebook report

Raw JSON is fine for pipelines, but humans need a readable report. This formatter turns the structured output into a short summary suitable for a lab notebook.

def print_triage_report(findings: list[dict]):
    for f in findings:
        print(f"\n--- Finding {f['id']} ---")
        print(f"Summary: {f['summary']}")
        print("Equations:")
        for eq in f.get("equations", []):
            print(f"  - ${eq}$")
        print("Quantities:")
        for q in f.get("quantities", []):
            print(f"  - {q}")
        print(f"Dimensional check: {f.get('dimensional_check', 'N/A')}")
        print(f"Follow-up: {f.get('follow_up', 'N/A')}")

print_triage_report(findings)

Run it

Save the script as physics_agent.py, set your key, and run it.

export OXLO_API_KEY="sk-oxlo.ai-..."
python physics_agent.py

With the example snippets above, you should see output similar to this:

Processing snippet 1/2...
Processing snippet 2/2...

--- Finding 1 ---
Summary: The Lagrangian density for a real scalar field is constructed from kinetic and mass terms.
Equations:
  - $\mathcal{L} = \frac{1}{2}\partial_\mu \phi \partial^\mu \phi - \frac{1}{2}m^2\phi^2$
Quantities:
  - $\mathcal{L}$: Lagrangian density (J/m^3 or unspecified)
  - $\phi$: scalar field (unspecified)
  - $m$: mass (kg)
Dimensional check: The kinetic term has dimensions of [energy density] and the mass term has dimensions of [mass]^2[field]^2; consistency depends on natural units convention.
Follow-up: Derive the Klein-Gordon equation from this Lagrangian and verify the dispersion relation $\omega^2 = k^2 + m^2$.

--- Finding 2 ---
Summary: A modified Friedmann equation includes the standard matter density term and the cosmological constant.
Equations:
  - $H^2 = \frac{8\pi G}{3}\rho + \frac{\Lambda}{3}$
Quantities:
  - $H$: Hubble parameter (s^-1)
  - $G$: gravitational constant (m^3 kg^-1 s^-2)
  - $\rho$: energy density (J m^-3)
  - $\Lambda$: cosmological constant (m^-2)
Dimensional check: Both terms on the right have dimensions of s^-2, matching H^2.
Follow-up: Measure the current expansion rate $H_0$ using Cepheid variables and compare against the Planck 2018 value.

Wrap-up and next steps

This agent gives you a reproducible way to turn raw LaTeX into structured notes. Two concrete ways to extend it:

  • Wire the batch_analyze helper into an arXiv RSS fetcher so it runs on new papers automatically.
  • Swap the model to deepseek-v3.2 or qwen-3-32b for heavier symbolic reasoning, or use kimi-k2.6 if you want to analyze paper figures through the vision pipeline.

Top comments (0)