{"id":15039315,"url":"https://github.com/future-house/paper-qa","last_synced_at":"2026-03-04T09:00:45.607Z","repository":{"id":65705091,"uuid":"597583114","full_name":"Future-House/paper-qa","owner":"Future-House","description":"High accuracy RAG for answering questions from scientific documents with citations","archived":false,"fork":false,"pushed_at":"2026-02-27T05:45:02.000Z","size":43847,"stargazers_count":8216,"open_issues_count":131,"forks_count":834,"subscribers_count":63,"default_branch":"main","last_synced_at":"2026-02-27T12:14:58.338Z","etag":null,"topics":["ai","rag","science","search"],"latest_commit_sha":null,"homepage":"https://futurehouse.gitbook.io/futurehouse-cookbook","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Future-House.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-02-05T01:07:25.000Z","updated_at":"2026-02-27T09:56:02.000Z","dependencies_parsed_at":"2023-11-20T00:27:48.752Z","dependency_job_id":"fa3f52cf-a0cb-4d32-8dbc-b4f0743a705e","html_url":"https://github.com/Future-House/paper-qa","commit_stats":{"total_commits":527,"total_committers":29,"mean_commits":18.17241379310345,"dds":0.5920303605313093,"last_synced_commit":"8d768476764282fc825f2fa251c6f2713f5c61e8"},"previous_names":["future-house/paper-qa","whitead/paper-qa"],"tags_count":164,"template":false,"template_full_name":null,"purl":"pkg:github/Future-House/paper-qa","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Future-House%2Fpaper-qa","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Future-House%2Fpaper-qa/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Future-House%2Fpaper-qa/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Future-House%2Fpaper-qa/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Future-House","download_url":"https://codeload.github.com/Future-House/paper-qa/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Future-House%2Fpaper-qa/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30076935,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-04T08:01:56.766Z","status":"ssl_error","status_checked_at":"2026-03-04T08:00:42.919Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","rag","science","search"],"created_at":"2024-09-24T20:42:24.792Z","updated_at":"2026-03-04T09:00:45.597Z","avatar_url":"https://github.com/Future-House.png","language":"Python","funding_links":[],"categories":["📋 Scientific Documentation \u0026 Parsing"],"sub_categories":["Scientific Literature RAG \u0026 Analysis"],"readme":"# PaperQA2\n\n\u003c!-- pyml disable-num-lines 6 line-length --\u003e\n\n[![GitHub](https://img.shields.io/badge/GitHub-black?logo=github\u0026logoColor=white)](https://github.com/Future-House/paper-qa)\n[![PyPI version](https://badge.fury.io/py/paper-qa.svg)](https://badge.fury.io/py/paper-qa)\n[![tests](https://github.com/Future-House/paper-qa/actions/workflows/tests.yml/badge.svg)](https://github.com/Future-House/paper-qa)\n![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)\n![PyPI Python Versions](https://img.shields.io/pypi/pyversions/paper-qa)\n\nPaperQA2 is a package for doing high-accuracy retrieval augmented generation (RAG) on PDFs, text files, Microsoft Office documents, and source code files,\nwith a focus on the scientific literature.\nSee our [recent 2024 paper](https://paper.wikicrow.ai)\nto see examples of PaperQA2's superhuman performance in scientific tasks like\nquestion answering, summarization, and contradiction detection.\n\n\u003c!--TOC--\u003e\n\n---\n\n**Table of Contents**\n\n- [Quickstart](#quickstart)\n  - [Example Output](#example-output)\n- [What is PaperQA2](#what-is-paperqa2)\n  - [PaperQA2 vs PaperQA](#paperqa2-vs-paperqa)\n  - [PaperQA2 Goes CalVer in December 2025](#paperqa2-goes-calver-in-december-2025)\n  - [What's New in Version 5 (aka PaperQA2)?](#whats-new-in-version-5-aka-paperqa2)\n  - [What's New in December 2025?](#whats-new-in-december-2025)\n  - [PaperQA2 Algorithm](#paperqa2-algorithm)\n- [Installation](#installation)\n- [CLI Usage](#cli-usage)\n  - [Bundled Settings](#bundled-settings)\n  - [Rate Limits](#rate-limits)\n- [Library Usage](#library-usage)\n  - [Agentic Adding/Querying Documents](#agentic-addingquerying-documents)\n  - [Manual (No Agent) Adding/Querying Documents](#manual-no-agent-addingquerying-documents)\n  - [Async](#async)\n  - [Choosing Model](#choosing-model)\n    - [Locally Hosted](#locally-hosted)\n  - [Embedding Model](#embedding-model)\n    - [Specifying the Embedding Model](#specifying-the-embedding-model)\n    - [Local Embedding Models (Sentence Transformers)](#local-embedding-models-sentence-transformers)\n  - [Adjusting number of sources](#adjusting-number-of-sources)\n  - [Using Code or HTML](#using-code-or-html)\n  - [Multimodal Support](#multimodal-support)\n  - [Using External DB/Vector DB and Caching](#using-external-dbvector-db-and-caching)\n  - [Creating Index](#creating-index)\n    - [Manifest Files](#manifest-files)\n  - [Reusing Index](#reusing-index)\n  - [Using Clients Directly](#using-clients-directly)\n- [Settings Cheatsheet](#settings-cheatsheet)\n- [Where do I get papers?](#where-do-i-get-papers)\n- [Callbacks](#callbacks)\n  - [Caching Embeddings](#caching-embeddings)\n- [Customizing Prompts](#customizing-prompts)\n  - [Pre and Post Prompts](#pre-and-post-prompts)\n- [FAQ](#faq)\n  - [How come I get different results than your papers?](#how-come-i-get-different-results-than-your-papers)\n  - [How is this different from LlamaIndex or LangChain?](#how-is-this-different-from-llamaindex-or-langchain)\n  - [Can I save or load?](#can-i-save-or-load)\n- [Reproduction](#reproduction)\n- [Citation](#citation)\n\n---\n\n\u003c!--TOC--\u003e\n\n## Quickstart\n\nIn this example we take a folder of research paper PDFs,\nmagically get their metadata - including citation counts with a retraction check,\nthen parse and cache PDFs into a full-text search index,\nand finally answer the user question with an LLM agent.\n\n```bash\npip install paper-qa\nmkdir my_papers\ncurl -o my_papers/PaperQA2.pdf https://arxiv.org/pdf/2409.13740\ncd my_papers\npqa ask 'What is PaperQA2?'\n```\n\n### Example Output\n\nQuestion: Has anyone designed neural networks that compute with proteins or DNA?\n\n\u003e The claim that neural networks have been designed to compute with DNA is supported by multiple sources.\n\u003e The work by Qian, Winfree, and Bruck demonstrates the use of DNA strand displacement cascades\n\u003e to construct neural network components, such as artificial neurons and associative memories,\n\u003e using a DNA-based system (Qian2011Neural pages 1-2, Qian2011Neural pages 15-16, Qian2011Neural pages 54-56).\n\u003e This research includes the implementation of a 3-bit XOR gate and a four-neuron Hopfield associative memory,\n\u003e showcasing the potential of DNA for neural network computation.\n\u003e Additionally, the application of deep learning techniques to genomics,\n\u003e which involves computing with DNA sequences, is well-documented.\n\u003e Studies have applied convolutional neural networks (CNNs) to predict genomic features such as\n\u003e transcription factor binding and DNA accessibility (Eraslan2019Deep pages 4-5, Eraslan2019Deep pages 5-6).\n\u003e These models leverage DNA sequences as input data,\n\u003e effectively using neural networks to compute with DNA.\n\u003e While the provided excerpts do not explicitly mention protein-based neural network computation,\n\u003e they do highlight the use of neural networks in tasks related to protein sequences,\n\u003e such as predicting DNA-protein binding (Zeng2016Convolutional pages 1-2).\n\u003e However, the primary focus remains on DNA-based computation.\n\n## What is PaperQA2\n\nPaperQA2 is engineered to be the best agentic RAG model for working with scientific papers.\nHere are some features:\n\n- A simple interface to get good answers with grounded responses containing in-text citations.\n- State-of-the-art implementation including document metadata-awareness\n  in embeddings and LLM-based re-ranking and contextual summarization (RCS).\n- Support for agentic RAG, where a language agent can iteratively refine queries and answers.\n- Automatic redundant fetching of paper metadata,\n  including citation and journal quality data from multiple providers.\n- A usable full-text search engine for a local repository of PDF/text files.\n- A robust interface for customization, with default support for all [LiteLLM][LiteLLM providers] models.\n\n[LiteLLM providers]: https://docs.litellm.ai/docs/providers\n[LiteLLM general docs]: https://docs.litellm.ai/docs/\n\nBy default, it uses [OpenAI embeddings](https://platform.openai.com/docs/guides/embeddings)\nand [models](https://platform.openai.com/docs/models) with a Numpy vector DB to embed and search documents.\nHowever, you can easily use other closed-source, open-source models or embeddings (see details below).\n\nPaperQA2 depends on some awesome libraries/APIs that make our repo possible.\nHere are some in no particular order:\n\n1. [Semantic Scholar](https://www.semanticscholar.org/)\n2. [Crossref](https://www.crossref.org/)\n3. [Unpaywall](https://unpaywall.org/)\n4. [Pydantic](https://docs.pydantic.dev/latest/)\n5. [tantivy](https://github.com/quickwit-oss/tantivy)\n6. [LiteLLM][LiteLLM general docs]\n7. [pybtex](https://pybtex.org/)\n\n### PaperQA2 vs PaperQA\n\nWe've been working hard on fundamental upgrades for a while\nand mostly followed [SemVer](https://semver.org/), until [December 2025](#paperqa2-goes-calver-in-december-2025).\nMeaning we've incremented the major version number on each breaking change.\nThis brings us to the current major version number v5.\nSo why call is the repo now called PaperQA2?\nWe wanted to remark on the fact though that we've\nexceeded human performance on [many important metrics](https://paper.wikicrow.ai).\nSo we arbitrarily call version 5 and onward PaperQA2,\nand versions before it as PaperQA1 to denote the significant change in performance.\nWe recognize that we are challenged at naming and counting at FutureHouse,\nso we reserve the right at any time to arbitrarily change the name to PaperCrow.\n\n### PaperQA2 Goes CalVer in December 2025\n\nPrior to December 2025 we used [semantic versioning](https://semver.org/).\nThis eventually led to confusion in two ways:\n\n1. Developers: should we major version bump based on\n   settings or fundamental system capabilities?\n   What if a bug fix requires breaking changes to the agent's behaviors?\n2. Speaking: should one use terminology from our publications\n   (e.g. [PaperQA1](https://arxiv.org/abs/2312.07559),\n   [PaperQA2](https://arxiv.org/abs/2409.13740))\n   or the Git tags (e.g. v5) from this repo/package?\n   When someone says \"PaperQA\" -- what version do they mean?\n\nTo resolve these confusions, in December 2025,\nwe moved to [calendar versioning](https://calver.org/).\nThe developer burden is diminished because\nwe're basically removing guarantees of backwards compatibility across releases\n(as CalVer is [ZeroVer](https://0ver.org/) bound to dates).\nIt solves the \"speaking\" issue because Git tags are now\nquite different from publication terminology (e.g. PaperQA2 vs `v2025.12.17`).\nWhen someone says \"PaperQA\" it will just refer to the system,\nnot a particular snapshot of agentic behaviors.\nWhen someone says \"PaperQA2\" it will refer to `paper-qa\u003e=5`,\nwhich applies to both SemVer tags `v5.0.0` and the new CalVer tags `v2025.12.17`.\n\nThis switch is backwards compatible for version 5's SemVer,\nas the year 2025 is strictly greater than major version 5.\n\n### What's New in Version 5 (aka PaperQA2)?\n\nVersion 5 added:\n\n- A CLI `pqa`\n- Agentic workflows invoking tools for\n  paper search, gathering evidence, and generating an answer\n- Removed much of the statefulness from the `Docs` object\n- A migration to LiteLLM for compatibility with many LLM providers\n  as well as centralized rate limits and cost tracking\n- A bundled set of configurations (read [this section here](#bundled-settings)))\n  containing known-good hyperparameters\n\nNote that `Docs` objects pickled from prior versions of `PaperQA` are incompatible with version 5,\nand will need to be rebuilt.\nAlso, our minimum Python version was increased to Python 3.11.\n\n### What's New in December 2025?\n\nThe last four months since version `5.29.1` have seen many changes:\n\n- New modalities: tables, figures, non-English languages, math equations\n- More and better readers\n  - Two new _model-based_ PDF readers: [Docling](packages/paper-qa-docling)\n    and [Nvidia nemotron-parse](packages/paper-qa-nemotron)\n  - All PDF readers now can parse images and tables, report page numbers,\n    support DPI\n  - A reader for Microsoft Office data types\n- Multimodal contextual summarization\n  - Media objects are also passed to the `summary_llm` during creation\n  - Media objects' embedding space is enhanced using an `enrichment_llm` prompt\n- Simpler and performant HTTP stack\n  - Consolidation from `aiohttp` and `httpx` to just `httpx`\n  - Integration with [`httpx-aiohttp`](https://github.com/karpetrosyan/httpx-aiohttp) for performance\n- `Context` relevance is simplified and some assumptions were removed\n- Many minor features such as\n  retrying `Context` creation upon invalid JSON,\n  compatibility with fall 2025's frontier LLMs,\n  and improved prompt templates\n- Multiple fixes in metadata processing via Semantic Scholar and OpenAlex,\n  and metadata processing\n  (e.g. incorrectly inferring identical document IDs for main text and SI)\n- Completed the deprecations accrued over the past year\n\n### PaperQA2 Algorithm\n\nTo understand PaperQA2, let's start with the pieces of the underlying algorithm.\nThe default workflow of PaperQA2 is as follows:\n\n| Phase                  | PaperQA2 Actions                                                          |\n| ---------------------- | ------------------------------------------------------------------------- |\n| **1. Paper Search**    | - Get candidate papers from LLM-generated keyword query                   |\n|                        | - Chunk, embed, and add candidate papers to state                         |\n| **2. Gather Evidence** | - Embed query into vector                                                 |\n|                        | - Rank top _k_ document chunks in current state                           |\n|                        | - Create scored summary of each chunk in the context of the current query |\n|                        | - Use LLM to re-score and select most relevant summaries                  |\n| **3. Generate Answer** | - Put best summaries into prompt with context                             |\n|                        | - Generate answer with prompt                                             |\n\nThe tools can be invoked in any order by a language agent.\nFor example, an LLM agent might do a narrow and broad search,\nor using different phrasing for the gather evidence step from the generate answer step.\n\n## Installation\n\nFor a non-development setup,\ninstall PaperQA2 (aka version 5) from [PyPI](https://pypi.org/project/paper-qa/).\nNote version 5 requires Python 3.11+.\n\n```bash\npip install paper-qa\u003e=5\n```\n\nFor development setup,\nplease refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file.\n\nPaperQA2 uses an LLM to operate,\nso you'll need to either set an appropriate [API key environment variable][LiteLLM providers]\n(i.e. `export OPENAI_API_KEY=sk-...`)\nor set up an open source LLM server (i.e. using [llamafile](https://github.com/Mozilla-Ocho/llamafile).\nAny LiteLLM compatible model can be configured to use with PaperQA2.\n\nIf you need to index a large set of papers (100+),\nyou will likely want an API key for both\n[Crossref](https://www.crossref.org/documentation/metadata-plus/metadata-plus-keys/)\nand [Semantic Scholar](https://www.semanticscholar.org/product/api#api-key),\nwhich will allow you to avoid hitting public rate limits using these metadata services.\nThose can be exported as `CROSSREF_API_KEY` and `SEMANTIC_SCHOLAR_API_KEY` variables.\n\n## CLI Usage\n\nThe fastest way to test PaperQA2 is via the CLI. First navigate to a directory with some papers and use the `pqa` cli:\n\n```bash\npqa ask 'What is PaperQA2?'\n```\n\nYou will see PaperQA2 index your local PDF files,\ngathering the necessary metadata for each of them\n(using [Crossref](https://www.crossref.org/) and [Semantic Scholar](https://www.semanticscholar.org/)),\nsearch over that index, then break the files into chunked evidence contexts,\nrank them, and ultimately generate an answer.\nThe next time this directory is queried,\nyour index will already be built (save for any differences detected, like new added papers),\nso it will skip the indexing and chunking steps.\n\nAll prior answers will be indexed and stored,\nyou can view them by querying via the `search` subcommand,\nor access them yourself in your `PQA_HOME` directory,\nwhich defaults to `~/.pqa/`.\n\n```bash\npqa -i 'answers' search 'ranking and contextual summarization'\n```\n\nPaperQA2 is highly configurable, when running from the command line,\n`pqa --help` shows all options and short descriptions.\nFor example to run with a higher temperature:\n\n```bash\npqa --temperature 0.5 ask 'What is PaperQA2?'\n```\n\nYou can view all settings with `pqa view`.\nAnother useful thing is to change to other templated settings - for example\n`fast` is a setting that answers more quickly\nand you can see it with `pqa -s fast view`\n\nMaybe you have some new settings you want to save? You can do that with\n\n```bash\npqa -s my_new_settings --temperature 0.5 --llm foo-bar-5 save\n```\n\nand then you can use it with\n\n```bash\npqa -s my_new_settings ask 'What is PaperQA2?'\n```\n\nIf you run `pqa` with a command which requires a new indexing,\nsay if you change the default chunk_size,\na new index will automatically be created for you.\n\n```bash\npqa --parsing.chunk_size 5000 ask 'What is PaperQA2?'\n```\n\nYou can also use `pqa` to do full-text search with use of LLMs view the search command.\nFor example, let's save the index from a directory and give it a name:\n\n```bash\npqa -i nanomaterials index\n```\n\nNow I can search for papers about thermoelectrics:\n\n```bash\npqa -i nanomaterials search thermoelectrics\n```\n\nor I can use the normal ask\n\n```bash\npqa -i nanomaterials ask 'Are there nm scale features in thermoelectric materials?'\n```\n\nBoth the CLI and module have pre-configured settings based on prior performance and our publications,\nthey can be invoked as follows:\n\n```bash\npqa --settings \u003csetting name\u003e \\\n    ask 'Are there nm scale features in thermoelectric materials?'\n```\n\n### Bundled Settings\n\nInside [`src/paperqa/configs`](src/paperqa/configs) we bundle known useful settings:\n\n| Setting Name | Description                                                                                                                  |\n| ------------ | ---------------------------------------------------------------------------------------------------------------------------- |\n| high_quality | Highly performant, relatively expensive (due to having `evidence_k` = 15) query using a `ToolSelector` agent.                |\n| fast         | Setting to get answers cheaply and quickly.                                                                                  |\n| wikicrow     | Setting to emulate the Wikipedia article writing used in our WikiCrow publication.                                           |\n| contracrow   | Setting to find contradictions in papers, your query should be a claim that needs to be flagged as a contradiction (or not). |\n| debug        | Setting useful solely for debugging, but not in any actual application beyond debugging.                                     |\n| tier1_limits | Settings that match OpenAI rate limits for each tier, you can use `tier\u003c1-5\u003e_limits` to specify the tier.                    |\n\n### Rate Limits\n\nIf you are hitting rate limits, say with the OpenAI Tier 1 plan, you can add them into PaperQA2.\nFor each OpenAI tier, a pre-built setting exists to limit usage.\n\n```bash\npqa --settings 'tier1_limits' ask 'What is PaperQA2?'\n```\n\nThis will limit your system to use the [tier1_limits](src/paperqa/configs/tier1_limits.json),\nand slow down your queries to accommodate.\n\nYou can also specify them manually with any rate limit string that matches the specification in\nthe [limits](https://limits.readthedocs.io/en/stable/quickstart.html#rate-limit-string-notation) module:\n\n```bash\npqa --summary_llm_config '{\"rate_limit\": {\"gpt-4o-2024-11-20\": \"30000 per 1 minute\"}}' \\\n    ask 'What is PaperQA2?'\n```\n\nOr by adding into a `Settings` object, if calling imperatively:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm_config={\"rate_limit\": {\"gpt-4o-2024-11-20\": \"30000 per 1 minute\"}},\n        summary_llm_config={\"rate_limit\": {\"gpt-4o-2024-11-20\": \"30000 per 1 minute\"}},\n    ),\n)\n```\n\n## Library Usage\n\nPaperQA2's full workflow can be accessed via Python directly:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(temperature=0.5, paper_directory=\"my_papers\"),\n)\n```\n\nPlease see our [installation docs](#installation) for how to install the package from PyPI.\n\n### Agentic Adding/Querying Documents\n\nThe answer object has the following attributes:\n`formatted_answer`, `answer` (answer alone), `question` , and `context` (the summaries of passages found for answer).\n`ask` will use the `SearchPapers` tool, which will query a local index of files,\nyou can specify this location via the `Settings` object:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        temperature=0.5, agent={\"index\": {\"paper_directory\": \"my_papers\"}}\n    ),\n)\n```\n\n`ask` is just a convenience wrapper around the real entrypoint,\nwhich can be accessed if you'd like to run concurrent asynchronous workloads:\n\n```python\nfrom paperqa import Settings, agent_query\n\nanswer_response = await agent_query(\n    query=\"What is PaperQA2?\",\n    settings=Settings(\n        temperature=0.5, agent={\"index\": {\"paper_directory\": \"my_papers\"}}\n    ),\n)\n```\n\nThe default agent will use an LLM based agent,\nbut you can also specify a `\"fake\"` agent to use a hard coded call path of\nsearch -\u003e gather evidence -\u003e answer to reduce token usage.\n\n### Manual (No Agent) Adding/Querying Documents\n\nNormally via agent execution, the agent invokes the search tool,\nwhich adds documents to the `Docs` object for you behind the scenes.\nHowever, if you prefer fine-grained control,\nyou can directly interact with the `Docs` object.\n\nNote that manually adding and querying `Docs` does not impact performance.\nIt just removes the automation associated with an agent picking the documents to add.\n\n```python\nfrom paperqa import Docs, Settings\n\n# valid extensions include .pdf, .txt, .md, .html, .docx, .xlsx, .pptx, and code files (e.g., .py, .ts, .yaml)\ndoc_paths = (\"myfile.pdf\", \"myotherfile.pdf\")\n\n# Prepare the Docs object by adding a bunch of documents\ndocs = Docs()\nfor doc_path in doc_paths:\n    await docs.aadd(doc_path)\n\n# Set up how we want to query the Docs object\nsettings = Settings()\nsettings.llm = \"claude-3-5-sonnet-20240620\"\nsettings.answer.answer_max_sources = 3\n\n# Query the Docs object to get an answer\nsession = await docs.aquery(\"What is PaperQA2?\", settings=settings)\nprint(session)\n```\n\n### Async\n\nPaperQA2 is written to be used asynchronously.\nThe synchronous API is just a wrapper around the async.\nHere are the methods and their `async` equivalents:\n\n| Sync                | Async                |\n| ------------------- | -------------------- |\n| `Docs.add`          | `Docs.aadd`          |\n| `Docs.add_file`     | `Docs.aadd_file`     |\n| `Docs.add_url`      | `Docs.aadd_url`      |\n| `Docs.get_evidence` | `Docs.aget_evidence` |\n| `Docs.query`        | `Docs.aquery`        |\n\nThe synchronous version just calls the async version in a loop.\nMost modern python environments support `async` natively (including Jupyter notebooks!).\nSo you can do this in a Jupyter Notebook:\n\n```python\nimport asyncio\nfrom paperqa import Docs\n\n\nasync def main() -\u003e None:\n    docs = Docs()\n    # valid extensions include .pdf, .txt, .md, .html, .docx, .xlsx, .pptx, and code files (e.g., .py, .ts, .yaml)\n    for doc in (\"myfile.pdf\", \"myotherfile.pdf\"):\n        await docs.aadd(doc)\n\n    session = await docs.aquery(\"What is PaperQA2?\")\n    print(session)\n\n\nasyncio.run(main())\n```\n\n### Choosing Model\n\nBy default, PaperQA2 uses OpenAI's `gpt-4o-2024-11-20` model for the\n`summary_llm`, `llm`, and `agent_llm`.\nPlease see the [Settings Cheatsheet](#settings-cheatsheet)\nfor more information on these settings.\nPaperQA2 also defaults to using OpenAI's `text-embedding-3-small` model for the `embedding` setting.\nIf you don't have an OpenAI API key, you can use a different embedding model.\nMore information about embedding models can be found [in the \"Embedding Model\" section](#embedding-model).\n\nWe use the [`lmi`](https://github.com/Future-House/ldp/tree/main/packages/lmi) package for our LLM interface,\nwhich in turn uses `litellm` to support many LLM providers.\nYou can adjust this easily to use any model supported by `litellm`:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm=\"gpt-4o-mini\", summary_llm=\"gpt-4o-mini\", agent={\"index\": {\"paper_directory\": \"my_papers\"}}\n    ),\n)\n```\n\nTo use Claude, make sure you set the `ANTHROPIC_API_KEY` environment variable.\nIn this example, we also use a different embedding model.\nPlease make sure to `pip install paper-qa[local]` to use a local embedding model.\n\n```python\nfrom paperqa import Settings, ask\nfrom paperqa.settings import AgentSettings\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm=\"claude-3-5-sonnet-20240620\",\n        summary_llm=\"claude-3-5-sonnet-20240620\",\n        agent=AgentSettings(agent_llm=\"claude-3-5-sonnet-20240620\"),\n        # SEE: https://huggingface.co/sentence-transformers/multi-qa-MiniLM-L6-cos-v1\n        embedding=\"st-multi-qa-MiniLM-L6-cos-v1\",\n    ),\n)\n```\n\nOr Gemini, by setting the `GEMINI_API_KEY` from Google AI Studio\n\n```python\nfrom paperqa import Settings, ask\nfrom paperqa.settings import AgentSettings\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm=\"gemini/gemini-2.0-flash\",\n        summary_llm=\"gemini/gemini-2.0-flash\",\n        agent=AgentSettings(agent_llm=\"gemini/gemini-2.0-flash\"),\n        embedding=\"gemini/text-embedding-004\",\n    ),\n)\n```\n\n#### Locally Hosted\n\nYou can use llama.cpp to be the LLM.\nNote that you should be using relatively large models,\nbecause PaperQA2 requires following a lot of instructions.\nYou won't get good performance with 7B models.\n\nThe easiest way to get set-up is to download a [llama file](https://github.com/Mozilla-Ocho/llamafile)\nand execute it with `-cb -np 4 -a my-llm-model --embedding`\nwhich will enable continuous batching and embeddings.\n\n```python\nfrom paperqa import Settings, ask\n\nlocal_llm_config = dict(\n    model_list=[\n        dict(\n            model_name=\"my_llm_model\",\n            litellm_params=dict(\n                model=\"my-llm-model\",\n                api_base=\"http://localhost:8080/v1\",\n                api_key=\"sk-no-key-required\",\n                temperature=0.1,\n                frequency_penalty=1.5,\n                max_tokens=512,\n            ),\n        )\n    ]\n)\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm=\"my-llm-model\",\n        llm_config=local_llm_config,\n        summary_llm=\"my-llm-model\",\n        summary_llm_config=local_llm_config,\n    ),\n)\n```\n\nModels hosted with `ollama` are also supported.\nTo run the example below make sure you have downloaded llama3.2 and mxbai-embed-large via ollama.\n\n```python\nfrom paperqa import Settings, ask\n\nlocal_llm_config = {\n    \"model_list\": [\n        {\n            \"model_name\": \"ollama/llama3.2\",\n            \"litellm_params\": {\n                \"model\": \"ollama/llama3.2\",\n                \"api_base\": \"http://localhost:11434\",\n            },\n        }\n    ]\n}\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(\n        llm=\"ollama/llama3.2\",\n        llm_config=local_llm_config,\n        summary_llm=\"ollama/llama3.2\",\n        summary_llm_config=local_llm_config,\n        embedding=\"ollama/mxbai-embed-large\",\n    ),\n)\n```\n\n### Embedding Model\n\nEmbeddings are used to retrieve k texts (where k is specified via `Settings.answer.evidence_k`)\nfor re-ranking and contextual summarization.\nIf you don't want to use embeddings, but instead just fetch all chunks,\ndisable \"evidence retrieval\" via the `Settings.answer.evidence_retrieval` setting.\n\nPaperQA2 defaults to using OpenAI (`text-embedding-3-small`) embeddings,\nbut has flexible options for both vector stores and embedding choices.\n\n#### Specifying the Embedding Model\n\nThe simplest way to specify the embedding model is via `Settings.embedding`:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(embedding=\"text-embedding-3-large\"),\n)\n```\n\n`embedding` accepts any embedding model name supported by litellm.\nPaperQA2 also supports an embedding input of `\"hybrid-\u003cmodel_name\u003e\"`\ni.e. `\"hybrid-text-embedding-3-small\"` to use a hybrid sparse keyword (based on a token modulo embedding)\nand dense vector embedding, where any litellm model can be used in the dense model name.\n`\"sparse\"` can be used to use a sparse keyword embedding only.\n\nEmbedding models are used to create PaperQA2's index of the full-text embedding vectors (`texts_index` argument).\nThe embedding model can be specified as a setting when you are adding new papers to the `Docs` object:\n\n```python\nfrom paperqa import Docs, Settings\n\ndocs = Docs()\nfor doc in (\"myfile.pdf\", \"myotherfile.pdf\"):\n    await docs.aadd(doc, settings=Settings(embedding=\"text-embedding-large-3\"))\n```\n\nNote that PaperQA2 uses Numpy as a dense vector store.\nIts design of using a keyword search initially reduces the number of chunks\nneeded for each answer to a relatively small number \u003c 1k.\nTherefore, `NumpyVectorStore` is a good place to start, it's a simple in-memory store, without an index.\nHowever, if a larger-than-memory vector store is needed,\nyou can an external vector database like [Qdrant](https://qdrant.tech/) via the `QdrantVectorStore` class.\n\nThe hybrid embeddings can be customized:\n\n```python\nfrom paperqa import (\n    Docs,\n    HybridEmbeddingModel,\n    SparseEmbeddingModel,\n    LiteLLMEmbeddingModel,\n)\n\n\nmodel = HybridEmbeddingModel(\n    models=[LiteLLMEmbeddingModel(), SparseEmbeddingModel(ndim=1024)]\n)\ndocs = Docs()\nfor doc in (\"myfile.pdf\", \"myotherfile.pdf\"):\n    await docs.aadd(doc, embedding_model=model)\n```\n\nThe sparse embedding (keyword) models default to having 256 dimensions,\nbut this can be specified via the `ndim` argument.\n\n#### Local Embedding Models (Sentence Transformers)\n\nYou can use a `SentenceTransformerEmbeddingModel` model if you install `sentence-transformers`,\nwhich is [a local embedding library](https://sbert.net/) with support for HuggingFace models and more.\nYou can install it by adding the `local` extras.\n\n```sh\npip install paper-qa[local]\n```\n\nand then prefix embedding model names with `st-`:\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(embedding=\"st-multi-qa-MiniLM-L6-cos-v1\"),\n)\n```\n\nor with a hybrid model\n\n```python\nfrom paperqa import Settings, ask\n\nanswer_response = ask(\n    \"What is PaperQA2?\",\n    settings=Settings(embedding=\"hybrid-st-multi-qa-MiniLM-L6-cos-v1\"),\n)\n```\n\n### Adjusting number of sources\n\nYou can adjust the numbers of sources (passages of text) to reduce token usage or add more context.\n`k` refers to the top k most relevant and diverse (may from different sources) passages.\nEach passage is sent to the LLM to summarize, or determine if it is irrelevant.\nAfter this step, a limit of `max_sources` is applied so that the final answer can fit into the LLM context window.\nThus, `k` \u003e `max_sources` and `max_sources` is the number of sources used in the final answer.\n\n```python\nfrom paperqa import Settings\n\nsettings = Settings()\nsettings.answer.answer_max_sources = 3\nsettings.answer.evidence_k = 5\n\nawait docs.aquery(\n    \"What is PaperQA2?\",\n    settings=settings,\n)\n```\n\n### Using Code or HTML\n\nYou do not need to use papers -- you can use code or raw HTML.\nNote that this tool is focused on answering questions,\nso it won't do well at writing code.\nOne note is that the tool cannot infer citations from code,\nso you will need to provide them yourself.\n\n```python\nimport glob\nimport os\nfrom paperqa import Docs\n\nsource_files = glob.glob(\"**/*.js\")\n\ndocs = Docs()\nfor f in source_files:\n    # this assumes the file names are unique in code\n    await docs.aadd(\n        f, citation=\"File \" + os.path.basename(f), docname=os.path.basename(f)\n    )\nsession = await docs.aquery(\"Where is the search bar in the header defined?\")\nprint(session)\n```\n\n### Multimodal Support\n\nMultimodal support centers on:\n\n- Standalone images\n- Images or tables in PDFs\n\nThe `Docs` object stores media via a `ParsedMedia` object.\nWhen chunking a document, media are not split at chunk boundaries,\nso it's possible 2+ chunks can correspond with the same media.\nThis means within PaperQA each chunk\nhas a one-to-many relationship between `ParsedMedia` and chunks.\n\nDepending on the source document, the same image can appear multiple times\n(e.g. each page of a PDF has a logo in the margins).\nThus, clients should consider media databases\nto have a many-to-many relationship with chunks.\n\nSince PaperQA's evidence gathering process centers on text-based retrieval,\nit's possible relevant image(s) or table(s) aren't retrieved\nbecause their associated text content is irrelevant.\nFor a concrete example, imagine the figure in a paper has a terse caption\nand is placed one page after relevant main-text discussion.\nTo solve this problem, PaperQA supports media enrichment at document read-time.\nBasically after reading in the PDF,\nthe `parsing.enrichment_llm` is given the `parsing.enrichment_prompt`\nand co-located text to generate a synthetic caption for every image/table.\nThe synthetic captions are used to shift the embeddings of each text chunk,\nbut are kept separate from the actual source text.\nThis way evidence gathering can fetch relevant images/tables\nwithout risk of polluting contextual summaries with LLM-generated captions.\n\nIf you want multimodal PDF reading, but do not want enrichment\n(since adds one LLM prompt/media at read-time),\nenrichment can be disabled by setting `parsing.multimodal` to `ON_WITHOUT_ENRICHMENT`.\n\nWhen creating contextual summaries on a given chunk (a `Text`),\nthe summary LLM is passed both the chunk's text and the chunk's associated media,\nbut the output contextual summary itself remains text-only.\n\nIf you would like,\nspecifying the prompt `paperqa.prompts.summary_json_multimodal_system_prompt`\nto the setting `prompt.summary_json_system`\nwill include a `used_images` flag attributing\nusage of images in any contextual summarizations.\n\n### Using External DB/Vector DB and Caching\n\nYou may want to cache parsed texts and embeddings in an external database or file.\nYou can then build a Docs object from those directly:\n\n```python\nfrom paperqa import Docs, Doc, Text\n\ndocs = Docs()\n\nfor ... in my_docs:\n    doc = Doc(docname=..., citation=..., dockey=..., citation=...)\n    texts = [Text(text=..., name=..., doc=doc) for ... in my_texts]\n    docs.add_texts(texts, doc)\n```\n\n### Creating Index\n\nIndexes will be placed in the [home directory][home dir] by default.\nThis can be controlled via the `PQA_HOME` environment variable.\n\nIndexes are made by reading files in the `IndexSettings.paper_directory`.\nBy default, we recursively read from subdirectories of the paper directory,\nunless disabled using `IndexSettings.recurse_subdirectories`.\nThe paper directory is not modified in any way, it's just read from.\n\n[home dir]: https://docs.python.org/3/library/pathlib.html#pathlib.Path.home\n\n#### Manifest Files\n\nThe indexing process attempts to infer paper metadata like title and DOI\nusing LLM-powered text processing.\nYou can avoid this point of uncertainty using a \"manifest\" file,\nwhich is a CSV containing `DocDetails` fields (order doesn't matter).\nFor example:\n\n- `file_location`: relative path to the paper's PDF within the index directory\n- `doi`: DOI of the paper\n- `title`: title of the paper\n\nBy providing this information,\nwe ensure queries to metadata providers like Crossref are accurate.\n\nTo ease creating a manifest, there is a helper class method `Doc.to_csv`,\nwhich also works when called on `DocDetails`.\n\n### Reusing Index\n\nThe local search indexes are built based on a hash of the current `Settings` object.\nSo make sure you properly specify the `paper_directory` to your `IndexSettings` object.\nIn general, it's advisable to:\n\n1. Pre-build an index given a folder of papers (can take several minutes)\n2. Reuse the index to perform many queries\n\n```python\nimport os\n\nfrom paperqa import Settings\nfrom paperqa.agents.main import agent_query\nfrom paperqa.agents.search import get_directory_index\n\n\nasync def amain(folder_of_papers: str | os.PathLike) -\u003e None:\n    settings = Settings(agent={\"index\": {\"paper_directory\": folder_of_papers}})\n\n    # 1. Build the index. Note an index name is autogenerated when unspecified\n    built_index = await get_directory_index(settings=settings)\n    print(settings.get_index_name())  # Display the autogenerated index name\n    print(await built_index.index_files)  # Display the index contents\n\n    # 2. Use the settings as many times as you want with ask\n    answer_response_1 = await agent_query(\n        query=\"What is a cool retrieval augmented generation technique?\",\n        settings=settings,\n    )\n    answer_response_2 = await agent_query(\n        query=\"What is PaperQA2?\",\n        settings=settings,\n    )\n```\n\n### Using Clients Directly\n\nOne of the most powerful features of PaperQA2 is its ability to combine data from multiple metadata sources.\nFor example, [Unpaywall](https://unpaywall.org/) can provide open access status/direct links to PDFs,\n[Crossref](https://www.crossref.org/) can provide bibtex,\nand [Semantic Scholar](https://www.semanticscholar.org/) can provide citation licenses.\nHere's a short demo of how to do this:\n\n```python\nfrom paperqa.clients import DocMetadataClient, ALL_CLIENTS\n\nclient = DocMetadataClient(metadata_clients=ALL_CLIENTS)\ndetails = await client.query(title=\"Augmenting language models with chemistry tools\")\n\nprint(details.formatted_citation)\n# Andres M. Bran, Sam Cox, Oliver Schilter, Carlo Baldassari,\n# Andrew D. White, and Philippe Schwaller.\n#  Augmenting large language models with chemistry tools. Nature Machine Intelligence,\n# 6:525-535, May 2024. URL: https://doi.org/10.1038/s42256-024-00832-8,\n# doi:10.1038/s42256-024-00832-8.\n# This article has 243 citations and is from a domain leading peer-reviewed journal.\n\nprint(details.citation_count)\n# 243\n\nprint(details.license)\n# cc-by\n\nprint(details.pdf_url)\n# https://www.nature.com/articles/s42256-024-00832-8.pdf\n```\n\nthe `client.query` is meant to check for exact matches of title.\nIt's a bit robust (like to casing, missing a word).\nThere are duplicates for titles though - so you can also add authors to disambiguate.\nOr you can provide a doi directly `client.query(doi=\"10.1038/s42256-024-00832-8\")`.\n\nIf you're doing this at a large scale,\nyou may not want to use `ALL_CLIENTS` (just omit the argument)\nand you can specify which specific fields you want to speed up queries.\nFor example:\n\n```python\ndetails = await client.query(\n    title=\"Augmenting large language models with chemistry tools\",\n    authors=[\"Andres M. Bran\", \"Sam Cox\"],\n    fields=[\"title\", \"doi\"],\n)\n```\n\nwill return much faster than the first query and we'll be certain the authors match.\n\n## Settings Cheatsheet\n\n| Setting                                      | Default                                | Description                                                                                                                   |\n| -------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `llm`                                        | `\"gpt-4o-2024-11-20\"`                  | LLM for general use including metadata inference (see Docs.aadd) and answer generation (see Docs.aquery and gen_answer tool). |\n| `llm_config`                                 | `None`                                 | Optional configuration for `llm`.                                                                                             |\n| `summary_llm`                                | `\"gpt-4o-2024-11-20\"`                  | LLM for creating contextual summaries (see Docs.aget_evidence and gather_evidence tool).                                      |\n| `summary_llm_config`                         | `None`                                 | Optional configuration for `summary_llm`.                                                                                     |\n| `embedding`                                  | `\"text-embedding-3-small\"`             | Embedding model for embedding text chunks when adding papers.                                                                 |\n| `embedding_config`                           | `None`                                 | Optional configuration for `embedding`.                                                                                       |\n| `temperature`                                | `0.0`                                  | Temperature for LLMs.                                                                                                         |\n| `batch_size`                                 | `1`                                    | Batch size for calling LLMs.                                                                                                  |\n| `texts_index_mmr_lambda`                     | `1.0`                                  | Lambda for MMR in text index.                                                                                                 |\n| `verbosity`                                  | `0`                                    | Integer verbosity level for logging (0-3). 3 = all LLM/Embeddings calls logged.                                               |\n| `custom_context_serializer`                  | `None`                                 | Custom async function (see typing for signature) to override the default answer context serialization.                        |\n| `answer.evidence_k`                          | `10`                                   | Number of evidence pieces to retrieve.                                                                                        |\n| `answer.evidence_retrieval`                  | `True`                                 | Use retrieval vs processing all docs.                                                                                         |\n| `answer.evidence_summary_length`             | `\"about 100 words\"`                    | Length of evidence summary.                                                                                                   |\n| `answer.evidence_skip_summary`               | `False`                                | Whether to skip summarization.                                                                                                |\n| `answer.evidence_text_only_fallback`         | `False`                                | Whether to allow context creation to retry without media present.                                                             |\n| `answer.answer_max_sources`                  | `5`                                    | Max number of sources for an answer.                                                                                          |\n| `answer.max_answer_attempts`                 | `None`                                 | Max attempts to generate an answer.                                                                                           |\n| `answer.answer_length`                       | `\"about 200 words, but can be longer\"` | Length of final answer.                                                                                                       |\n| `answer.max_concurrent_requests`             | `4`                                    | Max concurrent requests to LLMs.                                                                                              |\n| `answer.answer_filter_extra_background`      | `False`                                | Whether to cite background info from model.                                                                                   |\n| `answer.get_evidence_if_no_contexts`         | `True`                                 | Allow lazy evidence gathering.                                                                                                |\n| `answer.group_contexts_by_question`          | `False`                                | Groups the final contexts by the underlying `gather_evidence` question in the final context prompt.                           |\n| `answer.evidence_relevance_score_cutoff`     | `1`                                    | Cutoff evidence relevance score to include in the answer context (inclusive)                                                  |\n| `answer.skip_evidence_citation_strip`        | `False`                                | Skip removal of citations from the `gather_evidence` contexts                                                                 |\n| `parsing.page_size_limit`                    | `1,280,000`                            | Character limit per page.                                                                                                     |\n| `parsing.use_doc_details`                    | `True`                                 | Whether to get metadata details for docs.                                                                                     |\n| `parsing.reader_config`                      | `dict`                                 | Optional keyword arguments for the document reader.                                                                           |\n| `parsing.multimodal`                         | `True`                                 | Control to parse both text and media from applicable documents, as well as potentially enriching them with text descriptions. |\n| `parsing.defer_embedding`                    | `False`                                | Whether to defer embedding until summarization.                                                                               |\n| `parsing.parse_pdf`                          | `paperqa_pypdf.parse_pdf_to_pages`     | Function to parse PDF files.                                                                                                  |\n| `parsing.configure_pdf_parser`               | No-op                                  | Callable to configure the PDF parser within `parse_pdf`, useful for behaviors such as enabling logging.                       |\n| `parsing.doc_filters`                        | `None`                                 | Optional filters for allowed documents.                                                                                       |\n| `parsing.use_human_readable_clinical_trials` | `False`                                | Parse clinical trial JSONs into readable text.                                                                                |\n| `parsing.enrichment_llm`                     | `\"gpt-4o-2024-11-20\"`                  | LLM for media enrichment.                                                                                                     |\n| `parsing.enrichment_llm_config`              | `None`                                 | Optional configuration for `enrichment_llm`.                                                                                  |\n| `parsing.enrichment_page_radius`             | `1`                                    | Page radius for context text in enrichment.                                                                                   |\n| `parsing.enrichment_prompt`                  | `image_enrichment_prompt_template`     | Prompt template for enriching media.                                                                                          |\n| `parsing.citation_prompt`                    | `citation_prompt`                      | Prompt to create citation from peeking one chunk.                                                                             |\n| `parsing.structured_citation_prompt`         | `structured_citation_prompt`           | Prompt to create a citation (in JSON) from peeking one chunk.                                                                 |\n| `parsing.disable_doc_valid_check`            | `False`                                | Flag to disable checking if a document looks like text (was parsed correctly).                                                |\n| `prompts.summary`                            | `summary_prompt`                       | Template for summarizing text, must contain variables matching `summary_prompt`.                                              |\n| `prompts.qa`                                 | `qa_prompt`                            | Template for QA, must contain variables matching `qa_prompt`.                                                                 |\n| `prompts.select`                             | `select_paper_prompt`                  | Template for selecting papers, must contain variables matching `select_paper_prompt`.                                         |\n| `prompts.pre`                                | `None`                                 | Optional pre-prompt templated with just the original question to append information before a qa prompt.                       |\n| `prompts.post`                               | `None`                                 | Optional post-processing prompt that can access PQASession fields.                                                            |\n| `prompts.system`                             | `default_system_prompt`                | System prompt for the model.                                                                                                  |\n| `prompts.use_json`                           | `True`                                 | Whether to use JSON formatting.                                                                                               |\n| `prompts.summary_json`                       | `summary_json_prompt`                  | JSON-specific summary prompt.                                                                                                 |\n| `prompts.summary_json_system`                | `summary_json_system_prompt`           | System prompt for JSON summaries.                                                                                             |\n| `prompts.context_outer`                      | `CONTEXT_OUTER_PROMPT`                 | Prompt for how to format all contexts in generate answer.                                                                     |\n| `prompts.context_inner`                      | `CONTEXT_INNER_PROMPT`                 | Prompt for how to format a single context in generate answer. Must contain 'name' and 'text' variables.                       |\n| `prompts.answer_iteration_prompt`            | `answer_iteration_prompt_template`     | Prompt to inject existing prior answers to allow iteration. Default injects no prior answers.                                 |\n| `agent.agent_llm`                            | `\"gpt-4o-2024-11-20\"`                  | LLM inside the agent making tool selections.                                                                                  |\n| `agent.agent_llm_config`                     | `None`                                 | Optional configuration for `agent_llm`.                                                                                       |\n| `agent.agent_type`                           | `\"ToolSelector\"`                       | Type of agent to use.                                                                                                         |\n| `agent.agent_config`                         | `None`                                 | Optional kwarg for AGENT constructor.                                                                                         |\n| `agent.agent_system_prompt`                  | `env_system_prompt`                    | Optional system prompt message.                                                                                               |\n| `agent.agent_prompt`                         | `env_reset_prompt`                     | Agent prompt.                                                                                                                 |\n| `agent.return_paper_metadata`                | `False`                                | Whether to include paper title/year in search tool results.                                                                   |\n| `agent.search_count`                         | `8`                                    | Search count.                                                                                                                 |\n| `agent.timeout`                              | `500.0`                                | Timeout on agent execution (seconds).                                                                                         |\n| `agent.tool_names`                           | `None`                                 | Optional override on tools to provide the agent.                                                                              |\n| `agent.max_timesteps`                        | `None`                                 | Optional upper limit on environment steps.                                                                                    |\n| `agent.agent_evidence_n`                     | `1`                                    | Top n ranked evidences shown to the agent after gathering evidence.                                                           |\n| `agent.rebuild_index`                        | `True`                                 | Flag to rebuild the index at the start of agent runners.                                                                      |\n| `agent.callbacks`                            | `{}`                                   | Named lists of callables to be invoked with environment state.                                                                |\n| `agent.index.name`                           | `None`                                 | Optional name of the index.                                                                                                   |\n| `agent.index.paper_directory`                | `Current working directory`            | Directory containing papers to be indexed.                                                                                    |\n| `agent.index.manifest_file`                  | `None`                                 | Path to manifest CSV with document attributes.                                                                                |\n| `agent.index.index_directory`                | `pqa_directory(\"indexes\")`             | Directory to store PQA indexes.                                                                                               |\n| `agent.index.use_absolute_paper_directory`   | `False`                                | Whether to use absolute paper directory path.                                                                                 |\n| `agent.index.recurse_subdirectories`         | `True`                                 | Whether to recurse into subdirectories when indexing.                                                                         |\n| `agent.index.concurrency`                    | `5`                                    | Number of concurrent filesystem reads.                                                                                        |\n| `agent.index.sync_with_paper_directory`      | `True`                                 | Whether to sync index with paper directory on load.                                                                           |\n| `agent.index.batch_size`                     | `1`                                    | Number of files to process before committing to the index.                                                                    |\n| `agent.index.files_filter`                   | `lambda f: f.suffix in {...}`          | Filter function to mark files in the paper directory to index.                                                                |\n\n## Where do I get papers?\n\nWell that's a really good question!\nIt's probably best to just download PDFs of papers you think will help answer your question and start from there.\n\nSee detailed docs [about zotero, openreview and parsing](docs/tutorials/where_do_I_get_papers.md)\n\n## Callbacks\n\nTo execute a function on each chunk of LLM completions,\nyou need to provide a function that can be executed on each chunk.\nFor example, to get a typewriter view of the completions, you can do:\n\n```python\nfrom paperqa import Docs\n\n\ndef typewriter(chunk: str) -\u003e None:\n    print(chunk, end=\"\")\n\n\ndocs = Docs()\n\n# add some docs...\n\nawait docs.aquery(\"What is PaperQA2?\", callbacks=[typewriter])\n```\n\n### Caching Embeddings\n\nIn general, embeddings are cached when you pickle a `Docs` regardless of what vector store you use.\nSo as long as you save your underlying `Docs` object,\nyou should be able to avoid re-embedding your documents.\n\n## Customizing Prompts\n\nYou can customize any of the prompts using settings.\n\n```python\nfrom paperqa import Docs, Settings\n\nmy_qa_prompt = (\n    \"Answer the question '{question}'\\n\"\n    \"Use the context below if helpful. \"\n    \"You can cite the context using the key like (pqac-abcd1234). \"\n    \"If there is insufficient context, write a poem \"\n    \"about how you cannot answer.\\n\\n\"\n    \"Context: {context}\"\n)\n\ndocs = Docs()\nsettings = Settings()\nsettings.prompts.qa = my_qa_prompt\nawait docs.aquery(\"What is PaperQA2?\", settings=settings)\n```\n\n### Pre and Post Prompts\n\nFollowing the syntax above, you can also include prompts that\nare executed after the query and before the query.\nFor example, you can use this to critique the answer.\n\n## FAQ\n\n### How come I get different results than your papers?\n\nInternally at FutureHouse, we have a slightly different set of tools.\nWe're trying to get some of them, like citation traversal, into this repo.\nHowever, we have APIs and licenses to access research papers that we cannot share openly.\nSimilarly, in our research papers' results we do not start with the known relevant PDFs.\nOur agent has to identify them using keyword search over all papers, rather than just a subset.\nWe're gradually aligning these two versions of PaperQA,\nbut until there is an open-source way to freely access papers (even just open source papers)\nyou will need to provide PDFs yourself.\n\n### How is this different from LlamaIndex or LangChain?\n\n[LangChain](https://github.com/langchain-ai/langchain)\nand [LlamaIndex](https://github.com/run-llama/llama_index)\nare both frameworks for working with LLM applications,\nwith abstractions made for agentic workflows and retrieval augmented generation.\n\nOver time, the PaperQA team over time chose to become framework-agnostic,\ninstead outsourcing LLM drivers to [LiteLLM][LiteLLM general docs]\nand no framework besides Pydantic for its tools.\nPaperQA focuses on scientific papers and their metadata.\n\nPaperQA can be reimplemented using either LlamaIndex or LangChain.\nFor example, our `GatherEvidence` tool can be reimplemented\nas a retriever with an LLM-based re-ranking and contextual summary.\nThere is similar work with the tree response method in LlamaIndex.\n\n### Can I save or load?\n\nThe `Docs` class can be pickled and unpickled.\nThis is useful if you want to save the embeddings of the documents and then load them later.\n\n```python\nimport pickle\n\n# save\nwith open(\"my_docs.pkl\", \"wb\") as f:\n    pickle.dump(docs, f)\n\n# load\nwith open(\"my_docs.pkl\", \"rb\") as f:\n    docs = pickle.load(f)\n```\n\n## Reproduction\n\nContained in [docs/2024-10-16_litqa2-splits.json5](docs/2024-10-16_litqa2-splits.json5)\nare the question IDs used in train, evaluation, and test splits,\nas well as paper DOIs used to build the splits' indexes.\n\n- Train and eval splits: question IDs come from\n  [LAB-Bench's LitQA2 question IDs](https://github.com/Future-House/LAB-Bench/blob/main/LitQA2/litqa-v2-public.jsonl).\n- Test split: questions IDs come from\n  [aviary-paper-data's LitQA2 question IDs](https://huggingface.co/datasets/futurehouse/aviary-paper-data).\n\nThere are multiple papers slowly building PaperQA, shown below in [Citation](#citation).\nTo reproduce:\n\n- `skarlinski2024language`: train and eval splits are applicable.\n  The test split remains held out.\n- `narayanan2024aviarytraininglanguageagents`: train, eval, and test splits are applicable.\n\nExample on how to use LitQA for evaluation can be found in\n[aviary.litqa](https://github.com/Future-House/aviary/tree/main/packages/litqa#running-litqa).\n\n## Citation\n\nPlease read and cite the following papers if you use this software:\n\n```bibtex\n@article{narayanan2024aviarytraininglanguageagents,\n      title = {Aviary: training language agents on challenging scientific tasks},\n      author = {\n      Siddharth Narayanan and\n James D. Braza and\n Ryan-Rhys Griffiths and\n Manu Ponnapati and\n Albert Bou and\n Jon Laurent and\n Ori Kabeli and\n Geemi Wellawatte and\n Sam Cox and\n Samuel G. Rodriques and\n Andrew D. White},\n      journal = {arXiv preprent arXiv:2412.21154},\n      year = {2024},\n      url = {https://doi.org/10.48550/arXiv.2412.21154},\n}\n```\n\n```bibtex\n@article{skarlinski2024language,\n    title = {Language agents achieve superhuman synthesis of scientific knowledge},\n    author = {\n    Michael D. Skarlinski and\n Sam Cox and\n Jon M. Laurent and\n James D. Braza and\n Michaela Hinks and\n Michael J. Hammerling and\n Manvitha Ponnapati and\n Samuel G. Rodriques and\n Andrew D. White},\n    journal = {arXiv preprent arXiv:2409.13740},\n    year = {2024},\n    url = {https://doi.org/10.48550/arXiv.2409.13740}\n}\n```\n\n```bibtex\n@article{lala2023paperqa,\n    title = {PaperQA: Retrieval-Augmented Generative Agent for Scientific Research},\n    author = {\n    Jakub Lála and\n Odhran O'Donoghue and\n Aleksandar Shtedritski and\n Sam Cox and\n Samuel G. Rodriques and\n Andrew D. White},\n    journal = {arXiv preprint arXiv:2312.07559},\n    year = {2023},\n    url = {https://doi.org/10.48550/arXiv.2312.07559}\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffuture-house%2Fpaper-qa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffuture-house%2Fpaper-qa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffuture-house%2Fpaper-qa/lists"}