Add Mistral AI as LLM provider (#14)

Add Mistral AI as LLM provider
This commit is contained in:
Calesthio
2026-03-19 08:11:19 -07:00
committed by GitHub
7 changed files with 236 additions and 5 deletions

View File

@@ -31,7 +31,7 @@ REFRESH_INTERVAL_MINUTES=15
# === LLM Layer (optional) ===
# Enables AI-enhanced trade ideas and breaking news Telegram alerts.
# Provider options: anthropic | openai | gemini | codex | openrouter | minimax
# Provider options: anthropic | openai | gemini | codex | openrouter | minimax | mistral
LLM_PROVIDER=
# Not needed for codex (uses ~/.codex/auth.json)
LLM_API_KEY=

View File

@@ -166,7 +166,7 @@ Alerts are delivered as rich embeds with color-coded sidebars: red for FLASH, ye
Connect any of 6 LLM providers for enhanced analysis:
- **AI trade ideas** — quantitative analyst producing 5-8 actionable ideas citing specific data
- **Smarter alert evaluation** — LLM classifies signals into FLASH/PRIORITY/ROUTINE tiers with cross-domain correlation and confidence scoring
- Providers: Anthropic Claude, OpenAI, Google Gemini, OpenRouter (Unified API), OpenAI Codex (ChatGPT subscription), MiniMax
- Providers: Anthropic Claude, OpenAI, Google Gemini, OpenRouter (Unified API), OpenAI Codex (ChatGPT subscription), MiniMax, Mistral
- Graceful fallback — when LLM is unavailable, a rule-based engine takes over alert evaluation. LLM failures never crash the sweep cycle.
---
@@ -199,7 +199,7 @@ These three unlock the most valuable economic and satellite data. Each takes abo
### LLM Provider (optional, for AI-enhanced ideas)
Set `LLM_PROVIDER` to one of: `anthropic`, `openai`, `gemini`, `codex`, `openrouter`, `minimax`
Set `LLM_PROVIDER` to one of: `anthropic`, `openai`, `gemini`, `codex`, `openrouter`, `minimax`, `mistral`
| Provider | Key Required | Default Model |
|----------|-------------|---------------|
@@ -209,6 +209,7 @@ Set `LLM_PROVIDER` to one of: `anthropic`, `openai`, `gemini`, `codex`, `openrou
| `openrouter` | `LLM_API_KEY` | openrouter/auto |
| `codex` | None (uses `~/.codex/auth.json`) | gpt-5.3-codex |
| `minimax` | `LLM_API_KEY` | MiniMax-M2.5 |
| `mistral` | `LLM_API_KEY` | mistral-large-latest |
For Codex, run `npx @openai/codex login` to authenticate via your ChatGPT subscription.
@@ -286,6 +287,7 @@ crucix/
│ │ ├── openrouter.mjs # OpenRouter (Unified API)
│ │ ├── codex.mjs # Codex (ChatGPT subscription)
│ │ ├── minimax.mjs # MiniMax (M2.5, 204K context)
│ │ ├── mistral.mjs # Mistral AI
│ │ ├── ideas.mjs # LLM-powered trade idea generation
│ │ └── index.mjs # Factory: createLLMProvider()
│ ├── delta/ # Change tracking between sweeps
@@ -387,7 +389,7 @@ All settings are in `.env` with sensible defaults:
|----------|---------|-------------|
| `PORT` | `3117` | Dashboard server port |
| `REFRESH_INTERVAL_MINUTES` | `15` | Auto-refresh interval |
| `LLM_PROVIDER` | disabled | `anthropic`, `openai`, `gemini`, `codex`, `openrouter`, or `minimax` |
| `LLM_PROVIDER` | disabled | `anthropic`, `openai`, `gemini`, `codex`, `openrouter`, `minimax`, or `mistral` |
| `LLM_API_KEY` | — | API key (not needed for codex) |
| `LLM_MODEL` | per-provider default | Override model selection |
| `TELEGRAM_BOT_TOKEN` | disabled | For Telegram alerts + bot commands |

View File

@@ -7,7 +7,7 @@ export default {
refreshIntervalMinutes: parseInt(process.env.REFRESH_INTERVAL_MINUTES) || 15,
llm: {
provider: process.env.LLM_PROVIDER || null, // anthropic | openai | gemini | codex | openrouter | minimax
provider: process.env.LLM_PROVIDER || null, // anthropic | openai | gemini | codex | openrouter | minimax | mistral
apiKey: process.env.LLM_API_KEY || null,
model: process.env.LLM_MODEL || null,
},

View File

@@ -6,6 +6,7 @@ import { OpenRouterProvider } from './openrouter.mjs';
import { GeminiProvider } from './gemini.mjs';
import { CodexProvider } from './codex.mjs';
import { MiniMaxProvider } from './minimax.mjs';
import { MistralProvider } from './mistral.mjs';
export { LLMProvider } from './provider.mjs';
export { AnthropicProvider } from './anthropic.mjs';
@@ -14,6 +15,7 @@ export { OpenRouterProvider } from './openrouter.mjs';
export { GeminiProvider } from './gemini.mjs';
export { CodexProvider } from './codex.mjs';
export { MiniMaxProvider } from './minimax.mjs';
export { MistralProvider } from './mistral.mjs';
/**
* Create an LLM provider based on config.
@@ -38,6 +40,8 @@ export function createLLMProvider(llmConfig) {
return new CodexProvider({ model });
case 'minimax':
return new MiniMaxProvider({ apiKey, model });
case 'mistral':
return new MistralProvider({ apiKey, model });
default:
console.warn(`[LLM] Unknown provider "${provider}". LLM features disabled.`);
return null;

51
lib/llm/mistral.mjs Normal file
View File

@@ -0,0 +1,51 @@
// Mistral AI Provider — raw fetch, no SDK
// Uses Mistral's OpenAI-compatible Chat Completions API
import { LLMProvider } from './provider.mjs';
export class MistralProvider extends LLMProvider {
constructor(config) {
super(config);
this.name = 'mistral';
this.apiKey = config.apiKey;
this.model = config.model || 'mistral-large-latest';
}
get isConfigured() { return !!this.apiKey; }
async complete(systemPrompt, userMessage, opts = {}) {
const res = await fetch('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
model: this.model,
max_tokens: opts.maxTokens || 4096,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage },
],
}),
signal: AbortSignal.timeout(opts.timeout || 60000),
});
if (!res.ok) {
const err = await res.text().catch(() => '');
throw new Error(`Mistral API ${res.status}: ${err.substring(0, 200)}`);
}
const data = await res.json();
const text = data.choices?.[0]?.message?.content || '';
return {
text,
usage: {
inputTokens: data.usage?.prompt_tokens || 0,
outputTokens: data.usage?.completion_tokens || 0,
},
model: data.model || this.model,
};
}
}

View File

@@ -0,0 +1,30 @@
// Mistral provider — integration test (calls real API)
// Requires MISTRAL_API_KEY environment variable
// Run: MISTRAL_API_KEY=sk-... node --test test/llm-minimax-integration.test.mjs
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { MistralProvider } from '../lib/llm/mistral.mjs';
const API_KEY = process.env.MISTRAL_API_KEY;
describe('Mistral integration', { skip: !API_KEY && 'MISTRAL_API_KEY not set' }, () => {
it('should complete a prompt with mistral large latest', async () => {
const provider = new MistralProvider({ apiKey: API_KEY, model: 'mistral-large-latest' });
assert.equal(provider.isConfigured, true);
const result = await provider.complete(
'You are a helpful assistant. Respond in exactly one sentence.',
'What is 2+2?',
{ maxTokens: 128, timeout: 30000 }
);
assert.ok(result.text.length > 0, 'Response text should not be empty');
assert.ok(result.usage.inputTokens > 0, 'Should report input tokens');
assert.ok(result.usage.outputTokens > 0, 'Should report output tokens');
assert.ok(result.model, 'Should report model name');
console.log(` Response: ${result.text}`);
console.log(` Tokens: ${result.usage.inputTokens} in / ${result.usage.outputTokens} out`);
console.log(` Model: ${result.model}`);
});
});

144
test/llm-mistral.test.mjs Normal file
View File

@@ -0,0 +1,144 @@
// Mistral provider — unit tests
// Uses Node.js built-in test runner (node:test) — no extra dependencies
import { describe, it, mock, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { MistralProvider } from '../lib/llm/mistral.mjs';
import { createLLMProvider } from '../lib/llm/index.mjs';
// ─── Unit Tests ───
describe('MistralProvider', () => {
it('should set defaults correctly', () => {
const provider = new MistralProvider({ apiKey: 'sk-test' });
assert.equal(provider.name, 'mistral');
assert.equal(provider.model, 'mistral-large-latest');
assert.equal(provider.isConfigured, true);
});
it('should accept custom model', () => {
const provider = new MistralProvider({ apiKey: 'sk-test', model: 'mistral-small-2603' });
assert.equal(provider.model, 'mistral-small-2603');
});
it('should report not configured without API key', () => {
const provider = new MistralProvider({});
assert.equal(provider.isConfigured, false);
});
it('should throw on API error', async () => {
const provider = new MistralProvider({ apiKey: 'sk-test' });
const originalFetch = globalThis.fetch;
globalThis.fetch = mock.fn(() =>
Promise.resolve({ ok: false, status: 401, text: () => Promise.resolve('Unauthorized') })
);
try {
await assert.rejects(
() => provider.complete('system', 'user'),
(err) => {
assert.match(err.message, /Mistral API 401/);
return true;
}
);
} finally {
globalThis.fetch = originalFetch;
}
});
it('should parse successful response', async () => {
const provider = new MistralProvider({ apiKey: 'sk-test' });
const mockResponse = {
choices: [{ message: { content: 'Hello from Mistral' } }],
usage: { prompt_tokens: 10, completion_tokens: 5 },
model: 'mistral-large-latest',
};
const originalFetch = globalThis.fetch;
globalThis.fetch = mock.fn(() =>
Promise.resolve({ ok: true, json: () => Promise.resolve(mockResponse) })
);
try {
const result = await provider.complete('You are helpful.', 'Say hello');
assert.equal(result.text, 'Hello from Mistral');
assert.equal(result.usage.inputTokens, 10);
assert.equal(result.usage.outputTokens, 5);
assert.equal(result.model, 'mistral-large-latest');
} finally {
globalThis.fetch = originalFetch;
}
});
it('should send correct request format', async () => {
const provider = new MistralProvider({ apiKey: 'sk-test-key', model: 'mistral-large-latest' });
let capturedUrl, capturedOpts;
const originalFetch = globalThis.fetch;
globalThis.fetch = mock.fn((url, opts) => {
capturedUrl = url;
capturedOpts = opts;
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
choices: [{ message: { content: 'ok' } }],
usage: { prompt_tokens: 1, completion_tokens: 1 },
model: 'mistral-large-latest',
}),
});
});
try {
await provider.complete('system prompt', 'user message', { maxTokens: 2048 });
assert.equal(capturedUrl, 'https://api.mistral.ai/v1/chat/completions');
assert.equal(capturedOpts.method, 'POST');
const headers = capturedOpts.headers;
assert.equal(headers['Content-Type'], 'application/json');
assert.equal(headers['Authorization'], 'Bearer sk-test-key');
const body = JSON.parse(capturedOpts.body);
assert.equal(body.model, 'mistral-large-latest');
assert.equal(body.max_tokens, 2048);
assert.equal(body.messages[0].role, 'system');
assert.equal(body.messages[0].content, 'system prompt');
assert.equal(body.messages[1].role, 'user');
assert.equal(body.messages[1].content, 'user message');
} finally {
globalThis.fetch = originalFetch;
}
});
it('should handle empty response gracefully', async () => {
const provider = new MistralProvider({ apiKey: 'sk-test' });
const originalFetch = globalThis.fetch;
globalThis.fetch = mock.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ choices: [], usage: {} }),
})
);
try {
const result = await provider.complete('sys', 'user');
assert.equal(result.text, '');
assert.equal(result.usage.inputTokens, 0);
assert.equal(result.usage.outputTokens, 0);
} finally {
globalThis.fetch = originalFetch;
}
});
});
// ─── Factory Tests ───
describe('createLLMProvider — mistral', () => {
it('should create MistralProvider for provider=mistral', () => {
const provider = createLLMProvider({ provider: 'mistral', apiKey: 'sk-test', model: null });
assert.ok(provider instanceof MistralProvider);
assert.equal(provider.name, 'mistral');
assert.equal(provider.isConfigured, true);
});
it('should be case-insensitive', () => {
const provider = createLLMProvider({ provider: 'Mistral', apiKey: 'sk-test', model: null });
assert.ok(provider instanceof MistralProvider);
});
it('should return null for empty provider', () => {
const provider = createLLMProvider({ provider: null, apiKey: 'sk-test', model: null });
assert.equal(provider, null);
});
});