मुख्य सामग्री पर जाएँ

Mistral Agents API: डेमो प्रोजेक्ट के साथ मार्गदर्शिका

Mistral के Agents API का उपयोग करके AI एजेंट बनाना सीखें, और टूल उपयोग, कनेक्टर्स, हैंडऑफ़्स आदि जैसे प्रमुख कॉन्सेप्ट्स खोजें।
· 12 मि॰ पढ़ें

AI के साथ खोजें

Mistral ने Agents API जारी किया है, जो एक ऐसा फ़्रेमवर्क है जो बुद्धिमान, स्वायत्त AI एजेंट्स के विकास को संभव बनाता है जो जटिल, बहु-चरणीय कार्यों को पूरा कर सकते हैं। यह टूल उपयोग, स्थायी मेमोरी और ऑर्केस्ट्रेशन क्षमताओं को जोड़कर पारंपरिक भाषा मॉडलों से आगे बढ़ता है।

इस ट्यूटोरियल में, मैं आपको दिखाऊँगा कि कैसे Mistral Agents API का उपयोग करके ऐसे बुद्धिमान असिस्टेंट बनाते हैं जो यह कर सकें:

  • वेब सर्च, कोड निष्पादन और इमेज जेनरेशन जैसे टूल्स का उपयोग
  • लंबी बातचीत में संदर्भ बनाए रखने के लिए मेमोरी रखना
  • कई एजेंट्स के बीच कार्य सौंपना

आप Mistral के एजेंटिक फ़्रेमवर्क के मूल सिद्धांत सीखेंगे, बिल्ट-इन कनेक्टर्स और ऑर्केस्ट्रेशन फ़ीचर्स का अन्वेषण करेंगे, और एक काम करने वाला मल्टी-एजेंट असिस्टेंट बनाएँगे।

हम अपने पाठकों को The Median, हमारे मुफ़्त शुक्रवार न्यूज़लेटर, के माध्यम से AI की नवीनतम ख़बरों से अपडेट रखते हैं, जो हफ्ते की प्रमुख कहानियों का सार बताता है। कुछ मिनटों में तेज़ बने रहने के लिए सब्सक्राइब करें:

Mistral का Agents API क्या है?

Mistral Agents API एक ऐसा फ़्रेमवर्क है जो बड़े भाषा मॉडलों को बहु-चरणीय कार्रवाइयाँ करने, बाहरी टूल्स का उपयोग करने और इंटरैक्शंस के दौरान मेमोरी बनाए रखने में सक्षम बनाता है। साधारण चैट APIs के विपरीत, यह AI एजेंट्स को सक्षम बनाता है कि वे:

  • वेब तक पहुंचें, कोड चलाएँ, इमेज बनाएँ, या दस्तावेज़ प्राप्त करें
  • ऑर्केस्ट्रेशन के माध्यम से अन्य एजेंट्स के साथ समन्वय करें
  • लंबी अवधि की मेमोरी के साथ स्थायी बातचीत बनाए रखें

वर्तमान में केवल mistral-medium-latest (जिसे mistral-medium-2505 भी कहा जाता है) और mistral-large-latest सपोर्टेड हैं, लेकिन जल्द ही नए मॉडल्स भी सपोर्ट हो सकते हैं।

मुख्य कॉन्सेप्ट्स समझाए गए

हैंड्स-ऑन भाग में जाने से पहले, Agents API के मुख्य कॉन्सेप्ट्स स्पष्ट करना उपयोगी होगा।

mistral agents api diagram

स्रोत: Mistral AI

एजेंट्स

एजेंट्स Mistral में मॉडल-संचालित पर्सोना हैं जिन्हें पूर्वनिर्धारित निर्देशों, टूल एक्सेस और बातचीत की स्थिति से समृद्ध किया गया है:

  • निर्देश एजेंट के व्यवहार का मार्गदर्शन करते हैं (उदा., “आप एक भोजन-लॉगिंग न्यूट्रिशन कोच हैं”).
  • web_search या image_generation जैसे टूल्स एजेंट्स को वास्तविक दुनिया की कार्रवाइयाँ करने देते हैं।
  • मेमोरी एजेंट्स को कई टर्न्स में पिछले संदेशों और टूल आउटपुट्स को ट्रैक करने देती है, जिससे संदर्भ-आधारित तर्क संभव होता है।

यह एब्स्ट्रैक्शन एक बेसिक चैट मॉडल को मल्टी-फ़ंक्शनल असिस्टेंट में बदल देता है जो जटिल वर्कफ़्लोज़ में संलग्न हो सकता है।

कन्वर्सेशंस 

उपयोगकर्ता और एजेंट के बीच हर इंटरैक्शन एक बातचीत का हिस्सा होता है, जो यह संग्रहीत करता है:

  • पिछले संदेश और असिस्टेंट के उत्तर
  • टूल कॉल्स और उनके परिणाम
  • टोकन-स्तरीय दृश्यता के लिए स्ट्रीमिंग मेटाडेटा (वैकल्पिक)

ये स्थायी बातचीत एजेंट्स को प्लानिंग, संशोधन या पहले के इनपुट्स से सीखने जैसे मल्टी-टर्न कार्यों को पूरा करने देती हैं।

कनेक्टर्स और कस्टम टूल सपोर्ट

Mistral आसान टूल इंटीग्रेशन सक्षम करता है, इन माध्यमों से:

  • कनेक्टर्स: ये प्री-इंटीग्रेटेड टूल्स हैं जैसे web_search, code_execution, image_generation, document_library जो बॉक्स से बाहर काम करते हैं।
  • MCP टूल्स: ये डेवलपर्स द्वारा होस्ट की गई कस्टम APIs होती हैं जिन्हें एजेंट वर्कफ़्लो के अंदर टूल्स की तरह कॉल किया जा सकता है।

कनेक्टर्स को बिल्ट-इन ऐप्स समझें, और MCP टूल्स को ऐसे प्लगइन्स जिन्हें आप लिखते हैं। साथ मिलकर, ये एजेंट्स को बिल्ट-इन क्षमताओं और डेवलपर-परिभाषित एंडपॉइंट्स तक पहुंच देते हैं ताकि निजीकरणयुक्त लॉजिक लागू हो सके।

mistral agents api mcp diagram

स्रोत: Mistral AI

एंट्रीज़ और हैंडऑफ़्स

Mistral किसी बातचीत में सभी कार्रवाइयों को संरचित “एंट्रीज़” के रूप में ट्रैक करता है, जिससे संदेशों के आदान-प्रदान और टूल निष्पादन पर ट्रेसएबिलिटी और नियंत्रण संभव होता है।

एजेंट हैंडऑफ़्स वे हैं जहाँ एक एजेंट वर्कफ़्लोज़ को मॉड्यूलर बनाने के लिए नियंत्रण दूसरे एजेंट को सौंपता है।

mistral agent handoffs

स्रोत: Mistral AI

यह ऑर्केस्ट्रेशन आर्किटेक्चर जटिल मल्टी-एजेंट सिस्टम्स को पारदर्शिता या नियंत्रण गंवाए बिना संयोजित और प्रबंधित करना आसान बनाता है।

Mistral API सेटअप करना

आइए Mistral को सेटअप करने से शुरू करें। हम प्रोजेक्ट के लिए एक API कुंजी बनाकर शुरुआत करेंगे। ये चरण अपनाएँ:

  1. शुरू करने के लिए, console.mistral.ai पर एक Mistral खाता बनाएँ या साइन इन करें।

Mistral dashboard

  1. फिर, Workspace Settings (आपके नाम के पास ड्रॉपडाउन तीर—ऊपरी बाएँ कोना) पर जाएँ और Billing पर क्लिक करके अपना भुगतान विवरण जोड़ें और अपने खाते पर पेमेंट्स सक्रिय करें।

Mistral billing

  1. Add credits पर क्लिक करें और फ़ॉर्म में अपना बिलिंग विवरण भरें। फिर, आप जितने क्रेडिट्स चाहते हैं वह संख्या भरें। नोट: आपको कम से कम 10 क्रेडिट्स जोड़ने होंगे।

Mistral credits

  1. इसके बाद, बाएँ टैब में API keys पर क्लिक करें और Create new key पर क्लिक करके एक नई API कुंजी बनाएँ। API कुंजी को कॉपी करना, सुरक्षित रखना और किसी से साझा न करना सुनिश्चित करें।

अब आपके पास Mistral मॉडल्स के साथ इंटरैक्ट करने और बुद्धिमान एजेंट्स बनाने के लिए एक वैध API कुंजी है।

प्रोजेक्ट अवलोकन: Mistral Agents के साथ न्यूट्रिशन कोच

इस प्रोजेक्ट में, हम Mistral के Agents API का उपयोग करके एक AI-संचालित न्यूट्रिशन कोच बनाएँगे। उपयोगकर्ता प्रवाह इस प्रकार है:

  1. उपयोगकर्ता अभी खाया हुआ भोजन सबमिट करता है (उदा., "ऑलिव ऑयल ड्रेसिंग के साथ चिकन सलाद").
  2. एक वेब सर्च एजेंट बिल्ट-इन कनेक्टर का उपयोग करके भोजन के लिए कैलोरी का अनुमान लगाता है।
  3. एक लॉगर एजेंट इसे उपयोगकर्ता के नाम और टाइमस्टैम्प के साथ दर्ज करता है।
  4. अंत में, एक इमेज जेनरेशन एजेंट एक स्वास्थ्यकर अगला भोजन सुझाता है, और एक इमेज के साथ विवरण और रेसिपी भी लौटाता है।

उपयोगकर्ताओं के लिए न्यूट्रिशनिस्ट के साथ इंटरैक्ट करने हेतु वेब इंटरफ़ेस देने के लिए हम Gradio का उपयोग करेंगे।

चरण 1: आवश्यकताएँ

शुरू करने से पहले, सुनिश्चित करें कि आपके पास निम्नलिखित इंस्टॉल हैं:

  • Python 3.8+
  • requirements.txt में सूचीबद्ध सभी आवश्यक पैकेज
python-dotenv==1.1.0
mistralai==0.0.7
typing-extensions==4.12.2
requests==2.31.0
gradio==4.34.0

साथ ही, एक .env फ़ाइल सेटअप करें जिसमें आपकी Mistral API कुंजी हो। यह तरीका API कुंजियों को सुरक्षित रखता है और टीम के अलग-अलग सदस्यों या डिप्लॉयमेंट वातावरणों को सोर्स कोड बदले बिना अलग क्रेडेंशियल्स उपयोग करने देता है।

MISTRAL_API_KEY=YOUR_API_KEY

नोट: अन्य Python प्रोजेक्ट्स के साथ वर्ज़न टकराव से बचने के लिए इन डिपेंडेंसीज़ को conda, venv या uv जैसे आइसोलेटेड वातावरण में इंस्टॉल करना अनुशंसित है।

विभिन्न वातावरण सेटअप करने के लिए ये कमांड्स हैं:

venv का उपयोग

python -m venv mistral_env
source mistral_env/bin/activate   # On Windows: mistral_env\Scripts\activate

Conda का उपयोग

conda create -n mistral_env python=3.10
conda activate mistral_env

