Skip to content

Lesson 4: Web Search Integration for Enhanced Analysis

This lesson adds web search capabilities to our financial agent, allowing it to access current market news and analysis for more comprehensive responses.

  1. Switch to Lesson 4 directory:

    cd workshop/dotnet/Lessons/Lesson4
    
  2. Copy the configuration file from the Solutions directory:

    cp ../../Solutions/Lesson4/appsettings.json .
    
  3. Run the application to see it works:

    dotnet run
    
  4. Open Program.cs and add web search capabilities to the financial agent:

    1. TODO: Step 1 - Initialize the chat client, plugins, and web search tool:

      IChatClient chatClient = AgentFrameworkProvider.CreateChatClientWithApiKey();
      
      // Initialize plugins
      TimeInformationPlugin timePlugin = new();
      HttpClient httpClient = new();
      StockDataPlugin stockDataPlugin = new(new StocksService(httpClient));
      
      // Create web search tool for enhanced sentiment analysis
      HostedWebSearchTool webSearchTool = new();
      
    2. TODO: Step 2 - Create AI Functions including web search:

      var timeTool = AIFunctionFactory.Create(timePlugin.GetCurrentUtcTime);
      var stockPriceTool = AIFunctionFactory.Create(stockDataPlugin.GetStockPrice);
      var stockPriceDateTool = AIFunctionFactory.Create(stockDataPlugin.GetStockPriceForDate);
      
    3. TODO: Step 3 - Define enhanced system instructions with web search capabilities:

      string stockSentimentAgentInstructions = """
          You are a Financial Analysis Agent with web search capabilities. Provide direct, comprehensive financial analysis and insights based on user questions.
      
          CAPABILITIES:
          - Analyze individual stocks, market sectors, or broader financial topics
          - Extract stock symbols from user queries when relevant (e.g., "What do you think about Microsoft?" -> analyze MSFT)
          - Handle free-form questions about market trends, economic conditions, investment strategies
          - Use stock sentiment scale from 1 to 10 where sentiment is 1 for sell and 10 for buy (when analyzing specific stocks)
          - Provide ratings, recommendations (buy/hold/sell), and detailed reasoning for stock-specific queries
      
          CRITICAL RULES:
          - Provide your complete analysis in a SINGLE response - do not say you're "gathering data" or "working on it"
          - For stock-specific questions: Use web search to gather current market news, analyst opinions, and sentiment data
          - For general financial questions: Use web search to find relevant financial news, economic data, and expert analysis
          - Combine web search results with available stock price data when analyzing specific companies
          - ALWAYS include a dedicated "Sources" section at the end of your response listing all the specific sources you found through web search
          - For each source, include the title, URL (if available), and a brief description of what information it provided
          - Focus on recent news, market trends, and expert analysis
          - Be transparent about which information came from which sources
          - If a user asks about a specific company without mentioning the stock symbol, try to identify the relevant ticker symbol
          - Answer immediately with your full analysis - do not provide status updates or say you're collecting information
          """;
      
    4. TODO: Step 4 - Create the Financial Analysis Agent with web search capabilities:

      ChatClientAgent financialAnalysisAgent = new(
          chatClient,
          instructions: stockSentimentAgentInstructions,
          name: "FinancialAnalysisAgent",
          description: "An intelligent agent that provides comprehensive financial analysis using web search and market data",
          tools: [
              timeTool,
              stockPriceTool, 
              stockPriceDateTool,
              webSearchTool
          ]
      );
      
    5. TODO: Step 5 - Create thread and process requests with web search:

      AgentThread thread = financialAnalysisAgent.GetNewThread();
      
      var response = await financialAnalysisAgent.RunAsync(userInput, thread);
      
      if (response?.Messages?.Any() == true)
      {
          var lastMessage = response.Messages.Last();
          Console.WriteLine(lastMessage.Text ?? "No response generated.");
      }
      
  5. Test the enhanced agent with various financial queries:

    dotnet run
    

    Example questions to test:

    User > What do you think about Microsoft?
    Assistant > (should search for recent Microsoft news and provide analysis with sources)
    
    User > How is the tech sector performing?
    Assistant > (should search for tech sector news and provide comprehensive analysis)
    
    User > Should I invest in renewable energy stocks?
    Assistant > (should search for renewable energy market trends and provide recommendations)
    

This lesson demonstrates how web search integration enhances the agent's ability to provide current, well-sourced financial analysis by accessing real-time market information and expert opinions.