Mistral API Usage - PikaBotz/My_Personal_Space GitHub Wiki


🆕 Free Mistral AI API

🔗 Parameters:

    1. apikey: Access key for authenticating requests.
    1. message: The prompt or message you want to send to the AI.

API ENDPOINT:

https://pikabotzapi.vercel.app/ai/mistral/


USAGE EXAMPLE:

🌟 GET Method:

  • Pros: Direct API access, no additional handler required.
  • Cons: Chatbot can't remember previous chats.

https://pikabotzapi.vercel.app/ai/mistral/?apikey=anya-md&message=Introduce%20Yourself

🌟 POST Method:

  • Pros: Chatbot can remember previous chats (stores conversation history).
  • Cons: Requires JSON handler structure for storing chat data.
const fs = require("fs");
const path = require("path");
const axios = require("axios");

const dataPath = path.join(__dirname, "PikaBotz_Mistral.json");

// Function to load stored data
const loadData = () => fs.existsSync(dataPath) ? JSON.parse(fs.readFileSync(dataPath, "utf-8")) : {};

// Function to save data
const saveData = (data) => fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));

// Function to interact with Mistral AI
const mistral = async (message, userId) => {
  if (!message) return "Message prompt is missing";  // Check if message is provided
  
  const data = loadData(); // Load existing conversation data
  const userMessages = data[userId] || []; // Retrieve user-specific messages or initialize an empty array
  
  userMessages.push({
    content: message,
    role: "user",  // Role is 'user' for input messages
  });

  const _previousMsg = userMessages.slice(-20); // Limit the history to the last 20 messages
  data[userId] = _previousMsg; // Update the conversation history for the user

  try {
    // Send POST request to Mistral AI API
    const response = await axios.post(
      `https://pikabotzapi.vercel.app/ai/mistral_anya/?apikey=anya-md`,
      { messages: _previousMsg },  // Send message history to AI
      { headers: { "Content-Type": "application/json" } }
    );

    // Check if response contains status and message
    if (!response.data.status || !response.data.message) {
      return response.data.message || "Unable to fetch API"; // Handle missing message
    }

    const aiResponse = response.data.message;  // Get the AI response
    _previousMsg.push({
      content: aiResponse,
      role: "assistant",  // Role is 'assistant' for AI's response
    });

    saveData(data); // Save updated conversation history
    return aiResponse; // Return the AI's response
  } catch (error) {
    console.error("Error calling Anya API:", error.response?.data || error.message);
    return "An error occurred while communicating with the AI."; // Handle API errors
  }
};

module.exports = { mistral };  // Export the function for use in other files

// Usage:
// mistral('Hello, your intro?', '1234@userId')
//   .then(response => console.log(response))
//   .catch(err => console.error(err));