uv का उपयोग

यदि आपके पास अभी uv नहीं है:

pip install uv

फिर:

uv venv mistral_env
source mistral_env/bin/activate

ऊपर उल्लिखित सभी डिपेंडेंसीज़ इंस्टॉल करने के लिए, अपने टर्मिनल में निम्न कोड चलाएँ:

pip install -r requirements.txt

नोट: यदि आप किसी एजेंट या कनेक्टर का उपयोग करते समय mistralai से संबंधित त्रुटियों का सामना करते हैं, तो निम्न कोड चलाएँ:

pip install –upgrade mistralai

यह mistralai लाइब्रेरी को उसके नवीनतम वर्ज़न में अपग्रेड कर देगा।

चरण 2: Mistral टूल्स सेटअप करना

इस खंड में, हम Mistral Agents API के साथ इंटरैक्शन के लिए अपने टूल्स और क्लाइंट सेटअप तैयार करेंगे। हम टूल स्कीमा परिभाषित करेंगे, क्लाइंट इनिशियलाइज़ करेंगे और ऑथेंटिकेशन सत्यापित करेंगे। बाद में, इन्हीं टूल्स को कैलोरी एस्टीमेटर्स या इमेज जेनरेटर्स जैसे विशिष्ट एजेंट्स सेटअप करते समय संदर्भित किया जाएगा।

चरण 2.1: टूल रजिस्ट्री और इनिशियलाइज़ेशन

पहले, हम अपने टूल स्कीमा, मॉडल चयन और क्लाइंट इंस्टैंशिएशन परिभाषित करते हैं। फिर, हम create_chat_completion() और check_client() जैसी हेल्पर मेथड्स बनाते हैं। निम्न कोड टूल्स फ़ोल्डर के अंदर configs.py फ़ाइल में जाता है:

#Configuration file
from mistralai import Mistral, UserMessage, SystemMessage
from dotenv import load_dotenv
import os
load_dotenv()
# Mistral model 
mistral_model = "mistral-large-latest"
client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))
# Agent IDs
web_search_id = "web_search_agent"
food_logger_id = "food_logger_agent"
user_assistant_id = "user_assistant_agent"
image_generator_id = "image_generator_agent"
# Tool definitions
tools = {
    "log_meal": {
        "name": "log_meal",
        "description": "Log a user's meal with calorie count",
        "input_schema": {
            "type": "object",
            "properties": {
                "username": {"type": "string"},
                "meal": {"type": "string"},
                "calories": {"type": "number"},
                "timestamp": {"type": "string", "format": "date-time"}
            },
            "required": ["username", "meal", "calories", "timestamp"]
        }
    },
    "web_search": {
        "name": "web_search",
        "description": "Search the web for information about a meal",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string"}
            },
            "required": ["query"]
        }
    }
}

हम dotenv इम्पोर्ट करके शुरू करते हैं ताकि Mistral API कुंजी जैसी संवेदनशील वैरिएबल्स को स्थानीय .env फ़ाइल से Python के वातावरण में लोड किया जा सके। यह क्रेडेंशियल्स को सुरक्षित और सोर्स कोड से बाहर रखता है। फिर, हम डिफ़ॉल्ट मॉडल mistral-large-latest चुनते हैं और API कुंजी का उपयोग करके एक Mistral क्लाइंट इंस्टैंशिएट करते हैं।

इसके बाद, हम JSON स्कीमा फ़ॉर्मेट का उपयोग करके आंतरिक टूल स्पेसिफ़िकेशंस (स्कीमा) परिभाषित करते हैं। वे इन कामों में मदद करते हैं:

  • MCP टूल व्यवहार का सिमुलेशन (भले ही वे McpTool लाइब्रेरी के माध्यम से रजिस्टर्ड न हों)
  • "username", "meal" और "calories" जैसे अपेक्षित इनपुट्स का वर्णन
  • मॉड्यूल्स में एकसमान इनपुट फ़ॉर्मैटिंग सुनिश्चित करना

अब, अपने हेल्पर मेथड्स जोड़ते हैं जो चैट कम्प्लीशन बनाते हैं, टूल्स, एजेंट्स रजिस्टर करते हैं, और क्लाइंट को इनिशियलाइज़ करते हैं।

def create_chat_completion(messages, model=mistral_model):  
    # Convert messages to new format
    formatted_messages = []
    for msg in messages:
        if msg["role"] == "system":
            formatted_messages.append(SystemMessage(content=msg["content"]))
        else:
            formatted_messages.append(UserMessage(content=msg["content"]))
    return client.chat.complete(
        model=model,
        messages=formatted_messages
    )
# Register tools
def register_tools():
    for tool_name, tool in tools.items():
        print(f"Registered tool: {tool_name}")
# Register agents
def register_agents():
    print("Registered User Assistant Agent")
    print("Registered Web Search Agent")
    print("Registered Food Logger Agent")
# Initialize everything
def initialize():
    register_tools()
    register_agents()
    check_client()
# Check if the client is initialized
def is_client_initialized():
    return client is not None and os.environ.get("MISTRAL_API_KEY") is not None
def check_client():
    if not is_client_initialized():
        print("Mistral client is not initialized. Please check your API key.")
        return False
    print("Mistral client is initialized.")
    return True
initialize()

फ़ंक्शन create_chat_completion() Mistral क्लाइंट SDK के हिस्से client.chat.complete() कॉल को रैप करता है, जो मॉडल को संदेश भेजता है।

  • यह कच्चे dict-शैली संदेशों को Mistral SDK द्वारा अपेक्षित UserMessage और SystemMessage ऑब्जेक्ट्स में रीफ़ॉर्मैट करता है।
  • यह ऐप में मानकीकृत कम्प्लीशंस के लिए भी उपयोगी है।

