Skip to content

About

Building a simple ReACT agent for (querying medical articles using pubmed) from scratch to enhance self understanding....πŸ˜ƒ

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

7 Commits

Folders and files

Repository files navigation

The Agent's Architectural Diagram

A ReAct-style research agent that answers biomedical questions by searching PubMed, reading abstracts, and opening open-access full text from PubMed Central. It streams every step (its reasoning, each tool call and each result) to a web UI as it happens, then writes a cited answer.

1. Logical flow

The agent loops between reasoning and tool use until it has enough evidence to answer.

agentflow-beta TB
  question[/"User question"/]
  connector ncbi["NCBI PubMed and PMC"]

  flow agent["PubMed research agent"]@{ model: "your OpenRouter model" }
    reason["Reason"]@{ instruction: "Decide whether to search, read abstracts, open full text, or answer." }
    search["Search PubMed"]@{ instruction: "Call search_pubmed and collect matching PMIDs." }
    abstracts["Read abstracts"]@{ instruction: "Call fetch_pubmed_articles for the PMIDs." }
    needfull{"Abstract enough?"}
    fulltext["Open full text"]@{ instruction: "Call fetch_full_text for articles with a pmcid." }
    enough{"Enough evidence?"}
    answer["Write answer"]@{ instruction: "Summarise in Markdown and cite PMIDs." }

    reason --> search --> abstracts --> needfull
    needfull -->|no| fulltext
    needfull -->|yes| enough
    fulltext --> enough
    enough -->|need more| reason
    enough -->|yes| answer
  end

  question --> agent
  search -.- ncbi
  abstracts -.- ncbi
  fulltext -.- ncbi
Loading

Figure 1: Agent's logical flow until a response

agentflow-beta is a beta Mermaid diagram type. If your viewer doesn't render Figure 1, the other diagrams below use standard Mermaid and show the same system.

In ReAct terms, the text the model writes before a tool call is its Thought, the tool call is the Action, and the tool's result, fed back to the model, is the Observation.

2. System components

How the pieces of the project connect.

flowchart LR
    subgraph Browser
        UI["Web UI<br/>web/index.html"]
    end

    subgraph Server["FastAPI server (server.py)"]
        API["POST /api/ask<br/>Server-Sent Events"]
        DISP["QueueDisplay<br/>event queue"]
    end

    subgraph Core["Agent core"]
        AG["PubMedAgent<br/>agent/agent.py"]
        UT["System prompt and tool schemas<br/>utilities/utility.py"]
        RT["run_tool dispatcher<br/>tools/pubmed_tools.py"]
    end

    LLM["LLM via OpenRouter<br/>Anthropic-compatible API"]
    NCBI[("NCBI E-utilities<br/>and PMC BioC")]

    UI -- question --> API
    API --> AG
    UT -.-> AG
    AG -- messages and tool schemas --> LLM
    LLM -- thought and tool call --> AG
    AG -- tool name and args --> RT
    RT --> NCBI
    NCBI --> RT
    RT -- result or error --> AG
    AG -- step, text, tool_call, observation --> DISP
    DISP -- SSE events --> UI
Loading

Figure 2: Components and the data that flows between them

3. One request, end to end

sequenceDiagram
    actor User
    participant UI as Web UI
    participant S as FastAPI server
    participant A as PubMedAgent
    participant L as LLM (OpenRouter)
    participant T as PubMed tools
    participant N as NCBI APIs

    User->>UI: Ask a question
    UI->>S: POST /api/ask
    S->>A: run_agent(QueueDisplay) in a background thread
    loop up to 10 iterations
        A->>L: messages and tool schemas (streamed)
        L-->>A: thought text and tool call
        A-->>UI: step, text, tool_call events
        A->>T: run_tool(name, args)
        T->>N: HTTPS request
        N-->>T: JSON or XML
        T-->>A: result, or an error as data
        A-->>UI: observation event
    end
    L-->>A: final answer (no tool call)
    A-->>UI: text, then done
    UI-->>User: Answer rendered as Markdown
Loading

Figure 3: Sequence of one question, with streaming

4. Tools

Tool Input Returns Notes
search_pubmed query, max_results (1 to 100) { count, pmids } Results are sorted by relevance.
fetch_pubmed_articles pmids (list) List of { pmid, title, abstract, authors, journal, publication_date, doi, pmcid } Requests are batched in groups of 100. An empty pmcid means no PMC full text.
fetch_full_text identifier (PMCID preferred, or PMID), max_chars { identifier, document_id, sections, full_text, truncated }, or null Open-access articles only. full_text is cut to 20,000 characters by default.

All tools run through run_tool, which catches any exception and returns it as { "error": ... }. A failed call becomes an observation the model can react to, not a crash.

5. Project structure

SimpleReactAgent/
β”œβ”€β”€ .env                      # secrets, never commit
β”œβ”€β”€ test_offline.py           # offline tests (mocked network)
└── src/
    └── simplereactagent/
        β”œβ”€β”€ server.py         # FastAPI app, SSE streaming
        β”œβ”€β”€ web/
        β”‚   └── index.html    # single-file chat UI
        β”œβ”€β”€ agent/
        β”‚   └── agent.py      # PubMedAgent loop, ConsoleDisplay
        β”œβ”€β”€ tools/
        β”‚   └── pubmed_tools.py   # three PubMed/PMC tools + run_tool
        └── utilities/
            └── utility.py    # system prompt and tool schemas

6. Setup

Install the dependencies in your virtual environment, just hit a sync. (Install uv if needed):

uv sync

Create a .env file in the project root:

Variable Required Purpose
OPENROUTER_API_KEY Yes Your OpenRouter key.
OPENROUTER_BASE_URL No Defaults to https://openrouter.ai/api. Values ending in /v1 or missing /api are corrected automatically.
AGENT_MODEL No Overrides the default model for the web UI.
NCBI_API_KEY No Raises the NCBI rate limit from 3 to 10 requests per second.

Add .env and .venv/ to .gitignore before you commit.

7. Running

Run both commands from the src folder.

# Web UI at http://127.0.0.1:8000
uvicorn simplereactagent.server:app --reload

# Console only
python -m simplereactagent.agent.agent

8. Design notes and limits

  • Iteration cap: the loop stops after 10 iterations and reports that it hit the limit.
  • Output limit: each model call is capped at 4,096 tokens. If a response is cut off, the UI says so.
  • No memory between questions: every question starts a fresh conversation.
  • Full text is limited: only open-access articles in PubMed Central have it. The agent falls back to abstracts.
  • Model support: OpenRouter's Anthropic-compatible endpoint is built for Anthropic models. Other models, especially free ones, may not support tool calling through it. So look into the model card.
  • Stop button: it ends the stream in the browser, but the server thread finishes its current model call.
  • Security: keep API keys in .env. If a key is ever committed, revoke it and create a new one.

About

Building a simple ReACT agent for (querying medical articles using pubmed) from scratch to enhance self understanding....πŸ˜ƒ

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages