ositamiles commited on
Commit
6919d16
·
verified ·
1 Parent(s): 5712f72

Add application file

Browse files
Files changed (1) hide show
  1. assistant.py +296 -0
assistant.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Optional
4
+ from textwrap import dedent
5
+ from typing import List
6
+
7
+ from phi.assistant import Assistant
8
+ from phi.tools import Toolkit
9
+ from phi.tools.exa import ExaTools
10
+ from phi.tools.shell import ShellTools
11
+ from phi.tools.calculator import Calculator
12
+ from phi.tools.duckduckgo import DuckDuckGo
13
+ from phi.tools.yfinance import YFinanceTools
14
+ from phi.tools.file import FileTools
15
+ from phi.llm.openai import OpenAIChat
16
+ from phi.knowledge import AssistantKnowledge
17
+ from phi.embedder.openai import OpenAIEmbedder
18
+ from phi.assistant.duckdb import DuckDbAssistant
19
+ from phi.assistant.python import PythonAssistant
20
+ from phi.storage.assistant.postgres import PgAssistantStorage
21
+ from phi.utils.log import logger
22
+ from phi.vectordb.pgvector import PgVector2
23
+
24
+ db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
25
+ cwd = Path(__file__).parent.resolve()
26
+ scratch_dir = cwd.joinpath("scratch")
27
+ if not scratch_dir.exists():
28
+ scratch_dir.mkdir(exist_ok=True, parents=True)
29
+
30
+
31
+ def get_llm_os(
32
+ llm_id: str = "gpt-4o",
33
+ calculator: bool = False,
34
+ ddg_search: bool = False,
35
+ file_tools: bool = False,
36
+ shell_tools: bool = False,
37
+ data_analyst: bool = False,
38
+ python_assistant: bool = False,
39
+ research_assistant: bool = False,
40
+ investment_assistant: bool = False,
41
+ user_id: Optional[str] = None,
42
+ run_id: Optional[str] = None,
43
+ debug_mode: bool = True,
44
+ ) -> Assistant:
45
+ logger.info(f"-*- Creating {llm_id} LLM OS -*-")
46
+
47
+ # Add tools available to the LLM OS
48
+ tools: List[Toolkit] = []
49
+ extra_instructions: List[str] = []
50
+ if calculator:
51
+ tools.append(
52
+ Calculator(
53
+ add=True,
54
+ subtract=True,
55
+ multiply=True,
56
+ divide=True,
57
+ exponentiate=True,
58
+ factorial=True,
59
+ is_prime=True,
60
+ square_root=True,
61
+ )
62
+ )
63
+ if ddg_search:
64
+ tools.append(DuckDuckGo(fixed_max_results=3))
65
+ if shell_tools:
66
+ tools.append(ShellTools())
67
+ extra_instructions.append(
68
+ "You can use the `run_shell_command` tool to run shell commands. For example, `run_shell_command(args='ls')`."
69
+ )
70
+ if file_tools:
71
+ tools.append(FileTools(base_dir=cwd))
72
+ extra_instructions.append(
73
+ "You can use the `read_file` tool to read a file, `save_file` to save a file, and `list_files` to list files in the working directory."
74
+ )
75
+
76
+ # Add team members available to the LLM OS
77
+ team: List[Assistant] = []
78
+ if data_analyst:
79
+ _data_analyst = DuckDbAssistant(
80
+ name="Data Analyst",
81
+ role="Analyze movie data and provide insights",
82
+ semantic_model=json.dumps(
83
+ {
84
+ "tables": [
85
+ {
86
+ "name": "movies",
87
+ "description": "CSV of my favorite movies.",
88
+ "path": "https://phidata-public.s3.amazonaws.com/demo_data/IMDB-Movie-Data.csv",
89
+ }
90
+ ]
91
+ }
92
+ ),
93
+ base_dir=scratch_dir,
94
+ )
95
+ team.append(_data_analyst)
96
+ extra_instructions.append(
97
+ "To answer questions about my favorite movies, delegate the task to the `Data Analyst`."
98
+ )
99
+ if python_assistant:
100
+ _python_assistant = PythonAssistant(
101
+ name="Python Assistant",
102
+ role="Write and run python code",
103
+ pip_install=True,
104
+ charting_libraries=["streamlit"],
105
+ base_dir=scratch_dir,
106
+ )
107
+ team.append(_python_assistant)
108
+ extra_instructions.append("To write and run python code, delegate the task to the `Python Assistant`.")
109
+ if research_assistant:
110
+ _research_assistant = Assistant(
111
+ name="Research Assistant",
112
+ role="Write a research report on a given topic",
113
+ llm=OpenAIChat(model=llm_id),
114
+ description="You are a Senior New York Times researcher tasked with writing a cover story research report.",
115
+ instructions=[
116
+ "For a given topic, use the `search_exa` to get the top 10 search results.",
117
+ "Carefully read the results and generate a final - NYT cover story worthy report in the <report_format> provided below.",
118
+ "Make your report engaging, informative, and well-structured.",
119
+ "Remember: you are writing for the New York Times, so the quality of the report is important.",
120
+ ],
121
+ expected_output=dedent(
122
+ """\
123
+ An engaging, informative, and well-structured report in the following format:
124
+ <report_format>
125
+ ## Title
126
+
127
+ - **Overview** Brief introduction of the topic.
128
+ - **Importance** Why is this topic significant now?
129
+
130
+ ### Section 1
131
+ - **Detail 1**
132
+ - **Detail 2**
133
+
134
+ ### Section 2
135
+ - **Detail 1**
136
+ - **Detail 2**
137
+
138
+ ## Conclusion
139
+ - **Summary of report:** Recap of the key findings from the report.
140
+ - **Implications:** What these findings mean for the future.
141
+
142
+ ## References
143
+ - [Reference 1](Link to Source)
144
+ - [Reference 2](Link to Source)
145
+ </report_format>
146
+ """
147
+ ),
148
+ tools=[ExaTools(num_results=5, text_length_limit=1000)],
149
+ # This setting tells the LLM to format messages in markdown
150
+ markdown=True,
151
+ add_datetime_to_instructions=True,
152
+ debug_mode=debug_mode,
153
+ )
154
+ team.append(_research_assistant)
155
+ extra_instructions.append(
156
+ "To write a research report, delegate the task to the `Research Assistant`. "
157
+ "Return the report in the <report_format> to the user as is, without any additional text like 'here is the report'."
158
+ )
159
+ if investment_assistant:
160
+ _investment_assistant = Assistant(
161
+ name="Investment Assistant",
162
+ role="Write a investment report on a given company (stock) symbol",
163
+ llm=OpenAIChat(model=llm_id),
164
+ description="You are a Senior Investment Analyst for Goldman Sachs tasked with writing an investment report for a very important client.",
165
+ instructions=[
166
+ "For a given stock symbol, get the stock price, company information, analyst recommendations, and company news",
167
+ "Carefully read the research and generate a final - Goldman Sachs worthy investment report in the <report_format> provided below.",
168
+ "Provide thoughtful insights and recommendations based on the research.",
169
+ "When you share numbers, make sure to include the units (e.g., millions/billions) and currency.",
170
+ "REMEMBER: This report is for a very important client, so the quality of the report is important.",
171
+ ],
172
+ expected_output=dedent(
173
+ """\
174
+ <report_format>
175
+ ## [Company Name]: Investment Report
176
+
177
+ ### **Overview**
178
+ {give a brief introduction of the company and why the user should read this report}
179
+ {make this section engaging and create a hook for the reader}
180
+
181
+ ### Core Metrics
182
+ {provide a summary of core metrics and show the latest data}
183
+ - Current price: {current price}
184
+ - 52-week high: {52-week high}
185
+ - 52-week low: {52-week low}
186
+ - Market Cap: {Market Cap} in billions
187
+ - P/E Ratio: {P/E Ratio}
188
+ - Earnings per Share: {EPS}
189
+ - 50-day average: {50-day average}
190
+ - 200-day average: {200-day average}
191
+ - Analyst Recommendations: {buy, hold, sell} (number of analysts)
192
+
193
+ ### Financial Performance
194
+ {analyze the company's financial performance}
195
+
196
+ ### Growth Prospects
197
+ {analyze the company's growth prospects and future potential}
198
+
199
+ ### News and Updates
200
+ {summarize relevant news that can impact the stock price}
201
+
202
+ ### [Summary]
203
+ {give a summary of the report and what are the key takeaways}
204
+
205
+ ### [Recommendation]
206
+ {provide a recommendation on the stock along with a thorough reasoning}
207
+
208
+ </report_format>
209
+ """
210
+ ),
211
+ tools=[YFinanceTools(stock_price=True, company_info=True, analyst_recommendations=True, company_news=True)],
212
+ # This setting tells the LLM to format messages in markdown
213
+ markdown=True,
214
+ add_datetime_to_instructions=True,
215
+ debug_mode=debug_mode,
216
+ )
217
+ team.append(_investment_assistant)
218
+ extra_instructions.extend(
219
+ [
220
+ "To get an investment report on a stock, delegate the task to the `Investment Assistant`. "
221
+ "Return the report in the <report_format> to the user without any additional text like 'here is the report'.",
222
+ "Answer any questions they may have using the information in the report.",
223
+ "Never provide investment advise without the investment report.",
224
+ ]
225
+ )
226
+
227
+ # Create the LLM OS Assistant
228
+ llm_os = Assistant(
229
+ name="llm_os",
230
+ run_id=run_id,
231
+ user_id=user_id,
232
+ llm=OpenAIChat(model=llm_id),
233
+ description=dedent(
234
+ """\
235
+ You are the most advanced AI system in the world called `LLM-OS`.
236
+ You have access to a set of tools and a team of AI Assistants at your disposal.
237
+ Your goal is to assist the user in the best way possible.\
238
+ """
239
+ ),
240
+ instructions=[
241
+ "When the user sends a message, first **think** and determine if:\n"
242
+ " - You can answer by using a tool available to you\n"
243
+ " - You need to search the knowledge base\n"
244
+ " - You need to search the internet\n"
245
+ " - You need to delegate the task to a team member\n"
246
+ " - You need to ask a clarifying question",
247
+ "If the user asks about a topic, first ALWAYS search your knowledge base using the `search_knowledge_base` tool.",
248
+ "If you dont find relevant information in your knowledge base, use the `duckduckgo_search` tool to search the internet.",
249
+ "If the user asks to summarize the conversation or if you need to reference your chat history with the user, use the `get_chat_history` tool.",
250
+ "If the users message is unclear, ask clarifying questions to get more information.",
251
+ "Carefully read the information you have gathered and provide a clear and concise answer to the user.",
252
+ "Do not use phrases like 'based on my knowledge' or 'depending on the information'.",
253
+ "You can delegate tasks to an AI Assistant in your team depending of their role and the tools available to them.",
254
+ ],
255
+ extra_instructions=extra_instructions,
256
+ # Add long-term memory to the LLM OS backed by a PostgreSQL database
257
+ storage=PgAssistantStorage(table_name="llm_os_runs", db_url=db_url),
258
+ # Add a knowledge base to the LLM OS
259
+ knowledge_base=AssistantKnowledge(
260
+ vector_db=PgVector2(
261
+ db_url=db_url,
262
+ collection="llm_os_documents",
263
+ embedder=OpenAIEmbedder(model="text-embedding-3-small", dimensions=1536),
264
+ ),
265
+ # 3 references are added to the prompt when searching the knowledge base
266
+ num_documents=3,
267
+ ),
268
+ # Add selected tools to the LLM OS
269
+ tools=tools,
270
+ # Add selected team members to the LLM OS
271
+ team=team,
272
+ # Show tool calls in the chat
273
+ show_tool_calls=True,
274
+ # This setting gives the LLM a tool to search the knowledge base for information
275
+ search_knowledge=True,
276
+ # This setting gives the LLM a tool to get chat history
277
+ read_chat_history=True,
278
+ # This setting adds chat history to the messages
279
+ add_chat_history_to_messages=True,
280
+ # This setting adds 6 previous messages from chat history to the messages sent to the LLM
281
+ num_history_messages=6,
282
+ # This setting tells the LLM to format messages in markdown
283
+ markdown=True,
284
+ # This setting adds the current datetime to the instructions
285
+ add_datetime_to_instructions=True,
286
+ # Add an introductory Assistant message
287
+ introduction=dedent(
288
+ """\
289
+ Hi, I'm your LLM OS.
290
+ I have access to a set of tools and AI Assistants to assist you.
291
+ Let's solve some problems together!\
292
+ """
293
+ ),
294
+ debug_mode=debug_mode,
295
+ )
296
+ return llm_os