फ़ंक्शंस register_tools() और register_agents() लोकल डेवलपमेंट के दौरान यह लॉग करने में मदद करते हैं कि सिस्टम में कौन से टूल्स और एजेंट्स सक्रिय हैं। वहीं, check_client() और is_client_initialized() यह सुनिश्चित करते हैं कि Mistral क्लाइंट सही ढंग से इंस्टैंशिएट किया गया है और API कुंजी उपलब्ध है, जिससे एजेंट निष्पादन के दौरान रनटाइम त्रुटियों से बचाव होता है।

चरण 2.2: वेब सर्च एजेंट के साथ कैलोरी का अनुमान

अब जब हमने बेस टूल्स और क्लाइंट इनिशियलाइज़ कर लिया है, तो एक समर्पित न्यूट्रिशन वेब सर्च एजेंट बनाते हैं। यह एजेंट Mistral के web_search कनेक्टर का उपयोग करता है ताकि रियल-टाइम में भोजन के लिए कैलोरी अनुमान ढूँढा जा सके। यह कोड टूल्स फ़ोल्डर के अंदर web_search.py फ़ाइल में है।

# Web search tool
import re
from mistralai import Mistral, UserMessage, SystemMessage
from tools.configs import client
def search_calories(meal_desc):
    try:
        # Web search agent
        websearch_agent = client.beta.agents.create(
            model="mistral-medium-latest",
            description="Agent able to search for nutritional information and calorie content of meals",
            name="Nutrition Search Agent",
            instructions="You have the ability to perform web searches with web_search to find accurate calorie information. Return ONLY a single number representing total calories.",
            tools=[{"type": "web_search"}],
            completion_args={
                "temperature": 0.3,
                "top_p": 0.95,
            }
        )
        response = client.beta.conversations.start(
            agent_id=websearch_agent.id,
            inputs=f"What are the total calories in {meal_desc}?"
        )
        print("Raw response:", response)
        # Extract the number from the response
        if hasattr(response, 'outputs'):
            for output in response.outputs:
                if hasattr(output, 'content'):
                    if isinstance(output.content, str):
                        numbers = re.findall(r'\d+', output.content)
                        if numbers:
                            return int(numbers[0])
                    elif isinstance(output.content, list):
                        for chunk in output.content:
                            if hasattr(chunk, 'text'):
                                numbers = re.findall(r'\d+', chunk.text)
                                if numbers:
                                    return int(numbers[0])
        print("No calorie information found in web search response")
        return 0     
    except Exception as e:
        print(f"Error during web search: {str(e)}")
        return 0

उपर्युक्त कोड में, search_calories() फ़ंक्शन Mistral Agents API के बिल्ट-इन वेब सर्च कनेक्टर टूल का उपयोग करता है, जो एजेंट्स को कैलोरी अनुमान जैसी लाइव वेब क्वेरीज़ करने में सक्षम बनाता है, और स्थिर मॉडल प्रशिक्षण की सीमाओं को पार करता है। यह इस प्रकार काम करता है:

  1. एजेंट निर्माण: यह पहले mistral-medium-latest मॉडल का उपयोग करके “Nutrition Search Agent” बनाता है, जो web_search टूल से लैस है और केवल कैलोरी लौटाने का निर्देश दिया गया है।
  2. क्वेरी निष्पादन: इसके बाद एजेंट के साथ एक बातचीत शुरू की जाती है जिसमें दिए गए भोजन विवरण में कुल कैलोरी पूछी जाती है।
  3. रिस्पॉन्स पार्सिंग: एजेंट के रिस्पॉन्स से रेगुलर एक्सप्रेशन का उपयोग करके पहला संख्यात्मक मान निकाला जाता है (जो कैलोरी काउंट होना चाहिए)।
  4. फ़ॉलबैक्स: यदि कोई वैध संख्या नहीं मिलती या कोई त्रुटि होती है, तो फ़ंक्शन समस्या को लॉग करता है और फ़ॉलबैक के रूप में शून्य लौटाता है।

बिना web_search के, अधिकांश मॉडल हाल की घटनाओं या ऐसे डोमेन-विशेष भोजन के बारे में सवालों का जवाब नहीं दे सकते जो उनके प्रशिक्षण डेटा में नहीं देखे गए हों। इसके साथ, हम वास्तविक समय में पोषण संबंधी जानकारी, रेस्तरां मेनू या समाचार लेख क्वेरी कर सकते हैं।

वेब सर्च के दो वैरिएंट हैं:

  • web_search: एक हल्का, सामान्य-उद्देश्य सर्च इंजन कनेक्टर (हमारे प्रोजेक्ट में प्रयुक्त)।
  • web_search_premium: एक उन्नत संस्करण जिसमें समाचार प्रदाता सत्यापन और व्यापक संदर्भ संग्रह शामिल है।

अगला, हम केवल प्रॉम्प्ट-आधारित लॉजिक का उपयोग करके फ़ॉलबैक कैलोरी अनुमान का अन्वेषण करेंगे।

चरण 2.3: अनुमान, लॉगिंग और भोजन सुझाव

इस खंड में, हम तीन आवश्यक फ़ंक्शंस लागू करते हैं जो फ़ॉलबैक्स या एन्हांसमेंट्स के रूप में कार्य करते हैं। निम्न कोड टूल्स फ़ोल्डर में next.py फ़ाइल के अंदर है।

