This project is a SvelteKit application that provides an interactive chat interface powered by Google's Gemini AI. It allows users to query financial data through Alpha Vantage in natural language conversation, for example - "Give me a quick analysis of AAPL this week" and the bot retrieves the data and conduct the analysis without explicit instructions.
- AI-Powered Chat: Engage in natural language conversations with a sophisticated AI model.
- Real-time Stock Analysis: Query stock quotes, historical daily data, and search for stock symbols using Alpha Vantage.
- Dynamic Tool Integration: Utilizes the
@ai-sdk/mcplibrary for discovering and executing tools from an external service, with a robust fallback to direct REST API calls. - SvelteKit Frontend: A modern, responsive user interface built with Svelte and SvelteKit.
- Streaming Responses: AI responses are streamed in real-time for a dynamic user experience.
- Frontend: Svelte, SvelteKit, TypeScript
- Backend API: SvelteKit, TypeScript, Node.js
- AI Model: Google Gemini (via
@ai-sdk/google) - Financial Data: Alpha Vantage
- Tooling:
@ai-sdk/mcp(Meta-Compute Protocol) with REST fallback,zodfor schema validation - Build Tools: Vite
- Linting & Formatting: ESLint, Prettier
This project features several complex integrations designed for flexibility and robustness:
The application uses the @ai-sdk/google package to interact with Google's Gemini models. The createGoogleGenerativeAI function is initialized with your GOOGLE_GENERATIVE_AI_API_KEY. The geminiModel function provides a convenient way to instantiate specific Gemini models, defaulting to gemini-2.5-flash for its balance of speed and capability.
This integration is designed with a two-tiered approach:
- MCP (Meta-Compute Protocol) Integration: The project attempts to dynamically import and utilize the
@ai-sdk/mcplibrary. If successful andALPHA_MCP_URLis configured, it connects to an MCP server to discover available tools (e.g., for stock quotes, time series data). This approach allows for flexible tool management without hardcoding tool definitions directly into the API route. - REST Fallback: If the MCP integration fails (e.g., the
@ai-sdk/mcppackage is not installed,ALPHA_MCP_URLis not set, or the MCP server is unreachable), the application gracefully falls back to a set of manually defined REST tools. These tools (global_quote,time_series_daily,symbol_search) are implemented usingzodfor strict input schema validation and standardfetchAPI calls to Alpha Vantage. This ensures that financial data querying remains functional even without a configured MCP service.
This API route handles incoming chat messages. It performs the following key functions:
- Request Handling: Listens for POST requests containing user messages.
- Environment Validation: Checks for the presence of necessary API keys.
- Dynamic Tool Loading: Attempts to load tools via MCP, falling back to REST tools if necessary.
- Message Conversion: Transforms UI messages into a format suitable for the AI model using
convertToModelMessages. - AI Interaction: Uses
streamTextfrom the AI SDK to send messages and tools to the Gemini model. - Streaming Response: Returns a
Responseobject that streams UI-compatible messages, allowing the frontend to display responses as they are generated. - Error Handling: Includes basic error handling for API key issues and MCP integration failures.
- Resource Management: Ensures the MCP client is gracefully closed upon completion.
The frontend provides the user interface for the chat application.
- Chat Component: Leverages the
@ai-sdk/svelteChatcomponent for managing chat state and rendering messages. - UI State Management: Manages input fields, sending/streaming indicators, error messages, and progress bars.
- Message Rendering: Displays user messages, AI responses (including text, tool calls, and potential errors), and metadata. It includes a
renderPartfunction to handle different message part types (text, images, tool outputs). - Scrolling Fix: Implements a robust scrolling mechanism using
requestAnimationFrameto ensure new messages are always visible as they appear. - User Interaction: Supports sending messages via button click or Enter key, stopping ongoing generation, retrying failed messages, and clearing input.
- Security: Implement input validation for all user-submitted data to prevent prompt injection. Add authentication and authorization to the API endpoint. Implement rate limiting to prevent abuse and manage costs.
- Error Handling: Provide more specific and user-friendly error messages.
- Abort Controller: Ensure the
AbortControlleris correctly passed and utilized by thesendMessagemethod to enable effective stopping of AI generation. - Model Choice: Consider using a more capable AI model if complex reasoning is required.
- Persistence: Implement chat history persistence (e.g., saving to a database or local storage) for a better user experience.
