Spaces:
Running
Running
Update agent.py
Browse filesUpdating the agent tools and factory
agent.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
import os
|
2 |
import pandas as pd
|
3 |
import requests
|
4 |
from pydantic import Field, BaseModel
|
@@ -8,92 +7,34 @@ from omegaconf import OmegaConf
|
|
8 |
from vectara_agentic.agent import Agent
|
9 |
from vectara_agentic.tools import ToolsFactory, VectaraToolFactory
|
10 |
|
11 |
-
from dotenv import load_dotenv
|
12 |
-
load_dotenv(override=True)
|
13 |
-
|
14 |
-
|
15 |
-
tickers = {
|
16 |
-
"C": "Citigroup",
|
17 |
-
"COF": "Capital One",
|
18 |
-
"JPM": "JPMorgan Chase",
|
19 |
-
"AAPL": "Apple Computer",
|
20 |
-
"GOOG": "Google",
|
21 |
-
"AMZN": "Amazon",
|
22 |
-
"SNOW": "Snowflake",
|
23 |
-
"TEAM": "Atlassian",
|
24 |
-
"TSLA": "Tesla",
|
25 |
-
"NVDA": "Nvidia",
|
26 |
-
"MSFT": "Microsoft",
|
27 |
-
"AMD": "Advanced Micro Devices",
|
28 |
-
"INTC": "Intel",
|
29 |
-
"NFLX": "Netflix",
|
30 |
-
"STT": "State Street",
|
31 |
-
"BK": "Bank of New York Mellon",
|
32 |
-
}
|
33 |
-
years = range(2015, 2025)
|
34 |
initial_prompt = "How can I help you today?"
|
35 |
|
36 |
-
|
37 |
|
38 |
-
def get_company_info() -> list[str]:
|
39 |
-
"""
|
40 |
-
Returns a dictionary of companies you can query about. Always check this before using any other tool.
|
41 |
-
The output is a dictionary of valid ticker symbols mapped to company names.
|
42 |
-
You can use this to identify the companies you can query about, and their ticker information.
|
43 |
-
"""
|
44 |
-
return tickers
|
45 |
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
|
53 |
-
|
54 |
-
def fmp_income_statement(
|
55 |
-
ticker: str = Field(description="the ticker symbol of the company."),
|
56 |
-
year: int = Field(description="the year for which to get the income statement."),
|
57 |
-
) -> str:
|
58 |
-
"""
|
59 |
-
Get the income statement for a given company and year using the FMP (https://financialmodelingprep.com) API.
|
60 |
-
Returns a dictionary with the income statement data. All data is in USD, but you can convert it to more compact form like K, M, B.
|
61 |
-
"""
|
62 |
-
fmp_api_key = os.environ.get("FMP_API_KEY", None)
|
63 |
-
if fmp_api_key is None:
|
64 |
-
return "FMP_API_KEY environment variable not set. This tool does not work."
|
65 |
-
url = f"https://financialmodelingprep.com/api/v3/income-statement/{ticker}?apikey={fmp_api_key}"
|
66 |
-
response = requests.get(url)
|
67 |
-
if response.status_code == 200:
|
68 |
-
data = response.json()
|
69 |
-
income_statement = pd.DataFrame(data)
|
70 |
-
if len(income_statement) == 0 or "date" not in income_statement.columns:
|
71 |
-
return "No data found for the given ticker symbol."
|
72 |
-
income_statement["date"] = pd.to_datetime(income_statement["date"])
|
73 |
-
income_statement_specific_year = income_statement[
|
74 |
-
income_statement["date"].dt.year == int(year)
|
75 |
-
]
|
76 |
-
values_dict = income_statement_specific_year.to_dict(orient="records")[0]
|
77 |
-
return f"Financial results: {', '.join([f'{key}={value}' for key, value in values_dict.items() if key not in ['date', 'cik', 'link', 'finalLink']])}"
|
78 |
-
|
79 |
-
return f"FMP API returned error {response.status_code}. This tool does not work."
|
80 |
|
81 |
-
class QueryTranscriptsArgs(BaseModel):
|
82 |
-
query: str = Field(..., description="The user query, always in the form of a question", examples=["what are the risks reported?", "who are the competitors?"])
|
83 |
-
year: int | str = Field(..., description=f"The year this query relates to. An integer between {min(years)} and {max(years)} or a string specifying a condition on the year (example: '>2020').")
|
84 |
-
ticker: str = Field(..., description=f"The company ticker this query relates to. Must be a valid ticket symbol from the list {list(tickers.keys())}.")
|
85 |
|
|
|
|
|
|
|
86 |
vec_factory = VectaraToolFactory(vectara_api_key=cfg.api_key,
|
87 |
vectara_customer_id=cfg.customer_id,
|
88 |
vectara_corpus_id=cfg.corpus_id)
|
89 |
-
summarizer = 'vectara-
|
90 |
-
|
91 |
-
tool_name = "
|
92 |
tool_description = """
|
93 |
-
|
94 |
-
You can ask this tool any question about the company including risks, opportunities, financial performance, competitors and more.
|
95 |
""",
|
96 |
-
tool_args_schema =
|
97 |
reranker = "multilingual_reranker_v1", rerank_k = 100,
|
98 |
n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.005,
|
99 |
summary_num_results = 10,
|
@@ -105,50 +46,25 @@ def create_assistant_tools(cfg):
|
|
105 |
return (
|
106 |
[tools_factory.create_tool(tool) for tool in
|
107 |
[
|
108 |
-
get_company_info,
|
109 |
get_valid_years,
|
110 |
-
fmp_income_statement,
|
111 |
]
|
112 |
] +
|
113 |
-
tools_factory.
|
114 |
-
[
|
115 |
)
|
116 |
|
117 |
def initialize_agent(_cfg, agent_progress_callback=None):
|
118 |
-
|
119 |
-
- You are a helpful
|
120 |
-
- Use the
|
121 |
-
-
|
122 |
-
- Respond in a compact format by using appropriate units of measure (e.g., K for thousands, M for millions, B for billions).
|
123 |
-
Do not report the same number twice (e.g. $100K and 100,000 USD).
|
124 |
-
- Always use the 'income_statement' tool to obtain accurate financial data like revenues, expenses, net income, and other financial metrics
|
125 |
-
for a specific company, for any the year 2020 or later.
|
126 |
-
- Use the 'fmp_income_statement' tool (with the company ticker and year) to obtain financial data for any year before 2020.
|
127 |
-
- Always check the 'get_company_info' and 'get_valid_years' tools to validate company and year are valid.
|
128 |
-
- Do not include URLs unless they are provided in the output of a tool you use.
|
129 |
-
- When querying a tool for a numeric value or KPI, use a concise and non-ambiguous description of what you are looking for.
|
130 |
-
- If you calculate a metric, make sure you have all the necessary information to complete the calculation. Don't guess.
|
131 |
"""
|
132 |
|
133 |
agent = Agent(
|
134 |
tools=create_assistant_tools(_cfg),
|
135 |
-
topic="
|
136 |
-
custom_instructions=
|
137 |
agent_progress_callback=agent_progress_callback,
|
138 |
)
|
139 |
agent.report()
|
140 |
-
return agent
|
141 |
-
|
142 |
-
|
143 |
-
def get_agent_config() -> OmegaConf:
|
144 |
-
companies = ", ".join(tickers.values())
|
145 |
-
cfg = OmegaConf.create({
|
146 |
-
'customer_id': str(os.environ['VECTARA_CUSTOMER_ID']),
|
147 |
-
'corpus_id': str(os.environ['VECTARA_CORPUS_ID']),
|
148 |
-
'api_key': str(os.environ['VECTARA_API_KEY']),
|
149 |
-
'examples': os.environ.get('QUERY_EXAMPLES', None),
|
150 |
-
'demo_name': "finance-chat",
|
151 |
-
'demo_welcome': "Financial Assistant demo.",
|
152 |
-
'demo_description': f"This assistant can help you with any questions about the financials of several companies:\n\n **{companies}**.\n"
|
153 |
-
})
|
154 |
-
return cfg
|
|
|
|
|
1 |
import pandas as pd
|
2 |
import requests
|
3 |
from pydantic import Field, BaseModel
|
|
|
7 |
from vectara_agentic.agent import Agent
|
8 |
from vectara_agentic.tools import ToolsFactory, VectaraToolFactory
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
initial_prompt = "How can I help you today?"
|
11 |
|
12 |
+
years = range(2015, 2025)
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
def get_valid_years() -> list[str]:
|
16 |
+
"""
|
17 |
+
Returns a list of the years for which financial reports are available.
|
18 |
+
Always check this before using any other tool.
|
19 |
+
"""
|
20 |
+
return years
|
21 |
|
22 |
+
def create_assistant_tools(cfg):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
class QueryPublicationsArgs(BaseModel):
|
26 |
+
query: str = Field(..., description="The user query, always in the form of a question", examples=["what are the risks reported?", "which drug was use on the and how big was the population?"])
|
27 |
+
|
28 |
vec_factory = VectaraToolFactory(vectara_api_key=cfg.api_key,
|
29 |
vectara_customer_id=cfg.customer_id,
|
30 |
vectara_corpus_id=cfg.corpus_id)
|
31 |
+
summarizer = 'vectara-summary-ext-24-05-med-omni'
|
32 |
+
ask_publications = vec_factory.create_rag_tool(
|
33 |
+
tool_name = "ask_publications",
|
34 |
tool_description = """
|
35 |
+
Responds to an user question about a particular result, based on the publications.
|
|
|
36 |
""",
|
37 |
+
tool_args_schema = QueryPublicationsArgs,
|
38 |
reranker = "multilingual_reranker_v1", rerank_k = 100,
|
39 |
n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.005,
|
40 |
summary_num_results = 10,
|
|
|
46 |
return (
|
47 |
[tools_factory.create_tool(tool) for tool in
|
48 |
[
|
|
|
49 |
get_valid_years,
|
|
|
50 |
]
|
51 |
] +
|
52 |
+
tools_factory.standard_tools() +
|
53 |
+
[ask_publications]
|
54 |
)
|
55 |
|
56 |
def initialize_agent(_cfg, agent_progress_callback=None):
|
57 |
+
menarini_bot_instructions = """
|
58 |
+
- You are a helpful clinical trial assistant, with expertise in clinical trial test publications, in conversation with a user.
|
59 |
+
- Use the ask_publications tool to answer most questions about the results of clinical trials, risks, and more.
|
60 |
+
- Responses from ask_publications are summarized. You don't need to further summarize them.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
"""
|
62 |
|
63 |
agent = Agent(
|
64 |
tools=create_assistant_tools(_cfg),
|
65 |
+
topic="Drug trials publications",
|
66 |
+
custom_instructions=menarini_bot_instructions,
|
67 |
agent_progress_callback=agent_progress_callback,
|
68 |
)
|
69 |
agent.report()
|
70 |
+
return agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|