#Meal suggestions
from datetime import datetime
from tools.configs import client, create_chat_completion
from mistralai import SystemMessage, UserMessage
import re
def estimate_calories(meal_desc):   
    try:
        # Messages for calorie estimation
        messages = [
            SystemMessage(content="You are a nutrition expert. Estimate calories in meals. Return ONLY a single number representing total calories."),
            UserMessage(content=f"Estimate calories in: {meal_desc}")
        ]
        response = client.chat.complete(
            model="mistral-small-latest",  # Using smaller model to avoid rate limits
            messages=messages,
            temperature=0.1,
            max_tokens=50
        )
        content = response.choices[0].message.content
        numbers = re.findall(r'\d+', content)    
        if numbers:
            return int(numbers[0])
        return 0     
    except Exception as e:
        print(f"Error during calorie estimation: {str(e)}")
        return 0
def log_meal(username, meal, calories):  
    try:
        # Messages for meal logging
        messages = [
            SystemMessage(content="You are a meal logging assistant. Log the user's meal with calories."),
            UserMessage(content=f"Log this meal: {meal} with {calories} calories for user {username} at {datetime.utcnow().isoformat()}")
        ]
        response = client.chat.complete(
            model="mistral-small-latest",  # Using smaller model to avoid rate limits
            messages=messages,
            temperature=0.1,
            max_tokens=100
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"Error during meal logging: {str(e)}")
        return f"Logged {meal} ({calories} calories) for {username}"
