🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
docs: Add Mistral OCR Usecase with UI (#2528)
Sarthak Bhardwaj9ec57dcd9a52
diff --git a/docs/cookbooks/data_processing/index.rst b/docs/cookbooks/data_processing/index.rstindex 3d188fe85..01ec43017 100644--- a/docs/cookbooks/data_processing/index.rst+++ b/docs/cookbooks/data_processing/index.rst@@ -13,4 +13,5 @@ Data Processing and Analysisvideo_analysisagent_with_chunkr_for_pdf_parsing+ summarisation_agent_with_mistral_ocringest_data_from_websites_with_Firecrawldiff --git a/docs/cookbooks/data_processing/summarisation_agent_with_mistral_ocr.ipynb b/docs/cookbooks/data_processing/summarisation_agent_with_mistral_ocr.ipynbnew file mode 100644index 000000000..c4ff0f4b3--- /dev/null+++ b/docs/cookbooks/data_processing/summarisation_agent_with_mistral_ocr.ipynb@@ -0,0 +1,364 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "source": [+ "# Create Document Summarization Agents with Mistral OCR & CAMEL-AI 🐫\n",+ "\n",+ "You can also check this cookbook in Colab [here](https://colab.research.google.com/drive/1ZwVmqa5vjpZ0C3H7k1XIseFfbCR4mq17?usp=sharing)\n",+ "\n",+ "In this cookbook, we’ll explore [**Mistral OCR**](https://mistral.ai/news/mistral-ocr)—a state-of-the-art Optical Character Recognition API that understands complex document layouts and extracts text, tables, images, and equations with unprecedented accuracy. We’ll show you how to:\n",+ "\n",+ "- Use the Mistral OCR API to convert scanned or image-based PDFs into structured Markdown\n",+ "- Leverage a Mistral LLM agent within CAMEL to summarize and analyze the extracted content\n",+ "- Build a seamless, end-to-end pipeline for retrieval-augmented generation (RAG), research, or business automation\n",+ "\n",+ "## Table of Contents\n",+ "\n",+ "1. 🧑🏻💻 Introduction\n",+ "2. ⚡️ Step-by-step Guide: Mistral OCR Extraction\n",+ "3. 💫 Quick Demo with Mistral Agent\n",+ "4. 🧑🏻💻 Conclusion\n",+ "\n",+ "<div class=\"align-center\">\n",+ " <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\" width=\"150\"></a>\n",+ " <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\" width=\"150\"></a>\n",+ " \n",+ "⭐ <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)</i>\n",+ "</div>\n",+ "\n"+ ],+ "metadata": {+ "id": "zbmL45h7fWRT"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ ""+ ],+ "metadata": {+ "id": "wbUMBBIB3LM3"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## **Introduction to Mistral OCR**\n",+ "\n",+ "Throughout history, advancements in information abstraction and retrieval have driven human progress—from hieroglyphs to digitization. Today, over 90% of organizational data lives in documents, often locked in complex layouts and multiple languages. **Mistral OCR** ushers in the next leap in document understanding: a multimodal API that comprehends every element—text, images, tables, equations—and outputs ordered, structured Markdown with embedded media references.\n",+ "\n",+ "#### **Key Features of Mistral OCR:**\n",+ "\n",+ "1. **State-of-the-art complex document understanding** \n",+ " - Extracts interleaved text, figures, tables, and mathematical expressions with high fidelity.\n",+ "\n",+ "2. **Natively multilingual & multimodal** \n",+ " - Parses scripts and fonts from across the globe, handling right-to-left layouts and non-Latin characters seamlessly.\n",+ "\n",+ "3. **Doc-as-prompt, structured output** \n",+ " - Returns ordered Markdown, embedding images and bounding-box metadata ready for RAG and downstream AI workflows.\n",+ "\n",+ "4. **Top-tier benchmarks & speed** \n",+ " - Outperforms leading OCR systems in accuracy—especially in math, tables, and multilingual tests—while delivering fast batch inference (∼2000 pages/min).\n",+ "\n",+ "5. **Scalable & flexible deployment** \n",+ " - Available via `mistral-ocr-latest` on Mistral’s developer suite, cloud partners, and on-premises self-hosting for sensitive data.\n",+ "\n",+ "Ready to unlock your documents? Let’s dive into the extraction guide.\n"+ ],+ "metadata": {+ "id": "Bl90urdzuQLu"+ }+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "7p-JjpyNVcCT"+ },+ "source": [+ "First, install the CAMEL package with all its dependencies."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "I2X5A0LBc92C",+ "collapsed": true+ },+ "outputs": [],+ "source": [+ "!pip install \"camel-ai[all]==0.2.61\""+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## ⚡️ Step-by-step Guide: Mistral OCR Loader"+ ],+ "metadata": {+ "id": "WCfZ6vA0iFQv"+ }+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "FmuVvhpDyCT8"+ },+ "source": [+ "**Step 1: Set up your Mistral API key**\n",+ "\n",+ "If you don’t have a Mistral API key, you can obtain one by following these steps:\n",+ "\n",+ "1. **Create an account:** \n",+ " Go to [Mistral Console](https://console.mistral.ai/home) and sign up for an organization account.\n",+ "\n",+ "2. **Get your API key:** \n",+ " Once logged in, navigate to **Organization** → **API Keys**, generate a new key, copy it, and store it securely.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "cuZwSWBYyCT8"+ },+ "outputs": [],+ "source": [+ "import os\n",+ "from getpass import getpass\n",+ "\n",+ "mistral_api_key = getpass('Enter your Mistral API key: ')\n",+ "os.environ['MISTRAL_API_KEY'] = mistral_api_key\n"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "**Step 2: Upload your PDF or image file for OCR**\n",+ "\n",+ "In a Colab or Jupyter environment, you can upload any PDF file directly:\n"+ ],+ "metadata": {+ "id": "LUpFBEB9vrIz"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Colab file upload\n",+ "from google.colab import files\n",+ "\n",+ "uploaded = files.upload()\n",+ "# Grab the first uploaded filename\n",+ "file_path = next(iter(uploaded))"+ ],+ "metadata": {+ "id": "dUVE7z9hwEV7"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "**Step 3: Import and initialize the Mistral OCR loader**"+ ],+ "metadata": {+ "id": "fwlB09epyeWK"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Importing the MistralReader class from the camel.loaders module\n",+ "# This class handles document processing using Mistral OCR capabilities\n",+ "from camel.loaders import MistralReader\n",+ "\n",+ "# Initializing an instance of MistralReader\n",+ "# This object will be used to submit tasks and manage OCR processing\n",+ "mistral_reader = MistralReader()"+ ],+ "metadata": {+ "id": "SgIsQpOX82Bo"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Step 4: Obtain OCR output from Mistral\n",+ "\n",+ "Once the task completes, retrieve its output using the returned `task.id`.\n",+ "\n",+ "The output of **Mistral OCR** is a structured object:\n"+ ],+ "metadata": {+ "id": "ecWmxX4ZyoS8"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "# Retrieve the OCR output\n",+ "# CORRECT: Just use extract_text for local files or URLs\n",+ "ocr_response = mistral_reader.extract_text(file_path)\n",+ "print(ocr_response)"+ ],+ "metadata": {+ "id": "rTKuFUXuyoS8"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "65Z2nDTfUM0P"+ },+ "source": [+ "## 💫 Quick Demo with CAMEL Agent\n",+ "\n",+ "Here we choose Mistral model for our demo. If you'd like to explore different models or tools to suit your needs, feel free to visit the [CAMEL documentation page](https://docs.camel-ai.org/), where you'll find guides and tutorials.\n"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "If you don't have a Mistral API key, you can obtain one by following these steps:\n",+ "\n",+ "1. Visit the Mistral Console (https://console.mistral.ai/)\n",+ "\n",+ "2. In the left panel, click on API keys under API section\n",+ "\n",+ "3. Choose your plan\n",+ "\n",+ "For more details, you can also check the Mistral documentation: https://docs.mistral.ai/getting-started/quickstart/"+ ],+ "metadata": {+ "id": "AtaiHz437A2_"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from camel.configs import MistralConfig\n",+ "from camel.models import ModelFactory\n",+ "from camel.types import ModelPlatformType, ModelType\n",+ "\n",+ "mistral_model = ModelFactory.create(\n",+ " model_platform=ModelPlatformType.MISTRAL,\n",+ " model_type=ModelType.MISTRAL_LARGE,\n",+ " model_config_dict=MistralConfig(temperature=0.0).as_dict(),\n",+ ")\n",+ "\n",+ "# Use Mistral model\n",+ "model = mistral_model"+ ],+ "metadata": {+ "id": "1mKu0Dgj5TV9"+ },+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "cPOelPF2UM0P"+ },+ "outputs": [],+ "source": [+ "from camel.agents import ChatAgent\n",+ "\n",+ "# Initialize a ChatAgent\n",+ "agent = ChatAgent(\n",+ " system_message=\"You are a helpful document assistant.\", # Define the agent's role\n",+ " model=mistral_model\n",+ ")\n",+ "\n",+ "# Use the ChatAgent to generate insights based on the OCR output\n",+ "response = agent.step(\n",+ " f\"Based on the following OCR-extracted content, give me a concise conclusion of the document:\\n{ocr_response}\"\n",+ ")\n",+ "print(response.msgs[0].content)"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "**For advanced usage of RAG capabilities with large files, please refer to our [RAG cookbook](https://docs.camel-ai.org/cookbooks/advanced_features/agents_with_rag#rag-cookbook).**"+ ],+ "metadata": {+ "id": "p3VfU-hdX4Ti"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "## 🧑🏻💻 Conclusion\n",+ "\n",+ "In conclusion, integrating **Mistral OCR** within CAMEL-AI revolutionizes the process of document data extraction and preparation, enhancing your capabilities for AI-driven applications. With Mistral OCR’s robust features—state-of-the-art complex document understanding, natively multilingual & multimodal parsing, and doc-as-prompt structured Markdown output—you can seamlessly process complex PDFs and images into machine-readable formats optimized for LLMs, directly feeding into CAMEL-AI’s multi-agent workflows. This integration not only simplifies data preparation but also empowers intelligent and accurate analytics at scale. With these tools at your disposal, you’re equipped to transform raw document data into actionable insights, unlocking new possibilities in automation and AI-powered decision-making.\n"+ ],+ "metadata": {+ "id": "sR4BU5Z_oanP"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "That's everything: Got questions about 🐫 CAMEL-AI? Join us on [Discord](https://discord.camel-ai.org)! Whether you want to share feedback, explore the latest in multi-agent systems, get support, or connect with others on exciting projects, we’d love to have you in the community! 🤝\n",+ "\n",+ "Check out some of our other work:\n",+ "\n",+ "1. 🐫 Creating Your First CAMEL Agent [free Colab](https://colab.research.google.com/drive/1cmWPxXEsyMbmjPhD2bWfHuhd_Uz6FaJQ?usp=sharing)\n",+ "\n",+ "2. Graph RAG Cookbook [free Colab](https://colab.research.google.com/drive/1uZKQSuu0qW6ukkuSv9TukLB9bVaS1H0U?usp=sharing)\n",+ "\n",+ "3. 🧑⚖️ Create A Hackathon Judge Committee with Workforce [free Colab](https://colab.research.google.com/drive/18ajYUMfwDx3WyrjHow3EvUMpKQDcrLtr?usp=sharing)\n",+ "\n",+ "4. 🔥 3 ways to ingest data from websites with Firecrawl & CAMEL [free Colab](https://colab.research.google.com/drive/1lOmM3VmgR1hLwDKdeLGFve_75RFW0R9I?usp=sharing)\n",+ "\n",+ "5. 🦥 Agentic SFT Data Generation with CAMEL and Mistral Models, Fine-Tuned with Unsloth [free Colab](https://colab.research.google.com/drive/1lYgArBw7ARVPSpdwgKLYnp_NEXiNDOd-?usp=sharingg)\n",+ "\n",+ "Thanks from everyone at 🐫 CAMEL-AI\n",+ "\n",+ "\n",+ "<div class=\"align-center\">\n",+ " <a href=\"https://www.camel-ai.org/\"><img src=\"https://i.postimg.cc/KzQ5rfBC/button.png\"width=\"150\"></a>\n",+ " <a href=\"https://discord.camel-ai.org\"><img src=\"https://i.postimg.cc/L4wPdG9N/join-2.png\" width=\"150\"></a></a>\n",+ " \n",+ "⭐ <i>Star us on <a href=\"https://github.com/camel-ai/camel\">Github</a> </i>, join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg) ⭐\n",+ "</div>\n"+ ],+ "metadata": {+ "id": "oA81T8-ToaWz"+ }+ },+ {+ "cell_type": "code",+ "source": [],+ "metadata": {+ "id": "k5hq3Y4Z6UBC"+ },+ "execution_count": null,+ "outputs": []+ }+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0+}\ No newline at end of filediff --git a/examples/usecases/mistral_OCR/README.md b/examples/usecases/mistral_OCR/README.mdnew file mode 100644index 000000000..d8a899790--- /dev/null+++ b/examples/usecases/mistral_OCR/README.md@@ -0,0 +1,88 @@+# CAMEL-AI OCR Demo (w/ Mistral)++A simple Streamlit app to extract and summarize text from PDFs and images using the [Mistral OCR](https://mistral.ai/research/mistral-ocr/) API, fully powered by the [CAMEL-AI](https://github.com/camel-ai/camel) framework.++---++## 🚀 Features++- Drag & drop PDF or image upload (up to 200MB)+- Live preview (PDF or image) in the sidebar+- One-click OCR extraction via Mistral OCR+- Nicely formatted OCR result in markdown+- Optional LLM-powered summary using CAMEL-AI’s agents+- Easy Mistral API key input (sidebar)+- Modern Streamlit UI, ready to customize++---++## 🛠️ Requirements++- Python **3.10** or **3.12** (recommended)+- [CAMEL-AI](https://github.com/camel-ai/camel) (`camel-ai==0.2.61`, installed via `requirements.txt`)+- [mistralai](https://pypi.org/project/mistralai/) (for API calls)+- [Streamlit](https://streamlit.io/)+- [Pillow](https://pypi.org/project/Pillow/) (image preview)++Install all dependencies in a **clean virtualenv**.++---++### 📦 Quick Install++```bash+# 1. (Recommended) Create and activate virtualenv+python3.12 -m venv .venv+source .venv/bin/activate++# 2. Clone this demo repo or copy app.py and requirements.txt+# (Assume you’re in the right directory)++# 3. Install dependencies+pip install --upgrade pip+pip install -r requirements.txt+```++---++### 📝 Usage++1. **Get your [Mistral API Key](https://console.mistral.ai/home)**+2. **Run the Streamlit app:**+ ```bash+ streamlit run app.py+ ```+3. **Open the app in your browser at** [http://localhost:8501](http://localhost:8501)+4. **Paste your API key** in the sidebar, upload a PDF/image, and extract text!++---++### 📁 File Structure++```+app.py # Main Streamlit app+README.md # This file+requirements.txt # Python dependencies+```++---++## 🔧 Troubleshooting++- **MistralReader import error?**+ Make sure you have `camel-ai==0.2.61` installed (see `requirements.txt`).+- **No module named mistralai?**+ Install with `pip install mistralai`.+- **Python version errors?**+ Use Python 3.10 or 3.12 only.++---++## requirements.txt++```+streamlit+pillow+mistralai+camel-ai==0.2.61+```diff --git a/examples/usecases/mistral_OCR/app.py b/examples/usecases/mistral_OCR/app.pynew file mode 100644index 000000000..91d19cf79--- /dev/null+++ b/examples/usecases/mistral_OCR/app.py@@ -0,0 +1,141 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import os+import streamlit as st+from PIL import Image+import tempfile+import base64++from camel.loaders import MistralReader+from camel.configs import MistralConfig+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType+from camel.agents import ChatAgent++# --- Page config ---+st.set_page_config(+ page_title="Create Document Summarization Agents with Mistral OCR & CAMEL-AI 🐫",+ page_icon="📄",+ layout="wide",+ initial_sidebar_state="expanded"+)++# --- Sidebar: API Key & Upload & Preview ---+st.sidebar.header("⚙️ Configuration")+api_key = st.sidebar.text_input(+ "Mistral API Key", type="password", help="Get it from https://console.mistral.ai/home"+)+if api_key:+ os.environ["MISTRAL_API_KEY"] = api_key++st.sidebar.markdown("---")+st.sidebar.header("📤 Upload Document")+uploaded = st.sidebar.file_uploader(+ "Choose a PDF or Image…", type=["pdf", "png", "jpg", "jpeg"]+)++# Display PDF or Image preview in sidebar+file_path = None+if uploaded:+ ext = uploaded.name.split('.')[-1].lower()+ if ext in ["png", "jpg", "jpeg"]:+ image = Image.open(uploaded)+ st.sidebar.image(image, caption="Uploaded Image Preview", use_container_width=True)+ tmp_pdf = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)+ image.convert("RGB").save(tmp_pdf.name)+ file_path = tmp_pdf.name+ else:+ tmp_pdf = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)+ with open(tmp_pdf.name, "wb") as f:+ f.write(uploaded.getbuffer())+ file_path = tmp_pdf.name+ with open(file_path, "rb") as f:+ b64 = base64.b64encode(f.read()).decode('utf-8')+ pdf_html = (+ f'<iframe src="data:application/pdf;base64,{b64}" '+ 'width="100%" height="300px" type="application/pdf"></iframe>'+ )+ st.sidebar.markdown("### PDF Preview")+ st.sidebar.markdown(pdf_html, unsafe_allow_html=True)++ if st.sidebar.button("Clear Result"):+ st.session_state.pop("ocr_result", None)+ st.session_state.pop("file_path", None)+ st.experimental_rerun()++ if st.sidebar.button("Extract Text 🔍"):+ with st.spinner("Running OCR…"):+ try:+ loader = MistralReader()+ ocr_response = loader.extract_text(file_path)+ st.session_state['ocr_result'] = ocr_response+ st.session_state['file_path'] = file_path+ except Exception as e:+ st.error(f"❌ OCR failed: {e}")++# --- Main UI ---+st.title("Create Document Summarization Agents with Mistral OCR & CAMEL-AI 🐫")+st.markdown("Upload a PDF or image via the sidebar, preview it there, and extract text, then summarize it with a CAMEL agent.")++# --- Show OCR Results ---+st.markdown("---")+if 'ocr_result' in st.session_state:+ resp = st.session_state['ocr_result']+ st.subheader("🔎 OCR Result")+ try:+ for page in resp.pages:+ if page.markdown:+ st.markdown(page.markdown)+ if page.images:+ st.markdown("**Extracted Images:**")+ for img_obj in page.images:+ img_path = img_obj.id+ if os.path.exists(img_path):+ st.image(img_path)+ except Exception:+ st.json(resp)++ st.write("**Model:**", resp.model)+ usage = getattr(resp, 'usage_info', None)+ if usage:+ st.write(f"**Pages Processed:** {usage.pages_processed}")+ st.write(f"**Document Size (bytes):** {usage.doc_size_bytes}")++# --- Optional: Quick Summary ---+st.markdown("---")+if 'ocr_result' in st.session_state:+ st.subheader("🤖 Quick Summary")+ mistral_model = ModelFactory.create(+ model_platform=ModelPlatformType.MISTRAL,+ model_type=ModelType.MISTRAL_LARGE,+ model_config_dict=MistralConfig(temperature=0.0).as_dict(),+ )+ agent = ChatAgent(+ system_message="You are a helpful document assistant.",+ message_window_size=10,+ model=mistral_model,+ )+ if st.button("Summarize Document"):+ with st.spinner("Generating summary…"):+ text = []+ for page in resp.pages:+ text.append(page.markdown or '')+ prompt_text = "\n---\n".join(text)[:4000]+ summary = agent.step(f"Summarize this document concisely:\n\n{prompt_text}")+ st.markdown(summary.msgs[0].content)++# --- Footer ---+st.markdown("---")+st.markdown("Made with ❤️ using CAMEL-AI & Mistral OCR 🐫")diff --git a/examples/usecases/mistral_OCR/requirements.txt b/examples/usecases/mistral_OCR/requirements.txtnew file mode 100644index 000000000..52815067d--- /dev/null+++ b/examples/usecases/mistral_OCR/requirements.txt@@ -0,0 +1,5 @@+camel-ai==0.2.61+streamlit+pillow+mistralai+