A Pydantic AI agent that answers questions about Pine Script v6, TradingView's language for indicators and strategies, and writes Pine Script code. It looks up the official documentation, indexed in PostgreSQL with pgvector, through a retrieval tool (RAG).
![]() |
![]() |
- Answers and Pine Script code grounded in the v6 documentation, found by hybrid search: vector and full-text results merged by rank fusion, then picked by MMR to leave out near-duplicates
- Three interfaces: a Streamlit web UI that keeps the chat history between sessions, an interactive shell, and single queries from the command line
- OpenAI by default, or any OpenRouter model, with presets for common choices
- Answers evaluated on recent Pine Script features, with and without the documents, and with RAGAS (results below)
tests/new_features_eval.py asks the model 31 questions, each about one feature of the Pine Script release notes from November 2024 to November 2026, five times with the retrieved documents and five times without.
| Right answers | Without documents | With documents |
|---|---|---|
| Round 1 | 21 of 31 | 27 of 31 |
| Round 2 | 16 of 31 | 29 of 31 |
| Round 3 | 18 of 31 | 28 of 31 |
| Round 4 | 19 of 31 | 28 of 31 |
| Round 5 | 19 of 31 | 27 of 31 |
| Right in most rounds | 19 of 31 | 28 of 31 |
| Released in 2024, all rounds | 34 of 35 | 35 of 35 |
| Released in 2025, all rounds | 39 of 45 | 43 of 45 |
| Released in 2026, all rounds | 20 of 75 | 61 of 75 |
The columns are close on the features of 2024 and 2025 and differ on those of 2026. The questions come from release notes that the index holds, so the table is about new features, not about Pine Script code in general.
Measured on 2 December 2026 with python tests/new_features_eval.py --rounds 5, on an index built with step 5 of the Quick Start, with the default settings and gpt-6-luna as answer model. An answer is right when its script contains the feature, found with a regular expression; no script is compiled.
RAGAS scores the answers to the 40 questions of tests/ragas_testset.json, ten for each category: function lookup, conceptual, code generation and complex multi-concept.
| Retrieval | Faithfulness | Context Relevance | Command |
|---|---|---|---|
| Vector search, 8 chunks | 0.3979 | 0.8125 | python tests/ragas_eval.py --retrieval baseline |
| Hybrid search, 15 chunks, as in the agent | 0.4211 | 0.8562 | python tests/ragas_eval.py --retrieval tier1 |
Measured on the same day and index, one run per row, with gpt-6-luna as answer model and as judge.
- Context Relevance says whether the retrieved chunks are about the question. Hybrid search scores higher in this run.
- Faithfulness is the share of the statements in an answer that the retrieved chunks support. The judge also counts the choices of a script, such as a length or a plot color, and no document states those: with hybrid search the command prints 0.67 for the conceptual questions and 0.30 for code generation. Faithfulness does not measure whether the code is right, and on it the two rows are too close to rank.
In both tables each answer is one direct call to the model, with the agent's instructions and, in all but the column without documents, the retrieved chunks in the message. tests/README.md has the steps to rerun them.
- Python 3.11+
- PostgreSQL with pgvector extension
- OpenAI API key (required for embeddings and default LLM)
- OpenRouter API key (optional, for alternative LLM providers)
- Docker (optional, for running PostgreSQL with pgvector)
-
Clone the repository
git clone https://github.com/FaustoS88/Pydantic-AI-Pinescript-Expert.git cd Pydantic-AI-Pinescript-Expert -
Start PostgreSQL with pgvector
docker run --name pinescript-pgvector \ -e POSTGRES_PASSWORD=postgres \ -p 54322:5432 \ -v pinescript_pgdata:/var/lib/postgresql/data \ -d pgvector/pgvector:pg16
-
Install the dependencies and create your
.envpython -m venv venv source venv/bin/activate # on Windows: venv\Scripts\activate pip install . cp -n .env.example .env # then add your API keys
pip install .installs the dependencies only; the scripts run from this folder. -
Initialize the database
python db.py init
-
Build the index of the Pine Script documentation
python crawler.py
The crawler fetches the pages over plain HTTP. With
--browserit renders them in a headless browser through Crawl4AI instead: install it withpip install ".[browser]", then download its browser once withcrawl4ai-setup. -
Ask questions in the web UI or in the terminal
streamlit run streamlit_ui.py # web UI python run.py interactive # terminal
The chat history is saved to chat_history.pkl and reloaded at the next start. The sidebar has a button that clears it.
Each answer sees the earlier turns. Type clear to forget the conversation and exit to quit.
python run.py query "How do I calculate RSI in Pine Script?"# Validate the schema and count the stored chunks
python run.py check
# List the first 20 chunks, with their ids
python db.py list
# Print one chunk by its id
python db.py view 508
# Print the 5 chunks closest to a query by vector
python db.py search "how to use request.security for different timeframes"- Search: full-text and vector search with a similarity threshold, merged by rank fusion, then MMR to drop near-duplicates
- Chunks: recursive chunking with overlap, fenced code blocks never split, a header with the context of each chunk, content type and metadata columns
- Contextual Retrieval (optional,
--contextual): an LLM writes a prefix for each chunk at crawl time
docs/retrieval.md follows the pipeline step by step, and docs/evaluations.md has the measurements behind the chunk size and the number of chunks.
Both commands fetch over plain HTTP; add --browser to render the pages through Crawl4AI.
# Standard crawl (no LLM prefix, about 3 minutes)
python crawler.py --clear
# Contextual re-crawl (one LLM call per chunk, up to 5 in parallel)
python crawler.py --contextual --clearagent.py: the Pydantic AI agent, itsretrievetool and the model selectionrag_utils.py: chunking and hybrid searchcrawler.py: fetches the documentation, splits it into chunks and stores them with their embeddingsdb.py: the database schema and connection, plus the commands to set up, inspect and clear it (python db.py -h)config.py: the settings, read from the environment and.env, and the model presetsrun.py: thequery,interactiveandcheckcommandsstreamlit_ui.py: the web UItests/: the offline tests and the two evaluations, described intests/README.md
Switch between LLM providers using the --model flag. Presets are defined in config.py:
| Preset | Model |
|---|---|
default |
openai/gpt-6-luna |
sol |
openai/gpt-6.2-sol |
opus |
anthropic/claude-opus-5.5 |
flash |
google/gemini-3.8-flash |
Since December 2026 the answers default to gpt-6-luna, with and without OpenRouter. OpenAI shuts down the snapshots of the earlier defaults, gpt-4.1-mini-2025-04-14 and gpt-4o-mini-2024-07-18, on 14 January 2027.
Models that reason run with effort low, and each model request has up to 4,000 output tokens, reasoning included. PINESCRIPT_THINKING_EFFORT and PINESCRIPT_MAX_TOKENS change them.
# Use a preset
python run.py query "How to use request.security?" --model sol
python run.py interactive --model opus
# Or pass any OpenRouter model ID directly
python run.py query "Explain ta.sma()" --model "anthropic/claude-sonnet-5.5"All presets route through OpenRouter — add your API key to .env as OPENROUTER_API_KEY. Without this key, the agent answers with the default OpenAI model.
Every variable, with its default and what it does, is in .env.example. Only OPENAI_API_KEY is required.
- Database status:
python run.py checkvalidates the schema and counts the stored chunks. - Docker: make sure Docker is running and port 54322 is free, or map another port and set it in
DATABASE_URL. - Database connection: check
DATABASE_URLin.env. - pgvector:
python db.py initcreates thevectorextension and lists the installed ones. It needs a server that has pgvector, such as the image of the Quick Start. - Embeddings: make sure your OpenAI API key is valid and has quota left.
Issues and pull requests are welcome. CONTRIBUTING.md has the setup, the checks and what a pull request should say.
- tickerflow — One async Python call for crypto, stocks, and forex OHLCV data with automatic provider fallback, pandas DataFrame support, and Pydantic AI agent integration.
This project is licensed under the MIT License - see the LICENSE file for details.
- Archon V1 by Cole Medin, the Pydantic AI docs agent that inspired this project
- Pydantic AI for the agent framework and the RAG example the database layer follows
- Crawl4AI for crawling the docs
- TradingView for Pine Script and its documentation
- pgvector for vector search
- OpenAI and OpenRouter for the models
- Streamlit for the web interface
- This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai).

