### Install Pre-commit Hooks Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/README.md Install pre-commit hooks to automatically run linting and formatting checks before committing code. ```sh pre-commit install ``` -------------------------------- ### Example Usage of AnsweredSubQuestion Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/types.md Demonstrates how to instantiate and use the AnsweredSubQuestion model. This example shows creating a SubQuestion and then pairing it with an answer to form an AnsweredSubQuestion object. ```python from openbb_agents.models import SubQuestion, AnsweredSubQuestion sq = SubQuestion(id=1, question="What is AAPL's P/E ratio?", depends_on=None) answered_sq = AnsweredSubQuestion( subquestion=sq, answer="- AAPL's current P/E ratio is 28.5 based on the latest earnings data" ) print(f"Q: {answered_sq.subquestion.question}") print(f"A: {answered_sq.answer}") ``` -------------------------------- ### Example JSON Response for Tool Search Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/prompts-reference.md This is an example of the expected JSON output format when the tool search is successful. It lists the identifiers of the selected tools. ```json [".equity.price.historical", ".equity.fundamentals.overview", ".equity.fundamentals.ratios"] ``` -------------------------------- ### Local Configuration File Example Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Set API keys and user preferences in the local user_settings.json file. Ensure the file is located at ~/.openbb_platform/user_settings.json. ```json { "credentials": { "alpha_vantage_api_key": "your-key", "polygon_api_key": "your-key", "fred_api_key": "your-key" }, "preferences": { "output_type": "llm" } } ``` -------------------------------- ### Install openbb-agents Package Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/README.md Install the openbb-agents package using pip. Ensure you are using Python 3.10+. ```sh pip install openbb-agents --upgrade ``` -------------------------------- ### Asynchronous Agent Usage Example Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Demonstrates how to use the asynchronous OpenBB agent to answer complex financial questions concurrently. Subquestions with no dependencies are processed in parallel. ```python import asyncio from openbb_agents.agent import aopenbb_agent async def analyze_portfolio(): # Multiple subquestions are processed concurrently result = await aopenbb_agent( "Who are TSLA's peers? What is their market cap? Return in descending order." ) print(result) # Run the async function asyncio.run(analyze_portfolio()) ``` -------------------------------- ### Environment Setup for API Keys Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/INDEX.md Configure necessary API keys as environment variables before running the OpenBB Agents Platform. `OPENAI_API_KEY` is required, while others are optional. ```bash # Required export OPENAI_API_KEY="sk-..." # Optional (yfinance always available) export ALPHA_VANTAGE_API_KEY="..." export POLYGON_API_KEY="..." export FRED_API_KEY="..." # Optional (enable logging) export VERBOSE="True" ``` -------------------------------- ### Querying Agent with Limited Tools Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/getting_started.ipynb This example demonstrates how to query the OpenBB agent with a specific question while restricting its toolset to only `.equity.fundamental.income`. This ensures the agent uses only the specified tool for its response. ```python #... then we can specify it using the `openbb_tools` input argument result = openbb_agent("What is the most recent annual revenue of MSFT?", openbb_tools=[“.equity.fundamental.income”]) print(result) ``` -------------------------------- ### Async Processing with OpenBB Agent Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/README.md This example shows how to perform asynchronous operations using the `aopenbb_agent` function. It requires importing `asyncio` and defining an async main function to run the agent. ```python import asyncio from openbb_agents.agent import aopenbb_agent async def main(): result = await aopenbb_agent("What is TSLA's market cap?") return result asyncio.run(main()) ``` -------------------------------- ### Final Response Example Input and Output Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/prompts-reference.md Illustrates the input and expected output for the final response synthesis prompt. The output is a bulleted list addressing the original query using information from subquestion answers. ```text user_query: "Compare AAPL and MSFT stock prices" answered_subquestions: - Subquestion: What is AAPL's current stock price? Answer: AAPL is trading at $195.50 - Subquestion: What is MSFT's current stock price? Answer: MSFT is trading at $420.75 ``` ```text - AAPL is currently trading at $195.50 - MSFT is currently trading at $420.75 - MSFT's stock price is significantly higher than AAPL's (2.15x) ``` -------------------------------- ### Get Valid List of Providers Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Retrieves a list of valid OpenBB providers. Used internally to get user credentials. ```python get_valid_list_of_providers() ``` -------------------------------- ### Query Stock Price with Verbose Output Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/getting_started.ipynb Uses the openbb_agent to ask a question about a stock's current price. This example shows the detailed logging output during the agent's execution. ```python from openbb_agents.agent import openbb_agent result = openbb_agent("What is the current stock price of TSLA?", openbb_pat=OPENBB_PAT) print(result) ``` -------------------------------- ### Get Company Metrics Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve key financial metrics for a company. ```python # Company metrics openbb_agent("What is AMZN's P/E ratio and revenue growth?") ``` -------------------------------- ### TOOL_SEARCH_PROMPT_TEMPLATE Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/prompts-reference.md This template guides the LLM in searching for and selecting relevant tools from an index based on a subquestion. It is used by `search_tools()` and `asearch_tools()` and is designed for GPT-3.5-turbo with a temperature of 0.2. ```text You are a world-class state-of-the-art search agent. Your purpose is to search for tools that allow you to answer a user's subquestion. The subquestion could be a part of a chain of other subquestions. Your search cycle works as follows: 1. Search for tools using keywords 2. Read the description of tools 3. Select tools that contain the relevant data to answer the user's query ... repeat as many times as necessary until you reach a maximum of 4 tools 4. Return the list of tools using the output schema. You can search for tools using the available tool, which uses your inputs to search a vector databse that relies on similarity search. These are the guidelines to consider when completing your task: * Immediately return no tools if you do not require any to answer the query. * Never use the stock ticker or symbol or quantity in the query * Always try use the category in the query (eg. crypto, stock, market, etc.) * Only use keyword searches * Make multiple searches with different terms * You can return up to a maximum of 4 tools * Pay close attention to the data that available for each tool, and if it can answer the user's question * Return 0 tools if tools are NOT required to answer the user's question given the information contained in the context. YOU ARE ALLOWED TO MAKE MULTIPLE QUERIES IF YOUR FIRST RESULT DOES NOT YIELD THE APPROPRIATE TOOL. ## Example queries Below are some bad examples (to avoid) and good examples (to follow): Bad: "technology company peer comparison" Good: "peers" Bad: "company competitor analysis" Good: "market peers" Bad: "compare technology companies market capitilization" Good: "market capitalization" Bad: "current market capitalization of companies" Good: "market capitilization" Bad: "financial analysis tool" (not specific enough) Bad: "market capitilization lookup" Good: "market capitilization" Bad: "technology company peer lookup" Good: "market peers" Bad: "net profit TSLA" Good: "net profit" Bad: "current price BTC" Good: "price crypto" ## Example response ``` -------------------------------- ### Use Specific Tools with OpenBB Agent Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/README.md This example demonstrates how to restrict the `openbb_agent` to use only a specified list of tools. The `openbb_tools` parameter accepts a list of tool identifiers. ```python result = openbb_agent( "What is AAPL's stock price?", openbb_tools=[ ".equity.price.quote" ] ) ``` -------------------------------- ### Agent Result Example Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/getting_started.ipynb This snippet shows a typical result format from the agent, summarizing stock prices for multiple companies. ```text Result: '- The current stock price of Apple Inc. (AAPL) is $192.25. - The current stock price of Microsoft Corporation (MSFT) is $415.13.' ``` -------------------------------- ### Get Valid OpenBB Function Descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Retrieves a list of valid OpenBB function descriptions. ```python get_valid_openbb_function_descriptions() ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/README.md Configure necessary API keys for the agent. The OpenAI API key is required, while data provider keys are optional. ```bash # OpenAI API key (required) export OPENAI_API_KEY="sk-..." # Data provider credentials (optional, yfinance always available) export ALPHA_VANTAGE_API_KEY="your-key" ``` -------------------------------- ### Working with OpenBBFunctionDescription Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/types.md Demonstrates how to obtain a function description, inspect its input and output schemas, and invoke the associated callable function. ```python from openbb_agents.tools import map_name_to_openbb_function_description desc = map_name_to_openbb_function_description(".equity.price.quote") # Inspect input parameters input_schema = desc.input_model.schema() print(f"Required inputs: {input_schema['required']}") print(f"Parameters: {list(input_schema['properties'].keys())}") # Inspect output fields output_schema = desc.output_model.schema() print(f"Output fields: {list(output_schema['properties'].keys())}") # Call the function result = desc.callable(symbol="AAPL", provider="yfinance") ``` -------------------------------- ### Get Flat Properties from Pydantic Model as String Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Internal helper function to get flattened Pydantic model properties as a string. Used in vector index description generation. ```python _get_flat_properties_from_pydantic_model_as_str(model: BaseModel) -> str ``` -------------------------------- ### Get Crypto Price Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve the current price of a cryptocurrency in USD. ```python # Crypto prices openbb_agent("What is the current price of Bitcoin in USD?") ``` -------------------------------- ### Get Financial Statements Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve the latest financial statements for a company. ```python # Financial statements openbb_agent("What are MSFT's latest revenue and net income?") ``` -------------------------------- ### Instantiate SubQuestion Objects Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/types.md Demonstrates how to create SubQuestion objects, illustrating both subquestions with no dependencies and those that depend on the completion of other subquestions. ```python from openbb_agents.models import SubQuestion # Subquestion with no dependencies sq1 = SubQuestion( id=1, question="Who are TSLA's competitors?", depends_on=None ) # Subquestion depends on sq1 being answered first sq2 = SubQuestion( id=2, question="What are the market caps of TSLA's competitors?", depends_on=[1] ) ``` -------------------------------- ### Initialize and use the async OpenBB agent Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/getting_started.ipynb Use the `aopenbb_agent` for asynchronous workflows. This can improve performance in certain scenarios. Ensure you are in an async context when calling this function. ```python from openbb_agents.agent import aopenbb_agent await aopenbb_agent("What is the stock price of AAPL and MSFT?") ``` -------------------------------- ### Get Interest Rate Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve the current value of a specific interest rate. ```python # Interest rates openbb_agent("What is the current Federal Funds Rate?") ``` -------------------------------- ### Get Economic Indicator Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve the current value of a specific economic indicator. ```python # Economic data openbb_agent("What is the current unemployment rate?") ``` -------------------------------- ### Synchronous and Asynchronous Agent Entry Points Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/INDEX.md Use `openbb_agent` for synchronous calls and `aopenbb_agent` for asynchronous calls to interact with the OpenBB agent. Both functions accept a query string and optional tool lists or credentials. ```python from openbb_agents.agent import openbb_agent, aopenbb_agent # Synchronous result = openbb_agent( query: str, openbb_tools: list[str] | None = None, openbb_pat: str | None = None, extra_tools: list[Callable] | None = None, verbose: bool = True, ) -> str # Asynchronous result = await aopenbb_agent( query: str, openbb_tools: list[str] | None = None, extra_tools: list[Callable] | None = None, verbose: bool = True, ) -> str ``` -------------------------------- ### Get Company Valuation Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Assess if a company is overvalued compared to its industry peers. ```python # Valuation openbb_agent("Is AAPL overvalued compared to its peers?") ``` -------------------------------- ### Configure OpenBB Data Providers (Local) Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Create a local user settings JSON file to store API keys for OpenBB data providers like Alpha Vantage and Polygon. ```json { "credentials": { "alpha_vantage_api_key": "your-key", "polygon_api_key": "your-key" } } ``` -------------------------------- ### Get Stock Price History Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve historical stock prices for a given ticker. ```python # Price history openbb_agent("What was the stock price of TSLA one year ago?") ``` -------------------------------- ### Get Single Stock Price Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Retrieve the current price for a specific stock ticker. ```python # Single stock price openbb_agent("What is the current price of AAPL?") ``` -------------------------------- ### Basic OpenBB Agent Usage Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Demonstrates the basic usage of the openbb_agent function to answer a financial query using all available tools. ```python from openbb_agents.agent import openbb_agent # Basic usage with all available tools result = openbb_agent("What is TSLA's current market cap?") print(result) ``` -------------------------------- ### Get Dependencies Function Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Retrieves a list of AnsweredSubQuestion objects, representing dependencies. This function is part of the utility module. ```python def get_dependencies() -> list[AnsweredSubQuestion]: """Get dependencies. Returns: list[AnsweredSubQuestion]: A list of answered sub-questions. """ # Placeholder for actual dependency retrieval logic return [] ``` -------------------------------- ### Get Answerable Subquestions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Filters subquestions to those whose dependencies are all satisfied. Returns a list of answerable SubQuestion objects. ```python def _get_answerable_subquestions( subquestions: list[SubQuestion], answered_subquestions: list[AnsweredSubQuestion] ) -> list[SubQuestion]: # Filters subquestions to those whose dependencies are all satisfied. # # Returns: List of answerable SubQuestion objects. pass ``` -------------------------------- ### Synchronous OpenBB Agent Execution Flow Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/architecture-overview.md Illustrates the sequential steps involved when the OpenBB Agent processes a user query synchronously. This includes logging configuration, tool index handling, sub-question generation, tool searching, answer generation for each sub-question, and finally, compiling the overall answer. ```text openbb_agent("What is TSLA's market cap?") ↓ configure_logging(verbose) ↓ _handle_tool_vector_index(openbb_tools) ├─→ if openbb_tools is None: │ build_openbb_tool_vector_index() │ └─→ get_valid_openbb_function_descriptions() │ └─→ get_valid_list_of_providers() │ └─→ if openbb_tools provided: build_vector_index_from_openbb_function_descriptions() ↓ generate_subquestions_from_query(query) ├─→ LLM Call (GPT-4o, temp=0.0) └─→ Returns: list[SubQuestion] ↓ For each SubQuestion: ├─→ Check _is_subquestion_answerable() │ └─→ if dependencies satisfied: │ ├─→ get_dependencies(answered_subquestions, subquestion) │ └─→ Returns: list[AnsweredSubQuestion] │ ├─→ search_tools(subquestion, tool_index) │ ├─→ LLM Call (GPT-3.5-turbo, temp=0.2) │ │ └─→ Can call llm_query_tool_index(query) │ │ └─→ vector_store.similarity_search(k=4) │ └─→ Returns: list[Callable] │ └─→ generate_subquestion_answer(user_query, subquestion, tools, deps) ├─→ While answer not received: │ ├─→ LLM Call (GPT-4o, temp=0.0, functions=tools) │ ├─→ If LLM returns ParallelFunctionCall: │ │ ├─→ For each function_call: │ │ │ ├─→ Execute: function_call() │ │ │ ├─→ Catch exceptions │ │ │ └─→ Build FunctionResultMessage │ │ └─→ Append to messages, loop │ └─→ If LLM returns str: break └─→ Returns: AnsweredSubQuestion ↓ generate_final_answer(user_query, answered_subquestions) ├─→ LLM Call (GPT-4o, temp=0.0) └─→ Returns: str (bulleted list) ↓ Return final_answer to user ``` -------------------------------- ### Importing OpenBB Agents Modules Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Demonstrates how to import key components from the openbb_agents package. All imports must use full module paths. ```python from openbb_agents.agent import openbb_agent, aopenbb_agent from openbb_agents.chains import generate_subquestions_from_query from openbb_agents.tools import build_openbb_tool_vector_index from openbb_agents.models import SubQuestion, AnsweredSubQuestion from openbb_agents.testing import with_llm from openbb_agents.utils import configure_logging, get_dependencies ``` -------------------------------- ### OpenBB Agent with Specific Tools Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Shows how to use the openbb_agent function with a predefined list of OpenBB functions. ```python # Use specific OpenBB functions only result = openbb_agent( "Compare AAPL and MSFT by market cap", openbb_tools=[ ".equity.price.quote", ".equity.fundamental.metrics"] ) print(result) ``` -------------------------------- ### Get OpenBB User Credentials Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md An internal function to fetch the user's OpenBB credentials. This is utilized to validate the availability of different providers. ```python def _get_openbb_user_credentials() -> dict ``` -------------------------------- ### Use All Available Tools with OpenBB Agent Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/README.md This snippet shows the basic usage of the `openbb_agent` function to query information using all available tools. Ensure the `openbb_agent` function is imported. ```python from openbb_agents.agent import openbb_agent result = openbb_agent("What is AAPL's stock price?") ``` -------------------------------- ### Asynchronous Agent Usage with Specific Tools Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Shows how to use the asynchronous OpenBB agent with a specified list of OpenBB tools for a targeted financial analysis. ```python async def get_fundamentals(): result = await aopenbb_agent( "Perform a fundamentals financial analysis of AMZN", openbb_tools=[ ".equity.fundamentals.overview", ".equity.fundamentals.ratios"] ) return result ``` -------------------------------- ### Get Verbosity Function Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Retrieves the verbosity setting from the VERBOSE environment variable. Returns True if the variable is set to 'True' (case-sensitive), otherwise False. ```python def get_verbosity() -> bool: """Get verbosity from environment variable. Returns: bool: True if VERBOSE is set to "True", False otherwise. """ return os.getenv("VERBOSE", "False") == "True" ``` -------------------------------- ### Get Output Type Hint Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Internal helper function to determine the output type hint for a tool. Used when appending tools to a vector index. ```python _get_output_type_hint(tool: Callable) -> str ``` -------------------------------- ### Map Name to OpenBB Function Description Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Maps an OpenBB function name to its description. Used internally to get OpenBB coverage command schemas. ```python map_name_to_openbb_function_description(function_name: str) ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Enable verbose logging to observe the agent's tool selection process. ```python openbb_agent(query, verbose=True) ``` -------------------------------- ### Get Valid OpenBB Function Names Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Retrieves a list of valid OpenBB function names. Used internally to check OpenBB coverage providers. ```python get_valid_openbb_function_names() ``` -------------------------------- ### Configure OpenBB Data Providers (Environment Variables) Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Set API keys for OpenBB data providers as environment variables. This method is an alternative to local configuration or using the OpenBB Hub. ```bash export ALPHA_VANTAGE_API_KEY="your-key" export POLYGON_API_KEY="your-key" export FRED_API_KEY="your-key" ``` -------------------------------- ### Basic Agent Usage Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/README.md Use the openbb_agent function to query financial information. The agent will print logs showing its progress. ```python >>> from openbb_agents.agent import openbb_agent >>> result = openbb_agent("What is the current market cap of TSLA?") # Will print some logs to show you progress >>> print(result) - The current market cap of TSLA (Tesla, Inc.) is approximately $695,833,798,800.00. - This figure is based on the most recent data available, which is from January 15, 2024. - The market cap is calculated by multiplying the current stock price ($218.89) by the number of outstanding shares (3,178,920,000). ``` -------------------------------- ### Configure OpenBB Data Providers (OpenBB Hub) Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Use an OpenBB Hub Personal Access Token (PAT) directly in your code to authenticate with OpenBB data providers. Ensure you have created an account and generated a PAT on the OpenBB Hub. ```python from openbb_agents.agent import openbb_agent result = openbb_agent( "What is the stock price of AAPL?", openbb_pat="your-openbb-hub-pat" ) ``` -------------------------------- ### Build Vector Index from OpenBB Function Descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Builds a vector store index from a list of OpenBB function descriptions. ```python build_vector_index_from_openbb_function_descriptions(descriptions: list[OpenBBFunctionDescription]) -> VectorStore ``` -------------------------------- ### Testing with LLM Assertion Example Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/types.md Demonstrates how to use the `with_llm` function for evaluating unstructured output against an assertion. The function returns an `AssertResult` and raises an `AssertionError` if the result is false. ```python from openbb_agents.testing import with_llm output = "The stock price of AAPL is $195.50 as of today." assert with_llm(output, "AAPL's stock price is provided in the output") ``` -------------------------------- ### Build OpenBB Tool Vector Index Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Builds a vector store index for OpenBB tools. ```python build_openbb_tool_vector_index() -> VectorStore ``` -------------------------------- ### Configure OpenBB LLM Mode Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Set OpenBB output type to 'llm' and configure docstring settings for optimal LLM processing. Ensure OpenBB is built after configuration. ```python obb.user.preferences.output_type = "llm" obb.system.python_settings.docstring_sections = ["description", "examples"] ob.system.python_settings.docstring_max_length = 1024 openbb.build() ``` -------------------------------- ### Get Output Type Hint from Callable Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Extracts the return type annotation from a callable's type hints. It returns the type or BaseModel class, or None if no annotation is present. ```python def _get_output_type_hint(tool: Callable) -> type | BaseModel | None ``` -------------------------------- ### Get Valid OpenBB Function Descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Retrieves OpenBBFunctionDescription objects for all functions the user has valid credentials for. Each description includes the function's name, callable, and input/output models. ```python from openbb_agents.tools import get_valid_openbb_function_descriptions descriptions = get_valid_openbb_function_descriptions() for desc in descriptions[:3]: print(f"Function: {desc.name}") print(f"Callable: {desc.callable.__name__}") ``` -------------------------------- ### OpenBB Agent with Hub Credentials Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Illustrates how to authenticate the openbb_agent with OpenBB Hub credentials using a Personal Access Token. ```python # With OpenBB Hub credentials result = openbb_agent( "What is AMZN's most recent P/E ratio?", openbb_pat="your-openbb-hub-pat-token" ) ``` -------------------------------- ### Programmatic Configuration of Preferences Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Configure OpenBB preferences and system settings directly in your Python code. This allows for dynamic configuration during runtime. ```python from openbb import obb # Configure OpenBB preferences obb.user.preferences.output_type = "llm" obb.system.python_settings.docstring_sections = ["description", "examples"] obb.system.python_settings.docstring_max_length = 1024 ``` -------------------------------- ### Get Valid List of Providers Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Returns a list of data providers for which the user has valid credentials. It automatically detects credentials by looking for environment variables and always includes 'yfinance'. ```python from openbb_agents.tools import get_valid_list_of_providers providers = get_valid_list_of_providers() print(f"Configured providers: {providers}") ``` -------------------------------- ### Set Data Provider API Keys via Environment Variables Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Configure API keys for data providers like Alpha Vantage, Polygon, and FRED using environment variables. Note that yfinance does not require a key. ```bash # Default yfinance requires no key export ALPHA_VANTAGE_API_KEY="your-key" export POLYGON_API_KEY="your-key" export FRED_API_KEY="your-key" ``` -------------------------------- ### Perform a Simple Stock Query Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Use the `openbb_agent` function to ask a simple question about a stock, such as its current price. The result will be printed to the console. ```python from openbb_agents.agent import openbb_agent result = openbb_agent("What is the current stock price of AAPL?") print(result) ``` -------------------------------- ### Get OpenBB Command Schemas Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md An internal function that retrieves the command schemas for OpenBB, including input/output models and callable functions. The data is returned as a dictionary keyed by function name. ```python def _get_openbb_coverage_command_schemas() -> dict ``` -------------------------------- ### Set Alpha Vantage API Key via Local Config File Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Configure the Alpha Vantage API key by creating a local user settings JSON file. ```bash mkdir -p ~/.openbb_platform cat > ~/.openbb_platform/user_settings.json << 'EOF' {"credentials": {"alpha_vantage_api_key": "your-key"}} EOF ``` -------------------------------- ### Get OpenBB Provider Coverage Data Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md An internal helper function that retrieves raw OpenBB coverage data, keyed by provider name. This is primarily used for tool discovery purposes. ```python def _get_openbb_coverage_providers() -> dict ``` -------------------------------- ### build_openbb_tool_vector_index Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Builds a FAISS vector store containing all available OpenBB Platform functions that the user has valid credentials for. Uses OpenAI embeddings to vectorize function descriptions. ```APIDOC ## build_openbb_tool_vector_index ### Description Builds a FAISS vector store containing all available OpenBB Platform functions that the user has valid credentials for. Uses OpenAI embeddings to vectorize function descriptions. ### Returns `VectorStore` (FAISS instance with embedded OpenBB function descriptions). ### Process: 1. Retrieves all valid OpenBB function names based on user's API credentials 2. Gets function metadata (docstrings, input/output schemas) 3. Creates text descriptions combining function name, docstring, and output field descriptions 4. Embeds descriptions using OpenAI embeddings 5. Stores in FAISS for similarity search ### Usage Example: ```python from openbb_agents.tools import build_openbb_tool_vector_index # Build index of all available tools tool_index = build_openbb_tool_vector_index() # Use in similarity search (manual example) results = tool_index.similarity_search("stock price quote", k=4) for doc in results: print(f"Tool: {doc.metadata['tool_name']}") print(f"Description: {doc.page_content[:100]}...") ``` ``` -------------------------------- ### Final Response Synthesis Prompt Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/prompts-reference.md Guides the final answer synthesis stage by combining subquestion answers into a single response. Used by `generate_final_answer()` and `agenerate_final_answer()`. Model: GPT-4o (temperature 0.0). ```text Given the following high-level question: {user_query} And the following subquestions and subsequent observations: {answered_subquestions} Answer the high-level question. Give your answer in a bulleted list. ``` -------------------------------- ### OpenBB Agent Entry Points Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/architecture-overview.md Synchronous and asynchronous main entry points for the OpenBB agent. Manages authentication, pipeline orchestration, and subquestion dependency resolution. ```python openbb_agent() aopenbb_agent() ``` -------------------------------- ### Get Valid OpenBB Function Names Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Retrieves a sorted list of OpenBB function names for which the user has valid credentials. It uses the OpenBB coverage API and user credentials to filter available functions. ```python from openbb_agents.tools import get_valid_openbb_function_names functions = get_valid_openbb_function_names() print(f"Available functions: {len(functions)}") for fn in functions[:5]: print(f" - {fn}") ``` -------------------------------- ### Get Verbosity from Environment Variable Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/utilities-api.md Reads the VERBOSE environment variable to determine default verbosity for the library. Set the VERBOSE environment variable to "True" to enable verbose logging by default. ```python import os from openbb_agents.utils import get_verbosity # Set verbosity via environment variable os.environ["VERBOSE"] = "True" verbose = get_verbosity() # Returns True os.environ["VERBOSE"] = "False" verbose = get_verbosity() # Returns False del os.environ["VERBOSE"] verbose = get_verbosity() # Returns False (default) ``` -------------------------------- ### Import necessary modules for testing Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Imports `OpenaiChatModel` and `prompt` from magentic, and `BaseModel`, `Field` from pydantic. These are foundational for LLM interactions and data modeling in the testing module. ```python from magentic import OpenaiChatModel, prompt from pydantic import BaseModel, Field ``` -------------------------------- ### Set Data Provider API Key via Config File Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Configure a data provider API key by creating or updating the user settings JSON file. ```bash # Option 2: Create config file mkdir -p ~/.openbb_platform cat > ~/.openbb_platform/user_settings.json << 'EOF' {"credentials": {"alpha_vantage_api_key": "your-key"}} EOF ``` -------------------------------- ### build_vector_index_from_openbb_function_descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/module-reference.md Builds a vector index from a list of OpenBB function descriptions. ```APIDOC ## build_vector_index_from_openbb_function_descriptions ### Description Builds a vector index from a list of OpenBB function descriptions. ### Type function ### Returns VectorStore ``` -------------------------------- ### Use Custom Tools with OpenBB Agent Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/README.md This snippet illustrates how to extend the `openbb_agent`'s capabilities by providing custom functions via the `extra_tools` parameter. Ensure your custom functions are defined and have appropriate type hints. ```python def my_function(param: str) -> float: """My custom tool.""" return 3.14 result = openbb_agent( "Calculate something", extra_tools=[my_function] ) ``` -------------------------------- ### Set Alpha Vantage API Key via Environment Variable Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Configure the Alpha Vantage API key using an environment variable for authentication. ```bash export ALPHA_VANTAGE_API_KEY="your-key" ``` -------------------------------- ### Handle Tool Vector Index Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Builds or selects the appropriate tool vector index based on OpenBB tool specification. Pass a list of tool names or None to use all available tools. ```python def _handle_tool_vector_index(openbb_tools: list[str] | None) -> VectorStore: pass ``` -------------------------------- ### Configure OpenBB for LLM Mode Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Sets up the OpenBB Platform for optimal LLM interaction by adjusting output formatting and docstring extraction. This function is automatically invoked on module import. ```python def enable_openbb_llm_mode() ``` -------------------------------- ### Compare P/E Ratios Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Compare the Price-to-Earnings (P/E) ratios of a group of stocks, sorted by ratio. ```python # Ratios comparison openbb_agent("What are the P/E ratios of FAANG stocks? Return sorted from lowest to highest.") ``` -------------------------------- ### Set Data Provider API Keys Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Set environment variables for various data providers to enable them. The library automatically detects keys ending in _API_KEY or _TOKEN. ```bash export ALPHA_VANTAGE_API_KEY="your-key" # Enables alpha_vantage provider export POLYGON_API_KEY="your-key" # Enables polygon provider export FRED_API_KEY="your-key" # Enables fred provider ``` -------------------------------- ### Tool Vector Index Building Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/architecture-overview.md Functions for discovering and building a searchable vector index of available OpenBB tools and providers. ```python get_valid_list_of_providers() get_valid_openbb_function_names() build_openbb_tool_vector_index() ``` -------------------------------- ### Synchronous Tool Search Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/chains-api.md Use `search_tools` to find relevant OpenBB functions for a given subquestion using an LLM and a vector index. Ensure the tool vector index is built before calling this function. ```python from openbb_agents.chains import search_tools from openbb_agents.models import SubQuestion from openbb_agents.tools import build_openbb_tool_vector_index # Build tool index tool_index = build_openbb_tool_vector_index() # Create a subquestion subquestion = SubQuestion( id=1, question="What is AAPL's current stock price?", depends_on=None ) # Find relevant tools tools = search_tools(subquestion, tool_index) print(f"Found {len(tools)} relevant tools") for tool in tools: print(f" - {tool.__name__}") ``` -------------------------------- ### Set Data Provider API Key via Environment Variable Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Configure a data provider API key using an environment variable. ```bash # Option 1: Use environment variable export ALPHA_VANTAGE_API_KEY="your-key" ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Set the OpenAI API key as an environment variable. Replace 'sk-...' with your actual key. ```bash export OPENAI_API_KEY="sk-..." ``` -------------------------------- ### Tool Management Functions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/INDEX.md Imports essential functions for managing OpenBB tools, including retrieving valid provider lists, building vector indexes for tools, and appending custom tools to the index. ```python from openbb_agents.tools import ( get_valid_list_of_providers, build_openbb_tool_vector_index, append_tools_to_vector_index, ) ``` -------------------------------- ### build_vector_index_from_openbb_function_descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Builds a FAISS vector store from explicit OpenBB function descriptions. Used when only specific functions are needed. ```APIDOC ## build_vector_index_from_openbb_function_descriptions ### Description Builds a FAISS vector store from explicit OpenBB function descriptions. Used when only specific functions are needed. ### Parameters - `openbb_function_descriptions` (list[OpenBBFunctionDescription]): List of function description objects. ### Returns `VectorStore` (FAISS instance). ### Documents Created: One Document per function with: - `page_content`: Function name, docstring, and output field descriptions - `metadata`: `{"callable": , "tool_name": ""}` ### Usage Example: ```python from openbb_agents.tools import ( map_name_to_openbb_function_description, build_vector_index_from_openbb_function_descriptions ) # Get descriptions for specific functions descriptions = [ map_name_to_openbb_function_description(".equity.price.quote"), map_name_to_openbb_function_description(".equity.fundamentals.overview") ] # Build index from those specific functions index = build_vector_index_from_openbb_function_descriptions(descriptions) ``` ``` -------------------------------- ### Query with Specific Tools Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Limit the agent's search to a predefined set of tools by specifying them in the `openbb_tools` argument. This can improve performance and accuracy for targeted questions. ```python result = openbb_agent( "What is TSLA's P/E ratio?", openbb_tools=[ ".equity.fundamentals.overview", ".equity.price.quote"] ) print(result) ``` -------------------------------- ### Build Vector Index from Specific Function Descriptions Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Constructs a FAISS vector store using a provided list of OpenBB function descriptions. This is useful when only a subset of functions is required. ```python from openbb_agents.tools import ( map_name_to_openbb_function_description, build_vector_index_from_openbb_function_descriptions ) # Get descriptions for specific functions descriptions = [ map_name_to_openbb_function_description(".equity.price.quote"), map_name_to_openbb_function_description(".equity.fundamentals.overview") ] # Build index from those specific functions index = build_vector_index_from_openbb_function_descriptions(descriptions) ``` -------------------------------- ### Build OpenBB Tool Vector Index Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/tools-api.md Builds a FAISS vector store with embeddings of all available OpenBB Platform functions for which the user has valid credentials. Uses OpenAI embeddings for vectorization. ```python from openbb_agents.tools import build_openbb_tool_vector_index # Build index of all available tools tool_index = build_openbb_tool_vector_index() # Use in similarity search (manual example) results = tool_index.similarity_search("stock price quote", k=4) for doc in results: print(f"Tool: {doc.metadata['tool_name']}") print(f"Description: {doc.page_content[:100]}...") ``` -------------------------------- ### search_tools Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/chains-api.md Synchronously searches a vector database of OpenBB tools to find the most relevant ones for answering a given subquestion. It can leverage context from previously answered subquestions and uses GPT-3.5-turbo for the search. ```APIDOC ## search_tools ### Description Uses an LLM to search a vector database of OpenBB tools and find the most relevant ones for answering a subquestion. The LLM can make multiple searches and can use context from previously answered subquestions. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **subquestion** (SubQuestion) - Required - The subquestion to find tools for. - **tool_vector_index** (VectorStore) - Required - FAISS vector store of tool descriptions. - **answered_subquestions** (list[AnsweredSubQuestion] | None) - Optional - Previously answered subquestions for context (default None). ### Returns `list[Callable]` - List of callable OpenBB functions relevant to the subquestion. ### Usage Example ```python from openbb_agents.chains import search_tools from openbb_agents.models import SubQuestion from openbb_agents.tools import build_openbb_tool_vector_index # Build tool index tool_index = build_openbb_tool_vector_index() # Create a subquestion subquestion = SubQuestion( id=1, question="What is AAPL's current stock price?", depends_on=None ) # Find relevant tools tools = search_tools(subquestion, tool_index) print(f"Found {len(tools)} relevant tools") for tool in tools: print(f" - {tool.__name__}") ``` ``` -------------------------------- ### Configure Verbosity Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/configuration.md Enable verbose output for OpenBB Agents by setting the VERBOSE environment variable to 'True'. ```bash export VERBOSE="True" ``` -------------------------------- ### Asynchronous OpenBB Agent Execution Flow Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/architecture-overview.md Details the asynchronous processing of user queries by the OpenBB Agent. It highlights the use of `asyncio` for concurrent handling of sub-questions, enabling faster responses by processing multiple tasks in parallel. ```text aopenbb_agent(query) ↓ configure_logging(verbose) ↓ _handle_tool_vector_index(openbb_tools) └─→ (Same as sync) ↓ agenerate_subquestions_from_query(query) ├─→ Async LLM Call └─→ Returns: list[SubQuestion] ↓ _aprocess_subquestions(query, subquestions, tool_index) ├─→ While unanswered subquestions remain: │ ├─→ _get_answerable_subquestions() │ │ └─→ Returns subquestions ready to answer │ │ │ ├─→ For each new answerable subquestion: │ │ └─→ asyncio.create_task( │ │ _afetch_tools_and_answer_subquestion() │ │ ) │ │ │ ├─→ asyncio.wait(tasks, return_when=FIRST_COMPLETED) │ │ └─→ Processes completed tasks │ │ │ └─→ Append results to answered_subquestions │ └─→ Returns: list[AnsweredSubQuestion] ↓ generate_final_answer(user_query, answered_subquestions) └─→ (Same as sync) ↓ Return final_answer ``` -------------------------------- ### Fetch Tools and Answer Subquestion (Async) Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/agent-main-api.md Async variant of `_fetch_tools_and_answer_subquestion` for concurrent subquestion resolution. Use this when parallel processing of subquestions is required. ```python async def _afetch_tools_and_answer_subquestion( user_query: str, subquestion: SubQuestion, tool_vector_index: VectorStore, answered_subquestions: list[AnsweredSubQuestion], ) -> AnsweredSubQuestion: pass ``` -------------------------------- ### Authenticate with OpenBB Hub at Runtime Source: https://github.com/openbb-finance/experimental-openbb-platform-agent/blob/main/_autodocs/quick-start.md Authenticate with the OpenBB Hub at runtime using your personal access token (PAT) for accessing services or data. ```python openbb_agent("query", openbb_pat="your-hub-token") ```