# Octagon AI > Octagon provides specialized investment research Agents through an OpenAI-compatible API to build financial applications. These agents have been trained on domain-specific financial data of public and private companies from real-time verifiable data sources. # How Octagon API Works Octagon AI offers a suite of specialized investment research agents through an OpenAI-compatible API. These agents are designed for specific investment research domains and provide enhanced capabilities for financial analysis, SEC filing examination, earnings call transcript analysis, and more. ## API Architecture and Integration The Octagon API is built to be fully compatible with the OpenAI API format, allowing developers to seamlessly integrate financial research capabilities with minimal code changes. This means you can use the same client libraries and code patterns you're already familiar with - just switch the base URL to the Octagon API endpoint and use your Octagon API key. The API follows RESTful principles with JSON-based request and response formats. Authentication is handled via API keys in the Authorization header, similar to OpenAI's authentication method. This compatibility ensures that if you're already using OpenAI's API, transitioning to include Octagon's specialized financial agents is straightforward. ## Core Concepts 1. **Agents**: Specialized AI models trained on domain-specific financial data 2. **Chat Completions**: OpenAI-compatible endpoint for conversational interactions with agents 3. **Responses API**: Enhanced response format providing structured financial data 4. **Financial Citations**: Source attribution for financial data included in responses ## Getting Started with Code Examples Here are basic examples to help you quickly understand how to use the Octagon API: ## Example - Basic Usage ```Python from openai import OpenAI # Initialize the client with Octagon's API base and your API key client = OpenAI( base_url="https://api-gateway.octagonagents.com/v1", api_key="your-octagon-api-key" # Replace with your actual API key ) # Make a request to the SEC Filings Agent response = client.chat.completions.create( model="octagon-sec-agent", # Specify which specialized agent to use messages=[ {"role": "user", "content": "What were the key risk factors mentioned in Apple's latest 10-K?"} ] ) # Print the response print(response.choices[0].message.content) ``` ### JavaScript Example - Basic Usage ```JavaScript import OpenAI from 'openai'; // Initialize the client with Octagon's API base and your API key const client = new OpenAI({ baseURL: 'https://api-gateway.octagonagents.com/v1', apiKey: 'your-octagon-api-key', // Replace with your actual API key }); // Async function to query the Transcripts Agent async function analyzeEarningsCall() { const response = await client.chat.completions.create({ model: 'octagon-transcripts-agent', // Specify which specialized agent to use messages: [ { role: 'user', content: 'What was discussed about AI initiatives in Microsoft\'s latest earnings call?' } ] }); console.log(response.choices[0].message.content); } analyzeEarningsCall(); ``` ## Example - Using Financial Citations ```Python from openai import OpenAI import json # Initialize the client client = OpenAI( base_url="https://api-gateway.octagonagents.com/v1", api_key="your-octagon-api-key" ) # Make a request to the Financials Agent with citations response = client.chat.completions.create( model="octagon-financials-agent", messages=[ {"role": "user", "content": "Compare the profit margins of Apple and Microsoft for the last fiscal year"} ], response_format={"type": "json_object"} # Request JSON format for structured data ) # Parse the JSON response content = json.loads(response.choices[0].message.content) # Access the citations if they exist if 'citations' in content: for citation in content['citations']: print(f"Source: {citation['source']}") print(f"Data point: {citation['text']}") print(f"URL: {citation['url']}") print("---") # Print the analysis print("Analysis:", content['analysis'] if 'analysis' in content else content) ``` ### Advanced Example - Multi-Agent Research Workflow ```Python from openai import OpenAI # Initialize the client client = OpenAI( base_url="https://api-gateway.octagonagents.com/v1", api_key="your-octagon-api-key" ) # Step 1: Get SEC filing information def get_sec_filing_info(company, filing_type): response = client.chat.completions.create( model="octagon-sec-agent", messages=[ {"role": "user", "content": f"Find the latest {filing_type} filing for {company} and summarize the key points"} ] ) return response.choices[0].message.content # Step 2: Analyze financial metrics def analyze_financials(company): response = client.chat.completions.create( model="octagon-financials-agent", messages=[ {"role": "user", "content": f"Analyze the key financial ratios for {company} in the latest quarter"} ] ) return response.choices[0].message.content # Step 3: Check recent earnings call def analyze_earnings_call(company): response = client.chat.completions.create( model="octagon-transcripts-agent", messages=[ {"role": "user", "content": f"What were the main points discussed in {company}'s latest earnings call?"} ] ) return response.choices[0].message.content # Execute the workflow for a company company_name = "Tesla" print("=== COMPREHENSIVE COMPANY ANALYSIS ===") print("\n== SEC FILING ANALYSIS ==") sec_info = get_sec_filing_info(company_name, "10-Q") print(sec_info) print("\n== FINANCIAL METRICS ==") financial_analysis = analyze_financials(company_name) print(financial_analysis) print("\n== EARNINGS CALL INSIGHTS ==") earnings_insights = analyze_earnings_call(company_name) print(earnings_insights) ``` ## API Documentation - [Introduction to Octagon](https://docs.octagonagents.com/docs/guide/introduction.html.md): This section provides a comprehensive overview of Octagon's capabilities, explaining the key differentiators of the platform, such as domain-specific training on financial data, verifiable source citations, and specialized financial reasoning. It also covers common use cases for investment research, including company analysis, SEC filing examination, and earnings call insights. - [REST API Documentation](https://docs.octagonagents.com/docs/guide/rest-api/index.html.md): This guide offers detailed documentation on all aspects of the Octagon API, covering endpoint specifications, request parameters, response formats, error handling, and rate limits. It explains the architecture of the API and how it interfaces with various financial data sources to provide accurate, up-to-date information. - [Authentication Guide](https://docs.octagonagents.com/docs/guide/rest-api/authentication.html.md): This section walks through the authentication process for the Octagon API, explaining how to obtain API keys, properly include them in requests, manage permissions, and implement best practices for API key security. It also covers authentication troubleshooting and common issues. - [Available Agents](https://docs.octagonagents.com/docs/guide/agents.html.md): This page provides detailed information about each specialized agent, including their domains of expertise, training data sources, specific capabilities, parameter customizations, and optimal use cases. Each agent is described with examples of appropriate queries and expected response formats. - [Chat Completions API](https://docs.octagonagents.com/docs/guide/rest-api/chat-completions.html.md): This documentation explains how to use the OpenAI-compatible chat completions endpoint with Octagon agents. It covers conversation formatting, agent selection via model parameters, temperature settings, response formatting options, and streaming capabilities. The guide includes examples of properly structured requests and response handling. - [Responses API](https://docs.octagonagents.com/docs/guide/rest-api/responses.html.md): This section details the enhanced Responses API format, which provides structured financial data alongside narrative responses. It explains how to parse the structured components, access tabular financial data, utilize time-series information, and handle nested data structures in the enhanced response format. ## SDK Integration - [OpenAI Agents SDK Integration](https://docs.octagonagents.com/docs/guide/agents-sdk/index.html.md): This documentation explains how to integrate Octagon agents with the OpenAI Agents SDK, allowing for the creation of multi-agent workflows that combine OpenAI models with Octagon's specialized financial agents. It covers installation, configuration, agent selection, and communication patterns between agents. - [Research Workflow Example](https://docs.octagonagents.com/docs/guide/agents-sdk/research-workflow.html.md): This section provides a complete example of building a multi-agent research workflow, demonstrating how to combine different Octagon agents to create comprehensive financial analysis pipelines. It walks through setting up a workflow that gathers earnings data, analyzes financial statements, and compares against industry benchmarks, with code examples for each step. ## Public Market Intelligence Agents - [SEC Filings Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-sec-agent): This agent analyzes SEC filings data from over 6,000 companies, including 10-K, 10-Q, 8-K, proxy statements, and other regulatory documents. It can extract specific financial data points, analyze trends across filings, identify risk factors, and compare disclosures across reporting periods. The agent is trained on the structure and content of SEC filings to provide accurate contextual understanding. - [Transcripts Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-transcripts-agent): This agent specializes in analyzing earnings call transcripts, management commentary, and forward-looking statements. It can identify sentiment, extract guidance information, pinpoint management priorities, analyze Q&A exchanges, and track changes in strategic focus over time. The agent comprehends both the content and the context of management discussions. - [Stock Data Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-stock-data-agent): This agent analyzes stock prices, trading volumes, market trends, and technical indicators. It can provide historical performance data, comparative analysis against benchmarks or competitors, volatility assessments, momentum analysis, and correlation studies. The agent works with both historical and near real-time market data. - [Financials Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-financials-agent): This agent analyzes financial statements, ratios, and performance metrics for public companies. It can calculate and interpret key financial ratios, identify trends in revenue, margins, and profitability, perform peer comparisons, and evaluate financial health indicators. The agent works with standardized financial data from company reports. ## Private Market Intelligence Agents - [Companies Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-companies-agent): This agent provides detailed information on private companies, including founding history, product offerings, team details, and competitive landscape. It can research company structures, analyze market positioning, identify leadership backgrounds, and track product evolution over time. The agent draws from various private company data sources. - [Funding Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-funding-agent): This agent specializes in analyzing startup funding rounds, investors, and valuation data. It can track funding histories, identify key investors and their portfolios, analyze valuation trends, compare funding against industry benchmarks, and evaluate capital efficiency metrics. The agent works with comprehensive venture capital and private funding databases. - [Deals Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-deals-agent): This agent analyzes M&A activities, IPOs, and other financial transactions. It can research transaction terms, evaluate acquisition premiums, analyze post-deal performance, identify synergies and strategic rationales, and track industry consolidation trends. The agent incorporates both historical deal data and transaction documentation. ## Deep Research Agents - [Scraper Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-scraper-agent): This agent extracts structured data from financial websites and online sources. It can pull information from company websites, news articles, industry publications, and other public web sources. The agent transforms unstructured web content into organized, relevant financial data points that can be used in analysis. - [Deep Research Agent](https://docs.octagonagents.com/docs/guide/agents.html#octagon-deep-research-agent): This comprehensive agent performs research across multiple data sources, synthesizing information from SEC filings, earnings calls, financial statements, news, and other sources. It can conduct complex multi-step research processes, draw connections between different information sources, and provide comprehensive reports on research questions. ## Integration Examples ## Integration Example ```Python # Complete Python integration example import os from openai import OpenAI # Set up environment variables for security # In production, use proper environment variable management os.environ["OCTAGON_API_KEY"] = "your-octagon-api-key" # Initialize the client with Octagon's base URL and API key client = OpenAI( base_url="https://api-gateway.octagonagents.com/v1", api_key=os.environ.get("OCTAGON_API_KEY") ) def query_octagon_agent(agent_model, query, stream=False): """ General function to query any Octagon agent. Parameters: - agent_model: Name of the Octagon agent model to use - query: The user query to send to the agent - stream: Whether to stream the response (default: False) Returns: - Agent response """ try: response = client.chat.completions.create( model=agent_model, messages=[ {"role": "system", "content": "You are a helpful financial research assistant."}, {"role": "user", "content": query} ], stream=stream ) if stream: # Handle streaming response for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") print() return None else: # Return the complete response return response.choices[0].message.content except Exception as e: print(f"Error querying Octagon API: {e}") return None # Example usage if __name__ == "__main__": # Query the SEC Filings Agent sec_query = "What were the major risk factors disclosed in Tesla's latest 10-K filing?" print("\n===== SEC FILINGS AGENT RESPONSE =====") sec_response = query_octagon_agent("octagon-sec-agent", sec_query) print(sec_response) # Query the Financials Agent financials_query = "Compare the gross margins of Apple, Microsoft, and Google for the last 4 quarters." print("\n===== FINANCIALS AGENT RESPONSE =====") financials_response = query_octagon_agent("octagon-financials-agent", financials_query) print(financials_response) # Stream a response from the Transcripts Agent transcripts_query = "Summarize the key points from Amazon's latest earnings call." print("\n===== TRANSCRIPTS AGENT STREAMING RESPONSE =====") query_octagon_agent("octagon-transcripts-agent", transcripts_query, stream=True) ``` ### JavaScript/TypeScript Integration Example ```JavaScript // Complete JavaScript integration example import OpenAI from 'openai'; // In a real app, use environment variables or secure storage const OCTAGON_API_KEY = 'your-octagon-api-key'; // Initialize the OpenAI client with Octagon's base URL const client = new OpenAI({ baseURL: 'https://api-gateway.octagonagents.com/v1', apiKey: OCTAGON_API_KEY, }); /** * Query an Octagon agent with a user prompt * @param {string} agentModel - The Octagon agent model to use * @param {string} query - The user query to send to the agent * @param {boolean} stream - Whether to stream the response * @returns {Promise} - The agent's response or null if streaming */ async function queryOctagonAgent(agentModel, query, stream = false) { try { const response = await client.chat.completions.create({ model: agentModel, messages: [ { role: 'system', content: 'You are a helpful financial research assistant.' }, { role: 'user', content: query } ], stream: stream }); if (stream) { // Handle streaming response for await (const chunk of response) { if (chunk.choices[0]?.delta?.content) { process.stdout.write(chunk.choices[0].delta.content); } } console.log(); // New line after stream completes return null; } else { // Return complete response return response.choices[0].message.content; } } catch (error) { console.error('Error querying Octagon API:', error); return null; } } // Example usage as an async function async function runExamples() { // Query the Companies Agent const companiesQuery = "Provide an overview of Stripe's business model, key products, and main competitors."; console.log("\n===== COMPANIES AGENT RESPONSE ====="); const companiesResponse = await queryOctagonAgent("octagon-companies-agent", companiesQuery); console.log(companiesResponse); // Query the Stock Data Agent const stockDataQuery = "Show the performance of Tesla stock over the last 6 months compared to the S&P 500."; console.log("\n===== STOCK DATA AGENT RESPONSE ====="); const stockDataResponse = await queryOctagonAgent("octagon-stock-data-agent", stockDataQuery); console.log(stockDataResponse); // Stream a response from the Deals Agent const dealsQuery = "What were the largest tech acquisitions in the past year?"; console.log("\n===== DEALS AGENT STREAMING RESPONSE ====="); await queryOctagonAgent("octagon-deals-agent", dealsQuery, true); } // Run the examples runExamples().catch(console.error); ``` ### OpenAI SDK Integration Example ```Python # Integration with OpenAI Agents SDK from openai import OpenAI import os # Configure the API client with Octagon's base URL client = OpenAI( base_url="https://api-gateway.octagonagents.com/v1", api_key="your-octagon-api-key" ) # Create an assistant that utilizes Octagon agents assistant = client.beta.assistants.create( name="Financial Research Assistant", instructions="""You are a financial research assistant powered by Octagon AI. Use the specialized financial agents to provide accurate insights on companies, markets, and investment opportunities.""", model="gpt-4o", # Base model tools=[ { "type": "function", "function": { "name": "query_sec_filings", "description": "Query the SEC Filings Agent for information from SEC documents", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The question about SEC filings" }, "company": { "type": "string", "description": "The company to research" } }, "required": ["query", "company"] } } }, { "type": "function", "function": { "name": "analyze_financials", "description": "Analyze financial metrics using the Financials Agent", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The financial analysis question" }, "companies": { "type": "array", "items": { "type": "string" }, "description": "List of companies to analyze" } }, "required": ["query"] } } } ] ) # Function implementations that call the appropriate Octagon agents def query_sec_filings(query, company): response = client.chat.completions.create( model="octagon-sec-agent", messages=[{"role": "user", "content": f"{query} for {company}"}] ) return response.choices[0].message.content def analyze_financials(query, companies=None): if companies: company_list = ", ".join(companies) prompt = f"{query} for {company_list}" else: prompt = query response = client.chat.completions.create( model="octagon-financials-agent", messages=[{"role": "user", "content": prompt}] ) return response.choices[0].message.content # Create a thread for the conversation thread = client.beta.threads.create() # Add a message to the thread message = client.beta.threads.messages.create( thread_id=thread.id, role="user", content="Compare the financial performance of Apple and Microsoft in the last quarter." ) # Run the assistant on the thread run = client.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id ) # Process function calls from the assistant # In a real application, you would implement a polling mechanism or use webhooks # This is a simplified example import time while True: run_status = client.beta.threads.runs.retrieve( thread_id=thread.id, run_id=run.id ) if run_status.status == "requires_action": tool_calls = run_status.required_action.submit_tool_outputs.tool_calls tool_outputs = [] for tool_call in tool_calls: function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if function_name == "query_sec_filings": output = query_sec_filings(function_args["query"], function_args["company"]) elif function_name == "analyze_financials": output = analyze_financials(function_args["query"], function_args.get("companies")) tool_outputs.append({ "tool_call_id": tool_call.id, "output": output }) # Submit the outputs back to the assistant client.beta.threads.runs.submit_tool_outputs( thread_id=thread.id, run_id=run.id, tool_outputs=tool_outputs ) elif run_status.status == "completed": # Get the final response messages = client.beta.threads.messages.list( thread_id=thread.id ) for message in messages.data: if message.role == "assistant": print(f"Assistant: {message.content[0].text.value}") break elif run_status.status in ["failed", "cancelled", "expired"]: print(f"Run failed with status: {run_status.status}") break time.sleep(1) # Poll every second ```