def suggest_next_meal(calories, dietary_preference):   
    try:
        # Messages for meal suggestion
        messages = [
            SystemMessage(content="You are a nutrition expert. Suggest healthy meals based on calorie intake and dietary preferences."),
            UserMessage(content=f"Suggest a {dietary_preference} meal that would be a good next meal after consuming {calories} calories. Make it specific and appetizing.")
        ]
        response = client.chat.complete(
            model="mistral-small-latest",  
            messages=messages,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()        
    except Exception as e:
        print(f"Error during meal suggestion: {str(e)}")
        return "Unable to suggest next meal at this time."

यह स्क्रिप्ट हमारे न्यूट्रिशन वर्कफ़्लो (कैलोरी अनुमान से लेकर आगे के भोजन की योजना तक) को संचालित करने वाले मुख्य बैकएंड फ़ंक्शंस परिभाषित करती है। ये फ़ंक्शंस हल्के Mistral मॉडल्स और मानक चैट कम्प्लीशन का उपयोग करते हैं, ताकि जब वेब सर्च उपलब्ध न हो या रेट लिमिट त्रुटियों से बचना हो तो किसी एजेंट क्रिएशन या कनेक्टर्स की आवश्यकता न पड़े। प्रत्येक फ़ंक्शन यह करता है:

  1. estimate_calories(): यह फ़ंक्शन तब फ़ॉलबैक के रूप में उपयोग किया जाता है जब web_search कनेक्टर विफल हो या अनुपलब्ध हो।
    1. यह सिस्टम संदेश भेजता है जिसमें असिस्टेंट की भूमिका न्यूट्रिशन विशेषज्ञ के रूप में होती है, साथ ही उपयोगकर्ता प्रॉम्प्ट जिसमें उपयोगकर्ता द्वारा लॉग किया जाने वाला भोजन शामिल है।
    2. मॉडल को कम temperature=0.1 के साथ उपयोग किया जाता है ताकि आउटपुट निर्धारक रहे। इसका अर्थ है कि मॉडल एक ही इनपुट्स पर सुसंगत, दोहराने योग्य प्रतिक्रियाएँ देगा—जैसे कैलोरी अनुमान और लॉगिंग, जहाँ स्थिर और तथ्यात्मक आउटपुट रचनात्मक भिन्नता पर प्राथमिकता रखते हैं।
    3. यह मॉडल के उत्तर से (regex का उपयोग करके) पहली संख्या निकालता है।
  2. log_meal(): यह फ़ंक्शन उपयोगकर्ता के भोजन को टाइमस्टैम्प सहित लॉग करता है।
    1. यह निर्देशों के साथ एक चैट कम्प्लीशन का उपयोग करता है और असिस्टेंट का स्वरूपित पुष्टि संदेश लौटाता है।
    2. यह किसी समर्पित बैकएंड डेटाबेस की आवश्यकता के बिना हल्की-फुल्की आंतरिक लॉगिंग सक्षम करता है।
  3. suggest_next_meal(): यह फ़ंक्शन पिछले कैलोरी सेवन और उपयोगकर्ता की आहार वरीयता के आधार पर अगला भोजन सुझाता है।
    1. मॉडल को temperature=0.7 के साथ बुलाया जाता है ताकि अधिक रचनात्मक सुझाव प्रोत्साहित हों।
    2. इसके बाद रिस्पॉन्स को स्ट्रिप कर अगली भोजन की आइडिया के रूप में लौटाया जाता है।

साथ मिलकर, ये फ़ंक्शंस बिना किसी बाहरी API के कैलोरी अनुमान, लॉग पुष्टि और स्वास्थ्यकर सिफारिशें संभव बनाते हैं। अगले चरण में, हम Mistral के इमेज जेनरेशन कनेक्टर के साथ भोजन सुझावों को विज़ुअलाइज़ करेंगे।

चरण 2.4: इमेज जेनरेशन कनेक्टर के साथ विज़ुअल बनाना

अब अपने असिस्टेंट में एक विज़ुअल लेयर जोड़ते हैं। इस चरण में, हम Mistral के बिल्ट-इन image_generation कनेक्टर का उपयोग करके अगले सुझाए गए भोजन की एक लुभावनी इमेज बनाएँगे।

#Image generation tool
import os
import re
from mistralai import Mistral, UserMessage, SystemMessage
from mistralai.models import ToolFileChunk
from tools.configs import client
from datetime import datetime
def generate_food_image(meal_description):  
    try:
        print(f"Starting image generation for: {meal_description}")        
        # Image generation agent
        image_agent = client.beta.agents.create(
            model="mistral-medium-latest",
            name="Food Image Generation Agent",
            description="Agent used to generate food images.",
            instructions="Use the image generation tool to create appetizing food images. Generate realistic and appetizing images of meals.",
            tools=[{"type": "image_generation"}],
            completion_args={
                "temperature": 0.3,
                "top_p": 0.95,
            }
        )
        print("Created image generation agent")
        response = client.beta.conversations.start(
            agent_id=image_agent.id,
            inputs=f"Generate an appetizing image of: {meal_description}",
            stream=False  
        )
        print("Got response from image generation")
        os.makedirs("generated_images", exist_ok=True)
        # Process the response and save images
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        image_paths = []
        if hasattr(response, 'outputs'):
            print(f"Processing {len(response.outputs)} outputs")
            for output in response.outputs:
                if hasattr(output, 'content'):
                    print(f"Processing content of type: {type(output.content)}")
                    if isinstance(output.content, list):
                        for i, chunk in enumerate(output.content):
                            print(f"Processing chunk {i} of type: {type(chunk)}")
                            if isinstance(chunk, ToolFileChunk):
                                print(f"Found ToolFileChunk with file_id: {chunk.file_id}")
                                try:
                                    # Download the image
                                    file_bytes = client.files.download(file_id=chunk.file_id).read()       
                                    # Save the image
                                    image_path = f"generated_images/meal_{timestamp}_{i}.png"
                                    with open(image_path, "wb") as file:
                                        file.write(file_bytes)
                                    image_paths.append(image_path)
                                    print(f"Successfully saved image to: {image_path}")
                                except Exception as e:
                                    print(f"Error processing image chunk: {str(e)}")
                    else:
                        print(f"Content is not a list: {output.content}")
        if image_paths:
            print(f"Successfully generated {len(image_paths)} images")
            return image_paths[0]  # Return the first image path
        else:
            print("No images were generated")
            return "No image was generated”"
    except Exception as e:
        print(f"Error during image generation: {str(e)}")
        if hasattr(e, '__dict__'):
            print(f"Error details: {e.__dict__}")
        return f"Error generating image: {str(e)}" 

फ़ंक्शन generate_food_image() Mistral के बिल्ट-इन image_generation टूल का उपयोग करके भोजन का एक विज़ुअल प्रतिनिधित्व बनाता है। इसका हर भाग यह करता है:

  • एजेंट निर्माण: एक नया एजेंट यथार्थपरक और लुभावनी फूड विज़ुअल्स बनाने के लिए निर्देशित किया जाता है।
  • कन्वर्सेशन शुरू: एक प्रॉम्प्ट भेजा जाता है जिसमें एजेंट से दिए गए meal_description (जो अगले भोजन एजेंट द्वारा जनरेट किया गया है) की इमेज बनाने को कहा जाता है।
  • रिस्पॉन्स हैंडलिंग: फ़ंक्शन जाँचता है कि रिस्पॉन्स में इमेज चंक्स हैं या नहीं। यदि हाँ, तो यह Mistral क्लाइंट की files.download() मेथड के ज़रिए हर इमेज डाउनलोड करता है। इमेजेस को स्थानीय रूप से generated_images/ फ़ोल्डर में टाइमस्टैम्प वाले फ़ाइलनामों के साथ सेव किया जाता है।
  • आउटपुट: यह पहली सफलतापूर्वक सेव की गई इमेज का पथ लौटाता है, या विफलता पर एक फ़ॉलबैक त्रुटि संदेश देता है।

यह टूल हमारे न्यूट्रिशन कोच में विज़ुअल लेयर जोड़ता है, जिससे भोजन सुझाव अधिक आकर्षक और वास्तविक लगते हैं।

चरण 3: पूर्ण न्यूट्रिशनिस्ट पाइपलाइन

अब जब हमने व्यक्तिगत टूल्स और एजेंट क्षमताएँ बना ली हैं, तो उन्हें एक ही पाइपलाइन में जोड़ने का समय है। यह चरण सब कुछ एक साथ जोड़ देता है ताकि एक काम करने वाला असिस्टेंट बने जो यह संभाले:

  • कैलोरी लुकअप (वेब या अनुमान के माध्यम से)
  • लॉगिंग (उपयोगकर्ता, भोजन, कैलोरी, टाइमस्टैम्प)
  • अगला भोजन सुझाना
  • इमेज के साथ भोजन का विज़ुअलाइज़ेशन

इन सभी चरणों को हमारे पिछले फ़ाइलों के प्रत्येक फ़ंक्शन को सही क्रम में कॉल करके हैंडल किया जाता है। इस पाइपलाइन का कोड टूल्स फ़ोल्डर के बाहर agent.py फ़ाइल में होता है।

# Pipeline logic file
from tools import estimate_calories, log_meal, suggest_next_meal, search_calories
from tools.image_gen import generate_food_image
from datetime import datetime
import time
def run_nutritionist_pipeline(username, meal_desc, dietary_preference):
    tools_used = set()    
    print(f"Searching for calories for: {meal_desc}")
    calories_text = search_calories(meal_desc)
    tools_used.add("Web Search")    
    # If web search fails, fall back to estimation
    if calories_text == 0:
        print("Web search failed, falling back to estimation...")
        time.sleep(1)  # Add delay to avoid rate limits
        calories_text = estimate_calories(meal_desc)
        tools_used.add("Calorie Estimation")   
    estimated_calories = calories_text
    print(f"Estimated calories: {estimated_calories}")   
    print(f"Logging meal for {username}...")
    time.sleep(1)  # Add delay to avoid rate limits
    log_response = log_meal(username, meal_desc, estimated_calories)
    tools_used.add("Meal Logging")    
    print("Generating next meal suggestion...")
    time.sleep(1)  
    suggestion = suggest_next_meal(estimated_calories, dietary_preference)
    tools_used.add("Next Meal Suggestion")    
    print("Generating image description for suggested meal...")
    time.sleep(1)  
    meal_image = generate_food_image(suggestion)
    tools_used.add("Image Description Generation")
    return {
        "logged": log_response,
        "next_meal_suggestion": suggestion,
        "meal_image": meal_image,
        "tools_used": sorted(list(tools_used))
    }

उपर्युक्त कोड कई एजेंट टूल्स को एक एकल पाइपलाइन में चेन करके पूरे न्यूट्रिशन असिस्टेंट वर्कफ़्लो का समन्वय करता है। आइए इसे थोड़े और विस्तार से समझें:

  • फ़ंक्शन run_nutritionist_pipeline() इनपुट के रूप में username, meal_desc और dietary_preference लेता है ताकि सिफारिश प्रक्रिया संचालित हो सके।
  • पहले, यह Mistral के वेब सर्च कनेक्टर द्वारा संचालित search_calories() का उपयोग करके भोजन की कैलोरी निर्धारित करने का प्रयास करता है। यदि यह विफल होता है, तो यह estimate_calories() के माध्यम से एक हल्के मॉडल का उपयोग करके अनुमान पर लौट आता है।
  • प्राप्त कैलोरी मान को फिर log_meal() फ़ंक्शन का उपयोग करके लॉग किया जाता है, जो एंट्री को टाइमस्टैम्प के साथ टैग करता है और इसे उपयोगकर्ता से जोड़ता है।
  • खपत की गई कैलोरी और आहार वरीयता के आधार पर, suggest_next_meal() फ़ंक्शन प्रॉम्प्ट-आधारित तर्क का उपयोग करके अगला भोजन सुझाता है।
  • अंततः, generate_food_image() फ़ंक्शन Mistral के इमेज जेनरेशन कनेक्टर का उपयोग करके अनुशंसित डिश का विज़ुअल बनाता है।
  • पूरे प्रोसेस के दौरान, API कॉल्स के समय रेट लिमिट से बचने के लिए time.sleep(1) द्वारा छोटे विराम जोड़े जाते हैं।
  • फ़ंक्शन एक डिक्शनरी लौटाता है जिसमें भोजन लॉगिंग की पुष्टि, अगला भोजन सुझाव, जनरेट की गई इमेज का पथ, और इस इंटरैक्शन में उपयोग किए गए टूल्स की सूची होती है।

यह पाइपलाइन सर्च, अनुमान, लॉगिंग, सुझाव और विज़ुअलाइज़ेशन जैसी अनेक क्षमताओं को एक AI-संचालित न्यूट्रिशन अनुभव में समाहित करती है।

चरण 4: Gradio के साथ यूज़र-फ्रेंडली इंटरफ़ेस बनाना

अब जब बैकएंड लॉजिक पूरा हो चुका है, तो इसे Gradio का उपयोग करके साफ़-सुथरे, उपयोगकर्ता-अनुकूल फ़्रंटएंड में रैप करते हैं।

# Main files
import gradio as gr
from agent import run_nutritionist_pipeline
import os
import re
def process_meal(username, meal_desc, dietary_preference):
    # Run the pipeline
    result = run_nutritionist_pipeline(username, meal_desc, dietary_preference)    
    # Extract calories from the logged meal response
    calories = "Not available"
    if result['logged']:
        calorie_match = re.search(r'(\d+)\s*calories', result['logged'], re.IGNORECASE)
        if calorie_match:
            calories = calorie_match.group(1)
        else:
            paren_match = re.search(r'\((\d+)\)', result['logged'])
            if paren_match:
                calories = paren_match.group(1)
            else:
                number_match = re.search(r'\b(\d+)\b', result['logged'])
                if number_match:
                    calories = number_match.group(1)    
    # Map tool names to Mistral connectors
    connector_map = {
        "Web Search": "Web Search",
        "Image Description Generation": "Image Generation",
        "Meal Logging": "Chat Completion",
        "Next Meal Suggestion": "Chat Completion"
    }   
    connectors_used = set()
    for tool in result['tools_used']:
        if tool in connector_map:
            connectors_used.add(connector_map[tool])    
    output = f"""
# Meal Analysis Results
## Meal Details
- **Meal Description:** {meal_desc}
- **Estimated Calories:** {calories}
## Next Meal Suggestion
{result['next_meal_suggestion']}

## Tools Used
{', '.join(result['tools_used'])}
## Mistral Connectors Used
{', '.join(sorted(connectors_used))}
""
    # Get the image path and check if it is valid
    image_path = result['meal_image']    
    if os.path.exists(image_path) and image_path.endswith('.png'):
        return output, image_path
    else:
        return output, None
# Create the Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🍽️ Nutritionist Assistant")    
    with gr.Row():
        with gr.Column():
            username = gr.Textbox(label="Username", placeholder="Enter your name")
            meal_desc = gr.Textbox(label="Meal Description", placeholder="Describe your meal (e.g., 'Chicken salad with olive oil dressing')")
            dietary_preference = gr.Dropdown(
                choices=["vegetarian", "vegan", "Non-vegetarian", "gluten-free"],
                label="Dietary Preference",
                value="omnivore"
            )
            submit_btn = gr.Button("Process Meal", variant="primary")        
        with gr.Column():
            output = gr.Markdown(label="Results")
            image_output = gr.Image(label="Generated Meal Image", type="filepath")    
    submit_btn.click(
        fn=process_meal,
        inputs=[username, meal_desc, dietary_preference],
        outputs=[output, image_output]
    )
# Launch the app
if __name__ == "__main__":
    demo.launch() 

उपर्युक्त कोड स्निपेट में, हम न्यूट्रिशनिस्ट एजेंट पाइपलाइन के साथ इंटरैक्ट करने के लिए एक संपूर्ण Gradio UI सेटअप करते हैं। यह इस प्रकार काम करता है:

  • हम agent.py से run_nutritionist_pipeline() फ़ंक्शन इम्पोर्ट करके शुरू करते हैं, जो कोर एजेंट लॉजिक को चलाता है।
  • इसके बाद, process_meal() फ़ंक्शन एजेंट पाइपलाइन के चारों ओर एक रैपर की तरह कार्य करता है, जो username, meal_desc और dietary_preference को यूज़र इनपुट के रूप में स्वीकार करता है और पहले परिभाषित मल्टी-एजेंट लॉजिक को ट्रिगर करता है।
  • process_meal() फ़ंक्शन के अंदर, परिणाम डिक्शनरी को भोजन सार, कैलोरी, सुझाया गया अगला भोजन, और प्रयुक्त कनेक्टर्स निकालने के लिए पार्स किया जाता है।
  • फ़ंक्शन जनरेट की गई इमेज पथ को डिस्प्ले से पहले वैध भी जांचता है। यदि इमेज नहीं मिलती, तो केवल टेक्स्टुअल परिणाम लौटाया जाता है।
  • Gradio ऐप gr.Blocks() का उपयोग करके निर्मित है और लेआउट में दो हिस्से हैं—एक में इनपुट फ़ील्ड्स और Process Meal बटन, और दूसरे में भोजन विश्लेषण परिणामों के लिए आउटपुट क्षेत्र और अगले भोजन की इमेज प्रीव्यू।
  • submit_btn.click() कॉलबैक फ़्रंटएंड बटन को process_meal() फ़ंक्शन से जोड़ता है, इनपुट्स पास करता है और फ़ॉर्मेटेड मार्कडाउन और इमेज को आउटपुट के रूप में प्राप्त करता है।
  • अंत में, यदि स्क्रिप्ट मुख्य मॉड्यूल के रूप में चलती है, तो ऐप demo.launch() के माध्यम से लॉन्च होता है। आप ऐप के डिबगिंग मोड को सक्षम करने के लिए debug = True सेट कर सकते हैं।

यह डेमो चलाने के लिए, अपनी रूट डायरेक्टरी में एक टर्मिनल खोलें और यह कमांड टाइप करें:

python app.py

इस प्रोजेक्ट की समग्र संरचना कुछ इस प्रकार होगी:

Mistral_Agent_API/
├── generated_images/ # Stores generated meal images
├── tools/
│   ├── configs.py              # API setup, tool schema, environment config
│   ├── image_gen.py            # Generates meal image  
│   ├── next.py                 # Calorie estimator, logger, and next meal 
│   └── web_search.py           # Mistral web_search connector to find calorie 
├── agent.py                    # Main pipeline connecting all tools
├── app.py                      # Gradio UI 
├── requirements.txt            # Project dependencies
├── .env                        # Environment variables 

आप इस प्रोजेक्ट का पूरा कोड इस GitHub रिपो पर पा सकते हैं।

Nutritionist Assistant with mistral agents api

Nutritionist Assistant with mistral agents api

Nutritionist Assistant with mistral agents api

निष्कर्ष

इस ट्यूटोरियल में, हमने Mistral Agents API का उपयोग करके एक पूर्ण रूप से कार्यात्मक AI न्यूट्रिशन कोच बनाया। इस दौरान, हमने ये खोजा:

  • Mistral एजेंट्स कच्चे LLM मॉडलों से कैसे अलग हैं
  • web_search और image_generation जैसे कनेक्टर्स की भूमिका
  • एक ही पाइपलाइन में कई एजेंट्स के बीच ऑर्केस्ट्रेशन
  • Gradio के साथ उपयोगकर्ता-अनुकूल फ़्रंटएंड बनाना

यह प्रोजेक्ट एजेंटिक वर्कफ़्लोज़ की ताकत दिखाता है जहाँ LLMs सिर्फ़ निष्क्रिय उत्तरदाता नहीं, बल्कि ऐसे इंटरैक्टिव एंटिटीज़ हैं जो तर्क करते हैं, कार्रवाई करते हैं और कार्यों का समन्वय करते हैं। भोजन लॉग करने से लेकर स्वस्थ विकल्प सुझाने और इमेजेस जनरेट करने तक, हमने दिखाया कि कैसे सरल टूल्स को मिलाकर शक्तिशाली AI अनुभव बनाए जा सकते हैं।

AI एजेंट्स का उपयोग करने के बारे में और जानने के लिए, मैं ये हैंड्स-ऑन ट्यूटोरियल्स सुझाता हूँ:

Aashi Dutt

लेखक

Aashi Dutt

मैं एमएल (Gen AI) में Google Developers Expert, Kaggle 3x Expert, और Women Techmakers एंबेसडर हूँ, तथा तकनीक क्षेत्र में 3+ वर्षों का अनुभव रखती हूँ। मैंने 2020 में एक हेल्थ-टेक स्टार्टअप की सह-स्थापना की और वर्तमान में Georgia Tech से कंप्यूटर विज्ञान में मास्टर कर रही हूँ, जिसमें मेरा विशेषज्ञता क्षेत्र मशीन लर्निंग है।

विषय