Repository navigation
Expand file tree
/
Copy pathagent.py
More file actions
169 lines (137 loc) · 5.67 KB
/
Copy pathagent.py
File metadata and controls
169 lines (137 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""Pine Script expert agent: dependencies, agent, capability, tool, model routing and run."""
from __future__ import annotations
import logging
from dataclasses import dataclass
import asyncpg
from openai import AsyncOpenAI
from pydantic_ai import Agent, AgentRunResult, RunContext
from pydantic_ai.capabilities import Capability, Thinking
from pydantic_ai.messages import ToolReturn, ToolReturnPart
from pydantic_ai.models.openrouter import OpenRouterModel
from pydantic_ai.providers.openrouter import OpenRouterProvider
from config import (
DEFAULT_MODEL,
LLM_SETTINGS,
MODEL_PRESETS,
OPENROUTER_BASE_URL,
OPENROUTER_DEFAULT_MODEL,
THINKING_EFFORT,
configured_key,
)
from db import database_connect
from rag_utils import hybrid_retrieve
logger = logging.getLogger(__name__)
@dataclass
class Dependencies:
"""Runtime dependencies injected per run."""
openai: AsyncOpenAI
pool: asyncpg.Pool
pinescript_agent = Agent(
DEFAULT_MODEL,
deps_type=Dependencies,
capabilities=[
Thinking(effort=THINKING_EFFORT),
# a function, because pinescript_rag is defined further down
lambda ctx: pinescript_rag,
],
model_settings=LLM_SETTINGS,
)
# tests/ragas_eval.py passes the chunks in the message and answers with these instructions
EXPERT_INSTRUCTIONS = (
"You are a Pine Script v6 expert assistant. Pine Script is the programming "
"language used in TradingView for creating custom indicators and strategies "
"for technical analysis of financial markets.\n\n"
"Ground every answer in the official documentation you retrieve. "
"When generating code, use //@version=6 and cite the documentation URLs.\n\n"
"Response guidelines:\n"
"1. Include working code examples whenever possible\n"
"2. Explain each part of the code clearly\n"
"3. Highlight common pitfalls or best practices\n"
"4. If unsure about something, be transparent about it\n"
"5. Format code with proper syntax highlighting\n"
"6. Reference specific Pine Script v6 functions and features accurately\n"
"7. Provide clear explanations of complex concepts with analogies when helpful\n"
"8. When appropriate, mention TradingView-specific context"
)
pinescript_rag = Capability(
id="pinescript-rag",
instructions=[
EXPERT_INSTRUCTIONS,
"ALWAYS call the retrieve tool before answering any Pine Script question.",
],
)
@pinescript_rag.tool
async def retrieve(ctx: RunContext[Dependencies], search_query: str) -> ToolReturn:
"""Retrieve relevant Pine Script documentation using hybrid search.
Pipeline: vector + full-text search (cosine > threshold) → RRF fusion → MMR deduplication.
Args:
ctx: Run context with database pool and OpenAI client.
search_query: The search query to find relevant documentation.
Returns:
Concatenated documentation snippets relevant to the query.
"""
docs = await hybrid_retrieve(
pool=ctx.deps.pool, openai_client=ctx.deps.openai, query=search_query
)
if not docs:
return ToolReturn(
return_value=(
"No relevant documentation found in the database. "
"The database may need to be populated with Pine Script documentation."
),
metadata=[],
)
logger.debug("Hybrid retrieval returned %d documents", len(docs))
# the model sees return_value; the app counts the URLs in metadata as references
return ToolReturn(
return_value="\n\n".join(
f"# {doc.title}\nDocumentation URL: {doc.url}\n\n{doc.content}\n" for doc in docs
),
metadata=[doc.url for doc in docs],
)
def references(result: AgentRunResult[str]) -> int:
"""Count the distinct documentation chunks the retrieve tool returned during this run."""
return len(
{
url
for message in result.new_messages()
for part in message.parts
if isinstance(part, ToolReturnPart) and part.tool_name == "retrieve"
for url in part.metadata or ()
}
)
def resolve_model(preset: str | None = None) -> OpenRouterModel | None:
"""Resolve a preset name or raw model ID to an OpenRouter model.
Without OPENROUTER_API_KEY it returns None, and the run keeps DEFAULT_MODEL.
"""
api_key = configured_key("OPENROUTER_API_KEY")
if not api_key:
if preset:
logger.warning("No OPENROUTER_API_KEY for preset '%s', using default", preset)
return None
model_id = MODEL_PRESETS.get(preset, preset) if preset else OPENROUTER_DEFAULT_MODEL
logger.info("Using OpenRouter model %s", model_id)
provider = OpenRouterProvider(api_key=api_key, base_url=OPENROUTER_BASE_URL)
return OpenRouterModel(model_id, provider=provider)
async def run_agent(question: str, preset: str | None = None, message_history=None):
"""Run the agent with a specific question.
Args:
question: The user's Pine Script question.
preset: Optional model preset name ('sol', 'opus', 'flash')
or a raw OpenRouter model ID.
message_history: Optional list[ModelMessage] from a previous run
(via result.new_messages()) for multi-turn context.
"""
logger.info("Running agent with question: %s", question)
openai = AsyncOpenAI()
try:
async with database_connect() as pool:
return await pinescript_agent.run(
question,
deps=Dependencies(openai=openai, pool=pool),
model=resolve_model(preset),
message_history=message_history,
)
except Exception as e:
logger.error("Error running agent: %s", e)
return None