<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manaranjan Pradhan on Medium]]></title>
        <description><![CDATA[Stories by Manaranjan Pradhan on Medium]]></description>
        <link>https://medium.com/@manaranjanp?source=rss-ebd214554fa2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zHepjYgfDCKHhXQGrqjdkw.jpeg</url>
            <title>Stories by Manaranjan Pradhan on Medium</title>
            <link>https://medium.com/@manaranjanp?source=rss-ebd214554fa2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:25:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manaranjanp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Top Down Design of RAG Systems: Part 1 — User and Query Profiling]]></title>
            <link>https://medium.com/@manaranjanp/top-down-design-of-rag-systems-part-1-user-and-query-profiling-184651586854?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/184651586854</guid>
            <category><![CDATA[financial-rag]]></category>
            <category><![CDATA[rag-system]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 14:08:37 GMT</pubDate>
            <atom:updated>2024-11-03T15:48:11.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top Down Design of RAG Systems: Part 1 — User and Query Profiling</h3><p>In today’s world, we have more data available than ever before. <strong>Retrieval-Augmented Generation (RAG) systems</strong> are a powerful way to combine the intelligence of language models with the accuracy of searching for the right information. But there’s an important question here: how should we design these systems? Should we start from the bottom up using the data we already have, or should we begin by thinking about what users really need?</p><h3>Top down vs bottom up design</h3><p>Isn’t this what many organizations did while adopting machine learning, trying to <strong>find insights and build models simply because they had a lot of data, without understanding the actual business problem they were trying to solve?</strong> As a result, these models and insights often ended up being irrelevant and never saw the light of day. This kind of bottom-up approach, where you start with the data and try to make something out of it, lacks the purpose-driven design needed to really address user needs. It often leads to systems that might look impressive from a technical standpoint but don’t serve any meaningful purpose for the users or the business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Irkp0Aqdy-umS-7CR8EgoA.png" /><figcaption>Top down vs bottom up approach</figcaption></figure><p>This is exactly what is happening again! In a lot of consulting conversations I’ve had, people usually kick things off by asking about the best way to chunk their data or documents for building RAG systems.</p><p>Well, do we even know who are our users and what are their expectations? Are there many different users that may ask many different questions and have different expectations, which can be served from same set of domain documents?</p><p>A top-down approach to designing RAG systems is all about starting with the user’s experience and needs. It means figuring out what problems we want to solve and what kind of answers people are looking for. From there, we <strong>work backward to figure out which data to use, how to retrieve it, and how to combine it with the generative model to get the best possible results.</strong> This way, the system is built to meet specific user needs, making it much more useful and relevant.</p><h3>Use Case: Building a RAG System for Financial Professionals</h3><p>Imagine we are building a RAG system specifically for investment managers, auditors, and other financial professionals, giving them access to quarterly and annual investor filings from several companies in India over the last 10 years. In this case, the first step is to understand the types of questions these users are likely to ask, ranging from simple to complex inquiries that can be answered using the RAG system, with a chat assistant as the user interface.</p><p>To start, we need to profile the different user groups — such as investment managers seeking insights into financial health, auditors looking for compliance issues, or analysts exploring industry trends. Each of these user segments will have unique needs and expectations from the system.</p><p>The first step in designing a RAG system should be <strong>profiling users and understanding the types of queries they are likely to ask</strong>. This helps in defining what kind of information and documents are necessary, the complexity of the queries, and the quality of responses that users expect. Profiling users involves identifying different user segments, such as novice users, experts, or those looking for specific use cases. Each group may have different needs and expectations.</p><h3>Collecting user queries</h3><p>To understand user needs, it is important to engage directly with potential users and gather insights into their expectations, challenges, and goals. Standard methodologies that can be used to collect this information as listed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XWj0r2YdPrOUcT9r9z3yQ.png" /><figcaption>Methodologies for collecting user queries</figcaption></figure><p>User interviews can also help identify the domain experts who can be stakeholders in the project. Some users, who are <strong>domain experts</strong> can guide while designing and evaluating these systems better and make sure they align with the user goals and not deviate from delivering real values to the users.</p><p>We may not be able to capture every possible user query intent by interviewing users, as we would in traditional software requirement gathering. There is likely <strong>a long tail of user queries</strong> that will only emerge once the system is in use, revealing new, unanticipated questions. However, it’s still essential to have a basic understanding of user intents and expectations to develop an effective system.</p><h3>Query Samples</h3><p>Here is an example of query sample from the user interviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*-Ra99PeeJpZaoGdsYV0UEA.png" /><figcaption>Sample user queries along with user profile, topics and complexity</figcaption></figure><p>The queries gives insight into the categories of questions that user might ask, which cover a range of areas, including key financial indicators, risk assessment, compliance, growth potential, and broader industry challenges. By profiling these queries, we can ensure that the RAG system is designed with a clear focus on the needs of each user type and is equipped with the necessary documents and retrieval strategies to provide high-quality responses.</p><h3>Information span for the queries</h3><p>When designing systems to answer financial queries using company data, it’s crucial to understand the scope of information required for different types of questions. This helps gauge retrieval complexity. For example, information spans early helps design more effective retrieval systems that can handle both straightforward financial lookups and complex analytical queries that require synthesizing information across multiple investor filings from companies across different sectors and across time periods.</p><p>The sample queries provides initial understanding of the structure of repository that you will build for retrieval of information for different query types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vJKpJ7jZa5wfpBDk2H-cQ.png" /><figcaption>Examples of patterns of information span for answering user queries</figcaption></figure><p>We can also collect information like expected latency and sample responses for these queries, which would help in evaluation. (More on evaluation on future blog series)</p><p>Complexity and <strong>information span</strong> for the queries also help prioritize the queries that can be developed in stages and in iterative fashion. For example, developing RAG system for a specific sector in the first stage that answers simple queries by auditors or investment managers.</p><p>In the next blog, we will address the next steps on what to do after collecting user queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=184651586854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Comic Book Creation with CrewAI Agents: Creative Content Generation]]></title>
            <link>https://medium.com/@manaranjanp/automating-comic-book-creation-with-crewai-agents-creative-content-generation-113324e676cf?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/113324e676cf</guid>
            <category><![CDATA[dalle-3]]></category>
            <category><![CDATA[creative-content]]></category>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[genertive-ai]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 12:34:59 GMT</pubDate>
            <atom:updated>2024-10-07T13:04:26.879Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Once upon a time, creating a comic book was a laborious process, requiring writers, illustrators, and countless hours of effort. Today, artificial intelligence has emerged as a powerful tool that augments the capabilities of creative professionals. Imagine giving a short story to an AI, and watching it help transform that story into a vibrant, visually stunning comic book — all while preserving the creator’s unique vision. This is no longer just a fantasy; it’s a reality made possible by cutting-edge generative AI models. In this blog, we’ll explore how CrewAI LLM agents can enhance the creative process of comic book creation, diving into the architecture and implementation that makes this magic possible.</p><h4><strong>Example: Creating a Story Book from Panchatantra</strong></h4><p>To demonstrate this process, let’s use a short story from the Panchatantra — a collection of ancient Indian fables known for their wisdom and moral lessons. Consider the story of ‘The Lion and the Rabbit’:</p><p><em>Short Story</em>: “Once upon a time, there lived a mighty lion named Bhasuraka, who terrorized the jungle. The animals, tired of his tyranny, decided to send him a prey every day. One day, it was a clever rabbit’s turn, and he devised a plan to rid the jungle of the lion. He led Bhasuraka to a deep well, convincing him that another lion lived there. Bhasuraka, seeing his reflection in the water, roared in anger and jumped into the well, never to return.”</p><p>Using the CrewAI framework, we would follow these steps:</p><ol><li><strong>Script Writer Agent</strong>: The Script Writer would break down the story into scenes such as:</li></ol><ul><li>Scene 1: The lion terrorizes the jungle.</li><li>Scene 2: The animals decide to send a prey every day.</li><li>Scene 3: The rabbit plans to trick the lion.</li><li>Scene 4: The lion jumps into the well.</li></ul><ol><li><strong>Visual Artist Agent</strong>: The Visual Artist would then generate illustrations for each of these scenes, depicting key moments like the lion roaring in the jungle, the rabbit leading the lion to the well, and the final scene of the lion jumping into the water.</li><li><strong>Synthesizer Agent</strong>: Finally, the Synthesizer would combine all these scenes and images into a cohesive storybook, making it ready for viewing and sharing.</li></ol><p>For more details on Panchatantra stories, you can refer to external resources such as <a href="https://en.wikipedia.org/wiki/Panchatantra">Panchatantra on Wikipedia</a> or <a href="https://www.pitara.com/fiction-for-kids/folktales/indian-folktales/the-panchatantra-stories/">collections of Panchatantra stories</a>.</p><p><strong>Using LLM Agents to Automate Creative Generation</strong></p><p>Generative AI agents can be thought of as a digital “crew” working together to execute complex creative processes. By assigning specific tasks to individual AI agents, the process of creating an entire comic picture book becomes streamlined and automated. In the diagram below, specialized agents work together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*na4N3ryN8D9UWrvDaRYRfQ.png" /></figure><ol><li><strong>Script Writer</strong>: Responsible for transforming a short story into detailed, broken-down scenes.</li><li><strong>Visual Artist</strong>: Tasked with converting each of these scenes into captivating visual artwork.</li><li><strong>Synthesizer</strong>: Responsible for combining all the generated scenes and their corresponding images into a cohesive and complete comic book. The Synthesizer ensures that the narrative flows smoothly and that the final product is ready for publishing.</li></ol><p>The synergy between these agents automates the process of comic book creation, enabling an efficient and creative workflow. The key lies in leveraging the capabilities of generative language models and image-generative AI systems in a coordinated manner.</p><p><strong>Architecture Overview</strong></p><p>The architecture for this automation is straightforward yet effective. The process begins with a short story and proceeds as follows:</p><ol><li><strong>Short Story Input</strong>: The process starts with a short narrative as input, which serves as the basis for the comic book.</li><li><strong>Script Writer Agent</strong>: This agent breaks down the short story into discrete scenes, each capturing an important part of the storyline. In the diagram, this is shown as scenes labeled “Scene 1, Scene 2, Scene 3,” and so on, until the entire story is divided into several smaller scenes.</li><li><strong>Visual Artist Agent</strong>: The Visual Artist takes each scene description and creates visual representations for each one, effectively drawing the artwork for the comic. The visual elements are created as images representing scenes like a lion under the sun, a lion meeting a rabbit, and more.</li><li><strong>Synthesizer</strong>: Finally, all scenes and their corresponding images are combined by a synthesizer agent to create a complete picture book.</li></ol><p>The entire process aims at a seamless transformation of a narrative into an engaging comic book, requiring minimal human intervention.</p><p><strong>Implementing Using CrewAI Framework</strong></p><p>To bring this vision to life, we implemented the CrewAI framework with three agents working in harmony. Here are the detailed steps involved in the implementation, with placeholders for code snippets from the attached file to help you reproduce the process step by step:</p><p><strong>Defining the Agents and Tasks</strong>: We define two agents using the CrewAI framework — Agent 1 (Script Writer) and Agent 2 (Visual Artist). Both agents have specific roles to play, and their tasks are linked for efficient workflow.</p><pre># Agent<br>scriptwriter:<br>  role: &gt;<br>    Write scripts for scenes for short stories for kids<br>  goal: &gt;<br>    Write simple, clear and engaging scenes for short stories for kids for picture books.<br>  backstory: &gt;<br>    You are script writer focussing on converting short stories for kids into scripts for enacting or creation of animations.<br>  llm: llm_model               <br><br># Task<br><br>scriptwriting:<br>  description: &gt;<br>    You are given a short story for kids on learning important lessons on life. The story need to be converted to <br>    a picture book for fun reading and engagement for the kids. You are responsible for breaking down story into <br>    {number_of_scenes} distinct scenes, each focused on a specific event or moment in the story. Each scene will be <br>    converted to an image in the picture. You must generate the following information in the pydantic schema specified:<br><br>    - An apt name for the story <br>    - A short summary of the story <br>    - A short exposition of the story providing the reader with important background information.<br>    - Detailed narration of each scene in the story at least in one or two sentences.<br>    - The final lesson learnt from the story.<br><br>    &lt;short_story&gt;    <br>      {story_text}<br>    &lt;/short_story&gt;   <br>  expected_output: &gt;   <br>    The output must follow the pydantic schema strictly. There will be penalty if not followed.       <br>  agent: scriptwriter<br><br># Agent<br><br>visualartist:<br>  role: &gt;<br>    Visual illustrations for story books<br>  goal: &gt;<br>    Create engaging picture books.<br>  backstory: &gt;<br>    Expert in creating picture story books.<br>  llm: llm_model<br><br># Task<br><br>illustration:<br>  description: &gt; <br><br>    You are given a short story for kids on learning important lessons on life. The story will to be converted to <br>    a picture book for fun reading and engagement for the kids. The story is already broken down into distinct scenes.<br><br>    Below is a description of a specific scence from a story whose short summary is also given below. <br>    <br>    Generate a prompt  which can be used by a text to image model to generate an image for the scene. Send the prompt to the <br>    tool provided to generated the image that depicts characters and backgrounds appropriately as per the requirements of the scenes. <br>    And the characters should be in cartoon style. The prompts should be in less than 40 words.<br><br>    &lt;story_summary&gt;<br>      {story_summary}<br>    &lt;story_summary&gt;<br><br>    &lt;scene_description&gt;<br>      {scene_description}<br>    &lt;/scene_description&gt;<br>  expected_output: &gt;   <br>    The output must follow the pydantic schema strictly. There will be penalty if not followed.       <br>  agent: visualartist</pre><p><strong>Crew Configuration: </strong>Define the structured schemas for the agents to generate the responses and llm model like OpenAI and DaLLE models for the agent. And bind the agents with their tasks.</p><pre>dalle_tool = DallETool(model=&quot;dall-e-3&quot;,<br>                       size=&quot;1024x1024&quot;,<br>                       quality=&quot;standard&quot;,<br>                       n=1)<br><br># Define a class for an individual scene<br>class StoryScene(BaseModel):<br>    scene_number: int <br>    narration: str<br><br># Define a class for a list of story scenes<br>class StoryScenes(BaseModel):<br> story_name: str <br> summary: str <br> background: str <br> lesson: str <br> scenes: List[StoryScene]<br><br># Define a class for an individual scene<br>class SceneImage(BaseModel):<br>    prompt: str = Field(description = &quot;A prompt for text to image models that can be used to generate an image.&quot;, max_length = 50)<br>    image_url: str = Field(description = &quot;Url to the image generated by the tool&quot;)<br><br>@CrewBase<br>class StoryCrew():<br> &quot;&quot;&quot;StoryCrew crew&quot;&quot;&quot;<br><br> agents_config = &#39;config/story/agents.yaml&#39;<br> tasks_config = &#39;config/story/tasks.yaml&#39;<br><br> @llm<br> def llm_model(self):<br>  return ChatOpenAI(temperature=0.0,  # Set to 0 for deterministic output<br>                    model=&quot;gpt-4o-mini&quot;,  # Using the GPT-4 Turbo model<br>                    max_tokens=8000) <br><br> @agent<br> def scriptwriter(self) -&gt; Agent:<br>  return Agent(<br>   config=self.agents_config[&#39;scriptwriter&#39;],<br>   output_pydantic = StoryScenes,   <br>   verbose=True<br>  )<br><br> @task<br> def scriptwriting(self) -&gt; Task:<br>  return Task(<br>   config=self.tasks_config[&#39;scriptwriting&#39;],<br>   output_pydantic = StoryScenes,   <br>  )<br><br> @crew<br> def crew(self) -&gt; Crew:<br>  &quot;&quot;&quot;Creates the StoryCrew crew&quot;&quot;&quot;<br>  script_crew =  Crew(<br>   agents=self.agents, # Automatically created by the @agent decorator<br>   tasks=self.tasks, # Automatically created by the @task decorator<br>   process=Process.sequential,<br>   verbose=True,<br>   # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/<br>  )<br><br>  return script_crew<br> <br>@CrewBase<br>class ArtistCrew():<br><br> agents_config = &#39;config/visual/agents.yaml&#39;<br> tasks_config = &#39;config/visual/tasks.yaml&#39;<br><br> @llm<br> def llm_model(self):<br>  return ChatOpenAI(temperature=0.0,  # Set to 0 for deterministic output<br>                    model=&quot;gpt-4o-2024-08-06&quot;,  # Using the GPT-4 Turbo model<br>                    max_tokens=8000) <br><br> @agent<br> def visualartist(self) -&gt; Agent:<br>  return Agent(<br>   config=self.agents_config[&#39;visualartist&#39;],<br>   tools=[dalle_tool],   <br>   verbose=True<br>  )<br><br> @task<br> def illustration(self) -&gt; Task:<br>  return Task(<br>   config=self.tasks_config[&#39;illustration&#39;],<br>   output_pydantic = SceneImage,      <br>   output_file=&#39;report.md&#39;<br>  )<br><br> @crew<br> def crew(self) -&gt; Crew:<br>  &quot;&quot;&quot;Create the picture book crew&quot;&quot;&quot;<br>  artist_crew =  Crew(<br>   agents=self.agents, # Automatically created by the @agent decorator<br>   tasks=self.tasks, # Automatically created by the @task decorator<br>   process=Process.sequential,<br>   verbose=True,<br>   # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/<br>  ) <br><br>  return artist_crew</pre><p><strong>Main Workflow: </strong>Ensure proper hand-offs between the two agents. For instance, once the Script Writer completes a scene, it automatically passes it on to the Visual Artist, ensuring continuity in the workflow.</p><pre>agentops.start_session( tags = [&#39;story&#39;, &#39;scripts&#39;] )<br><br># Creating hypothesis or generating questions using QuestCrew<br>inputs = {<br>    &#39;number_of_scenes&#39;: int(number_of_scenes),<br>    &#39;story_text&#39;: story_text,<br>}<br><br>scenes_list = StoryCrew().crew().kickoff(inputs=inputs)<br><br>agentops.end_session(&quot;Success&quot;)<br><br>if scenes_list is not None:        <br>    print(f&quot;Raw result from script writing: {scenes_list.raw}&quot;)<br><br>slist = scenes_list.pydantic<br>story_summary = slist.summary<br>for scene in slist.scenes:<br>    print(f&quot;Scene: {scene.narration}&quot;) <br><br>scene_input = [{ &quot;story_summary&quot;: story_summary,<br>    &#39;scene_description&#39;: scene.narration} for i, scene in enumerate(slist.scenes)]<br><br>agentops.start_session(tags = [&#39;scene&#39;, &#39;illustration&#39;])<br><br># Run the agent<br>result_images = ArtistCrew().crew().kickoff_for_each(inputs = scene_input)<br><br>print(&quot;result_images : {result_images.raw}&quot;)</pre><h3><strong>Conclusion</strong></h3><p>The power of generative AI lies in its ability to enhance and support the creative process, offering new tools for content creators to bring their ideas to life. The CrewAI LLM agents assist in turning a simple short story into a captivating comic picture book, helping storytellers at each stage of the journey. By automating repetitive tasks like script breakdown and visual generation, AI allows artists and writers to focus more on the core creative elements, preserving their unique artistic touch. This implementation demonstrates how generative AI can augment creative industries, providing a glimpse into a future where creativity and technology work hand-in-hand seamlessly.</p><p>Let me know if you’d like to explore more about CrewAI or have questions about implementing a similar creative solution for your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113324e676cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Systems with Vision Language Models: Chatting with Complex Documents]]></title>
            <link>https://medium.com/@manaranjanp/revolutionizing-rag-systems-chatting-with-complex-documents-using-vision-language-models-c8896a55bc31?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8896a55bc31</guid>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[colpali]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[rag-system]]></category>
            <category><![CDATA[chat-with-pdf]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 16:51:02 GMT</pubDate>
            <atom:updated>2024-10-01T06:44:01.451Z</atom:updated>
            <content:encoded><![CDATA[<p>As data-driven decisions become the norm, tools that help extract relevant information from documents are more critical than ever. Retrieval-Augmented Generation (RAG) systems excel in this space, but they struggle with documents containing visual elements like tables, charts, and infographics. Traditional RAG systems, designed for text-heavy data, require developers to go through laborious processes — such as text extraction, OCR, and layout analysis — to make complex documents usable. This makes handling real-world documents inefficient and time-consuming, often leading to fragmented or incomplete answers.</p><h3>The Challenge of Complex Document Formats</h3><p>RAG systems rely primarily on text models, which means handling documents like PDFs or HTML files involves several steps:</p><ul><li><strong>Text and Metadata Extraction</strong></li><li><strong>OCR for Embedded Text in Images</strong></li><li><strong>Layout Analysis to Handle Tables and Charts</strong></li></ul><p>These steps are not only complex but also lead to a loss of context, negatively impacting retrieval accuracy and slowing down the overall process. With real-world documents, it’s not enough to extract just the text — charts, tables, and infographics often hold key information that text models cannot easily interpret.</p><h3>Vision Language Models (VLMs): A Game Changer</h3><p>Vision Language Models (VLMs) offer a groundbreaking solution. Unlike traditional models that only process text, VLMs can interpret both visual and textual data. This enables them to understand a document holistically, including images, tables, charts, and other complex elements, alongside text.</p><p>One significant innovation in this space is <a href="https://huggingface.co/blog/manu/colpali"><strong>ColPali</strong></a>, a system that bypasses the traditional extraction methods by embedding entire PDF pages — including all visual and textual content — into vector representations. This eliminates the need for OCR or layout analysis and drastically simplifies the RAG pipeline for complex documents.</p><h3>How ColPali Transforms Complex Document Interaction</h3><p>ColPali reimagines how we work with complex document formats in the following ways:</p><ol><li><strong>No Text Chunking or Layout Parsing Required:</strong> ColPali embeds entire document pages, including all visual elements, into vector form, avoiding the need to break the document into smaller text chunks. This allows for a more holistic understanding and retrieval of information.</li><li><strong>Multimodal Processing:</strong> VLMs combine text and visuals, allowing ColPali to simultaneously process paragraphs of text alongside charts, tables, or infographics. This integrated understanding improves the relevance and accuracy of retrieval.</li><li><strong>Multi-Vector Representations for Better Retrieval:</strong> Instead of one vector for the entire document, ColPali creates multiple vectors — one for each content type (text, image, table, etc.) — which significantly improves the accuracy of the retrieval process.</li><li><strong>Late-Interaction Scoring for Nuanced Matching:</strong> ColPali leverages late-interaction scoring to ensure better alignment between the query and the document’s multimodal content, leading to more precise responses.</li></ol><h3>Enhanced Citations and References</h3><p>A key benefit of VLM-enhanced RAG systems like ColPali is their ability to generate more meaningful citations and references. With VLMs, the system can reference not just text but also the exact chart, table, or infographic where the information resides, maintaining visual context. This results in citations that are not only more accurate but also more informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGJQtVZar9p4UM_I0M1ybw.png" /></figure><p>The screenshot illustrates a Retrieval-Augmented Generation (RAG) tool powered by a Vision Language Model (VLM) that can answer questions from complex documents such as PDFs. The tool allows users to upload a document (e.g., an annual report) and ask questions directly in natural language.</p><p>In the example shown:</p><ul><li>The user uploads a annual report in pdf format and asks, <em>“What is the percentage of electricity comes from renewable sources?”</em></li><li>The system processes the document, including text, tables, and infographics, and retrieves a relevant answer: <em>“67.52% of Infosys India operations come from renewable sources.”</em></li></ul><p>Below the answer, the tool shows the source, a page from the PDF, containing a chart or infographic, ensuring that the answer is both accurate and contextually referenced. The integration of VLM allows the tool to process both visual and textual data, making it possible to retrieve information from various elements in the document, like tables and charts, without requiring text-only extraction techniques like OCR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xTE-Mpx38hXsu7shsK7wQ.png" /></figure><p>In this second screenshot, the tool demonstrates the capability to extract information from financial tables within a PDF document. The user uploads an annual report and asks for the <strong>consolidated cost of sales expenses for the year 2024</strong>.</p><ul><li>The tool quickly retrieves and provides the answer: <strong>₹1,07,413 crore</strong>, directly extracted from the table in the PDF.</li><li>Below the answer, the tool references the table from the “Board’s report” section of the document, ensuring that the context and source are clearly visible.</li></ul><h3>Implementation Steps</h3><p>This code implements a <strong>RAG (Retrieval-Augmented Generation)</strong> system using <strong>FastAPI</strong> as the backend and <strong>React</strong> for the frontend. The main idea is to allow users to upload a PDF, ask questions about the content of that document, and receive an answer along with the relevant page as an image. The backend uses a multimodal RAG model to handle document indexing and retrieval, while the frontend facilitates file upload and querying, and displays the answers to the user.</p><h3>Frontend (React) Implementation:</h3><p><strong>File Upload:</strong></p><ul><li>The frontend provides a form for uploading a PDF document. The handleFileUpload function manages this process, sending the file to the backend using a POST request via the fetch API.</li><li>The file is appended to a FormData object and sent to the backend for processing. Once uploaded successfully, the setIsUploaded(true) function updates the state to indicate that a file has been uploaded and is ready for querying.</li></ul><p><strong>Question Submission:</strong></p><ul><li>After the PDF is uploaded, the user can submit a question via a form. The handleQuestionSubmit function sends the user’s question as a JSON payload to the backend.</li><li>The backend responds with the answer and the base64-encoded image of the relevant page from the PDF. These are displayed in the frontend: the answer is rendered as text, and the pageImage is converted into an image element using the base64 string.</li></ul><p><strong>Rendering Results:</strong></p><ul><li>Once the question is answered, the frontend dynamically updates the interface to show both the answer text and the image of the relevant document page.</li><li>The frontend uses React components like Textarea and Button to build the UI for input submission, and Card components to render the response.</li></ul><pre>const handleFileUpload = async (e: React.FormEvent) =&gt; {<br>    e.preventDefault()<br>    if (!file) return<br><br>    const formData = new FormData()<br>    <br>    formData.append(&#39;file&#39;, file)<br><br>    try {<br>      const response = await fetch(&#39;https://c7ce-34-16-160-219.ngrok-free.app/upload&#39;, {<br>        method: &#39;POST&#39;,<br>        body: formData,<br>      })<br>      if (response.ok) {<br>        setIsUploaded(true)<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error uploading file:&#39;, error)<br>    }<br>  }<br><br>  const handleQuestionSubmit = async (e: React.FormEvent) =&gt; {<br>    e.preventDefault()<br>    try {<br>      const response = await fetch(&#39;https://c7ce-34-16-160-219.ngrok-free.app/question&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify({ question }),<br>      })<br>      if (response.ok) {<br>        const data = await response.json()<br>        setAnswer(data.answer)<br>        setPageImage(`data:image/png;base64,${data.page_image}`)<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error submitting question:&#39;, error)<br>    }<br>  }<br><br>  return (<br>    &lt;div className=&quot;flex h-screen&quot;&gt;<br>      &lt;div className=&quot;w-[30%] p-4 bg-gray-100&quot;&gt;<br>        &lt;h2 className=&quot;text-2xl font-bold mb-4&quot;&gt;RAG using Vision Language Model&lt;/h2&gt;<br>        &lt;form onSubmit={handleFileUpload} className=&quot;mb-4&quot;&gt;<br>          &lt;Input<br>            type=&quot;file&quot;<br>            accept=&quot;.pdf&quot;<br>            onChange={(e) =&gt; setFile(e.target.files?.[0] || null)}<br>            className=&quot;mb-2&quot;<br>          /&gt;<br>          &lt;Button type=&quot;submit&quot; className=&quot;w-full&quot;&gt;Upload PDF&lt;/Button&gt;<br>        &lt;/form&gt;<br>        &lt;form onSubmit={handleQuestionSubmit}&gt;<br>          &lt;Textarea<br>            placeholder=&quot;Enter your question here&quot;<br>            value={question}<br>            onChange={(e) =&gt; setQuestion(e.target.value)}<br>            disabled={!isUploaded}<br>            className=&quot;mb-2&quot;<br>          /&gt;<br>          &lt;Button type=&quot;submit&quot; disabled={!isUploaded} className=&quot;w-full&quot;&gt;<br>            Submit Question<br>          &lt;/Button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;w-[70%] p-4 overflow-y-auto&quot;&gt;<br>        &lt;h2 className=&quot;text-2xl font-bold mb-4&quot;&gt;Answer and Reference&lt;/h2&gt;<br>        &lt;Card className=&quot;mb-4&quot;&gt;<br>          &lt;CardHeader&gt;<br>            &lt;CardTitle&gt;Answer&lt;/CardTitle&gt;<br>          &lt;/CardHeader&gt;<br>          &lt;CardContent&gt;<br>            &lt;p&gt;{answer}&lt;/p&gt;<br>          &lt;/CardContent&gt;<br>        &lt;/Card&gt;<br>        {pageImage &amp;&amp; (<br>          &lt;Card&gt;<br>            &lt;CardContent&gt;<br>              &lt;img src={pageImage} alt=&quot;Relevant page&quot; className=&quot;w-full&quot; /&gt;<br>            &lt;/CardContent&gt;<br>          &lt;/Card&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Backend (FastAPI) Implementation:</h4><p><strong>Model Initialization:</strong></p><ul><li><strong>FastAPI</strong> is initialized to manage API routes. The backend uses a global RAG model and a generative model (Gemini) for handling queries.</li><li>Upon starting the application, the startup_event function loads the RAG model (vidore/colpali-v1.2) and the generative model (gemini-1.5-flash) from Hugging Face and GenAI, respectively. These models are then used to handle both document processing and natural language responses.</li></ul><p><strong>File Indexing:</strong></p><ul><li>The /upload endpoint allows users to upload a PDF document. The uploaded file is read and stored temporarily, after which the file is indexed by the RAG model.</li><li>The indexing process prepares the document so that relevant content can be retrieved based on user queries. This involves indexing both the text and images within the document for future retrieval.</li></ul><p><strong>Answer Generation:</strong></p><ul><li>The /question endpoint handles user queries. It receives the question in JSON format, searches the indexed PDF for relevant content, and generates an answer.</li><li>The get_answer function is key to this process. It performs a search query using the RAG model, retrieves the most relevant content (including base64-encoded images of the document page), and passes the result to the Gemini generative model for a natural language response.</li><li>The <strong>Gemini</strong> generative model processes both the image and the query to generate a response. This is particularly important because it allows the system to answer questions based on both text and visual content (e.g., charts, tables) from the PDF.</li><li>The get_answer function returns both the base64-encoded image and the generated answer, which is then sent to the frontend.</li></ul><pre># Initialize FastAPI application<br>app = FastAPI()<br><br># Define a Pydantic model for the incoming JSON request for the question<br>class Question(BaseModel):<br>    question: str  # This model expects a &quot;question&quot; string in the input<br><br># Global variables for RAG model and generative model<br>RAG = None  # To store the multimodal RAG model for document retrieval<br>model = None  # To store the generative model for text generation<br><br># FastAPI startup event: Runs when the server starts<br>@app.on_event(&quot;startup&quot;)<br>def startup_event():<br>    &quot;&quot;&quot;<br>    Initialize RAG and generative models during application startup.<br>    &quot;&quot;&quot;<br>    global RAG, model<br><br>    # Set API tokens from environment variables<br>    os.environ[&quot;HF_token&quot;] = &lt;set the api key&gt;  # Token for Hugging Face<br>    genai.configure(api_key=&lt;set the api key&gt;)  # Configure GenAI with API key<br><br>    # Load the generative model (Gemini model from GenAI)<br>    model = genai.GenerativeModel(model_name=&quot;gemini-1.5-flash&quot;)<br><br>    # Print statement to indicate model is being downloaded<br>    print(&quot;Downloading model: vidore/colpali-v1.2 from huggingface.&quot;)<br><br>    # Load the RAG model for multimodal (text and image) document processing<br>    RAG = RAGMultiModalModel.from_pretrained(&quot;vidore/colpali-v1.2&quot;, verbose=1)<br><br># POST endpoint to handle file uploads<br>@app.post(&quot;/upload&quot;)<br>async def upload_file(file: UploadFile = File(...)):<br>    &quot;&quot;&quot;<br>    Uploads a PDF file, saves it temporarily, and indexes it for future queries using the RAG model.<br>    &quot;&quot;&quot;<br>    # Read the uploaded PDF file as bytes<br>    pdf_bytes = await file.read()<br><br>    # Print message to indicate the file has been read<br>    print(&quot;File is read.....&quot;)<br><br>    # Create a temporary file to save the uploaded PDF<br>    with tempfile.NamedTemporaryFile(delete=False, suffix=&quot;.pdf&quot;) as temp_file:<br>        # Write the contents of the uploaded file to the temporary file<br>        temp_file.write(pdf_bytes)<br>        temp_file_path = temp_file.name  # Store the temporary file path<br><br>    # Print statement indicating the file path of the saved PDF<br>    print(f&quot;pdf file created: {temp_file_path}&quot;)<br><br>    global RAG, model<br><br>    # Index the file using the RAG model to make it searchable<br>    RAG.index(<br>        input_path=temp_file_path,  # Path to the uploaded PDF<br>        index_name=&quot;Filing&quot;,  # Name of the index for the document<br>        store_collection_with_index=True,  # Store base64 representations<br>        overwrite=True  # Overwrite any existing indexed document<br>    )<br><br>    # Return a success message after file has been processed and indexed<br>    return {<br>        &quot;message&quot;: &quot;File uploaded and processed successfully&quot;,<br>    }<br><br># Helper function to generate a random image filename<br>def generate_image_filename(extension=&#39;jpg&#39;):<br>    &quot;&quot;&quot;<br>    Generates a random 10-character filename for images.<br>    &quot;&quot;&quot;<br>    # Generate a random string of 10 alphanumeric characters<br>    random_string = &#39;&#39;.join(random.choices(string.ascii_letters + string.digits, k=10))<br>    # Return the random filename with the provided extension<br>    filename = f&quot;{random_string}.{extension}&quot;<br>    return filename<br><br># Function to retrieve answer from the RAG model and generative model<br>def get_answer(query):<br>    &quot;&quot;&quot;<br>    Searches the RAG model using the query and generates an answer using the generative model.<br>    &quot;&quot;&quot;<br>    global RAG, model<br><br>    # Search the indexed document using the RAG model and retrieve the top result<br>    results = RAG.search(query, k=1, return_base64_results=True)<br><br>    # Base64-decode the retrieved page image (in base64 format)<br>    image_bytes = base64.b64decode(results[0].base64)<br>    # Generate a random filename for the image<br>    filename = generate_image_filename()<br><br>    # Write the decoded image bytes to a file<br>    with open(filename, &#39;wb&#39;) as f:<br>        f.write(image_bytes)<br><br>    # Open the saved image file using PIL (Python Imaging Library)<br>    image = pil.Image.open(filename)<br>    # Use the generative model to generate a response based on the image and query<br>    response = model.generate_content([image, query])<br><br>    # Print the generated response for debugging<br>    print(f&quot;Gemini response: {response}&quot;)<br><br>    # Return both the base64-encoded image and the generated text response<br>    return results[0].base64, response.text<br><br># POST endpoint to handle question answering<br>@app.post(&quot;/question&quot;)<br>def answer_question(question: Question):<br>    &quot;&quot;&quot;<br>    Receives a question from the user, retrieves relevant content from the PDF,<br>    and generates an answer using the generative model.<br>    &quot;&quot;&quot;<br>    # Print the received question for logging/debugging<br>    print(f&quot;The question is:{question.question}&quot;)<br><br>    # Get the answer (text and image) for the provided question<br>    image_base64, response = get_answer(question.question)<br><br>    # Print the response for debugging purposes<br>    print(f&quot;Response is: {response}&quot;)<br><br>    # Create a JSON response containing the answer and the relevant page image<br>    resp_json = {<br>        &quot;answer&quot;: response,  # The generated text response<br>        &quot;page_image&quot;: image_base64  # The base64-encoded image of the relevant page<br>    }<br><br>    # Return the JSON response with the answer and page image<br>    return JSONResponse(content=resp_json)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fue90wf-Ypek%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Due90wf-Ypek&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fue90wf-Ypek%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6736cd9b1e7bbb586593d88cfebf77db/href">https://medium.com/media/6736cd9b1e7bbb586593d88cfebf77db/href</a></iframe><h3>Conclusion: The Future of Document Understanding</h3><p>With the integration of Vision Language Models, systems like ColPali mark the future of document understanding. They enable RAG systems to process complex documents — such as financial reports, legal contracts, or technical papers — that contain both textual and visual information. The result is a more efficient, accurate, and comprehensive system for retrieving and generating answers from complex documents, ultimately transforming how we interact with data.</p><p>In this new era of multimodal RAG systems, the entire document — text, images, tables, and charts — is accessible, readable, and usable, pushing the boundaries of what retrieval models can achieve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8896a55bc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Collaborative AI Agent Framework for Automated EDA using CrewAI]]></title>
            <link>https://medium.com/@manaranjanp/building-a-collaborative-ai-agent-framework-for-automated-eda-using-crewai-351478b424ce?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/351478b424ce</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[eda-agent]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 16:12:50 GMT</pubDate>
            <atom:updated>2024-09-22T16:41:28.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: A New Era of Data Exploration</h3><p>In today’s data-driven world, businesses are continuously seeking ways to extract actionable insights from vast datasets. Traditionally, this task has been the domain of skilled data scientists, who spend considerable time exploring and analyzing data. But what if we could automate this process? What if an AI-driven system could ask insightful questions about the data, analyze it thoroughly, and present a detailed report — all with minimal human intervention? This is precisely what our project aims to achieve by leveraging the CrewAI agent framework.</p><h3>Context of the Project</h3><p>The project revolves around automating the Exploratory Data Analysis (EDA) process using AI agents. The primary goal is to create a system that can take a dataset along with its metadata, generate insightful questions, and then answer these questions using a data analysis agent. The final product is a comprehensive EDA report in markdown format, ready to be shared with stakeholders or further refined by data professionals.</p><h3>Why Automate EDA?</h3><p>EDA is a critical step in data science, allowing analysts to understand the structure, patterns, and relationships within a dataset before applying more advanced techniques. However, EDA can be time-consuming and repetitive, especially when dealing with large datasets. Automating this process not only saves time but also ensures consistency and thoroughness, enabling data scientists to focus on more complex tasks.</p><h3>Project Overview</h3><h3>The CrewAI Framework</h3><p>The project is built on the CrewAI framework, which allows for the creation of collaborative AI agents. In this context, the framework facilitates the coordination of two key types of agents:</p><ol><li><strong>Business Consultant Agent</strong>: This agent is responsible for generating insightful questions about the dataset. It examines the metadata and determines what aspects of the data warrant further exploration.</li><li><strong>Data Scientist Agent</strong>: Once the questions are generated, the Data Scientist agent takes over. This agent generates Python code to answer each question, executes the code, interprets the results, and summarizes the findings in a markdown format.</li></ol><h3>How It Works</h3><p>The process can be broken down into the following steps:</p><ol><li><strong>Metadata Analysis and Question Generation</strong>: The Business Consultant agent analyzes the dataset metadata and generates a series of questions designed to probe deeper into the data. These questions might involve investigating the distribution of a particular variable, examining correlations between variables, or testing a hypothesis.</li><li><strong>Automated Code Generation and Execution</strong>: For each question, the Data Scientist agent generates the necessary Python code to perform the required analysis. This could involve creating visualizations, conducting statistical tests, or applying machine learning models. The code is then executed, and the outputs — such as plots and statistical summaries — are captured.</li><li><strong>Result Summarization</strong>: The results of the analysis are compiled into a markdown report. This report includes the original questions, the Python code used, the outputs generated, and a summary of the findings.</li></ol><h3>Defining the Agents</h3><h4>Business Consultant Agent</h4><p>The Business Consultant agent is tasked with generating meaningful and relevant questions about the dataset. These questions are crucial as they guide the subsequent analysis. The agent is defined in the YAML configuration file as follows.</p><pre>business_consultant:<br>  role: &gt;<br>    Business Consultant<br>  goal: &gt;<br>    Generate insightful business questions based on the data and metadata. <br>  backstory: &gt;<br>    You are an experienced business consultant skilled at asking great questions based on the data and metadata..<br>  llm: llm_model    </pre><pre>generate_questions_task:<br>  description: &gt;<br>    Below is the description of a dataset containng the context and the description of data elements.<br>    - Based on your understanding of the metadata, generate {how_many} questions which woul give deeper insights into the domain the data represents. <br>    - Questions should be about specific variables and based on univariate or bivariate analysis.<br>    - The insights should be based on some of the basic statistical anlaysis like histogram, correlation analysis, hypothesis tests, bar plots, distribution or outlier analysis etc.<br><br>    &lt;metadata&gt;<br>      {metadata_info}<br>    &lt;/metadata&gt;<br>  expected_output: &gt;   <br>    A list of question as specified by schema.<br>  agent: business_consultant</pre><p>This configuration outlines the agent’s role, goals, and the parameters it uses to generate questions. The agent leverages a language model (e.g., GPT-4) to interpret the metadata and formulate questions that can be explored through statistical analysis or visualization.</p><h4>Data Scientist Agent</h4><p>The Data Scientist agent’s role is to answer the questions generated by the Business Consultant agent. It does this by writing and executing Python code. The agent is also defined in the YAML configuration file:</p><pre>data_scientist:<br>  role: &gt;<br>    Data Scientist<br>  goal: &gt;<br>    Generate code to answer the question,  execute the code, interpret and summarize the results.<br>  backstory: &gt;<br>    You are a skilled data scientist proficient in exploratory data analysis, statistics, machine learning.<br>  llm: llm_model    </pre><pre>datascience_task:<br>  description: &gt;<br>    You are tasked with generating the Python code, executing and summarizing to answer the question given a dataset. <br>    You are given the following information:<br><br>    - Dataset description: &lt;dataset_description&gt; {metadata_info} &lt;/dataset_description&gt;<br>    - Question: &lt;question&gt; {question_str} &lt;/question&gt;<br><br>    Steps to Follow:<br><br>    1. Must follow the guidelines below strictly to generate the code.<br>      - The code should use pandas, numpy, matplotlib, seaborn, statsmodel and scikit-learn libraries.<br>      - Include the above libraries and any other library that may be required.<br>      - Load the dataset from the dataset_location given below: <br>        &lt;dataset_location&gt;<br>          {datapath_info} <br>        &lt;/dataset_location&gt;  <br>      - Assuming the data is already clean (skip data preparation)<br>      - Use statistical tests and plots to answer the questions.<br>      - Do not do summary statistics on all the variables.<br>      - Focus only on the question in hand and use variables that are necessary for the analysis.<br>      - Must print all intermediate results and final results on the console.<br>      - The plot must be saved in png format at the below directory. Add plt.savefig() with the location below after the plots is created.  <br>        &lt;imagepath&gt; <br>          {imagepath_dir} <br>        &lt;/imagepath&gt;<br>      - Ensure the code is clear, efficient, and well-commented.<br><br>    2. The generated code satisfies the following conditions. If answer to any of the following is no, then the code generated in invalid.<br>      - Is dataset loaded from the &lt;dataset_location&gt; specified above ?<br>      - Is the code only use relevant variables in the dataframe for analysis that are necessary to answer the question?<br>      - Is atleast one plot generated?<br>      - Is the code saving the plot only in the &lt;imagepath&gt; directory mentioned above?<br>      - Are the results or outputs of printed to the console?<br><br>    3. Execute the code using the appropriate tool<br>    3. Collect all output <br>    4. Interpret and summarize the results from statistical tests and plots in outputs       <br>      <br>  agent: data_scientist<br>  expected_output: &gt;<br>    Summary or conclusion from the results or plots. <br>    The output should be in MARKDOWN format and must contain the following sections. It should start with question header as below. <br>    ### Question<br>       - question<br>    ### Code<br>      - The code provided in the context as it is, without any changes. Embed the code in fenced code blocks?<br>    ### Code Output<br>      Outputs from code execution<br>    ### Analysis<br>      Inference and summarization of the code outputs</pre><p>This agent uses well-known Python libraries such as Pandas, NumPy, Matplotlib, and Seaborn to conduct the analysis. The code generated by this agent is not only functional but also designed to be clear, efficient, and well-documented, ensuring that the analysis can be easily understood and replicated.</p><h3>Implementing the Crews</h3><p>To bring these agents to life, we implement two key components: QuestCrew and EDACrew.</p><h4>QuestCrew</h4><p>QuestCrew is responsible for coordinating the Business Consultant agent. It initializes the agent, provides it with the necessary metadata, and captures the questions generated. Here’s a glimpse of what this looks like:</p><pre><br>class QuestionList(BaseModel):<br>    questions: List[str]<br><br><br>pyrepltool = PythonREPL()<br><br>@CrewBase<br>class QuestCrew():<br> &quot;&quot;&quot;Quest crew&quot;&quot;&quot;<br> agents_config = &#39;config/quest/agents.yaml&#39;<br> tasks_config = &#39;config/quest/tasks.yaml&#39;<br><br> @llm<br> def llm_model(self):<br>  return ChatOpenAI(temperature=0.0,  # Set to 0 for deterministic output<br>                    model=&quot;gpt-4o-2024-08-06&quot;,  # Using the GPT-4 Turbo model<br>                    max_tokens=8000) <br> <br> @agent<br> def business_consultant(self) -&gt; Agent:<br>  return Agent(<br>   config=self.agents_config[&#39;business_consultant&#39;],<br>   max_rpm=None,<br>   verbose=True<br>  )<br><br> @task<br> def generate_questions_task(self) -&gt; Task:<br>  return Task(<br>   config=self.tasks_config[&#39;generate_questions_task&#39;],<br>   output_pydantic = QuestionList<br>  )<br><br> @crew<br> def crew(self) -&gt; Crew:<br>  &quot;&quot;&quot;Creates the Llmeda crew&quot;&quot;&quot;<br>  question_crew = Crew(<br>   agents=self.agents,<br>   tasks=self.tasks, # Automatically created by the @task decorator<br>   process=Process.sequential,<br>   verbose=True,<br>   output_log_file = &quot;qgen.log&quot;<br>   # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/<br>  )<br>  <br>  return question_crew</pre><h4>EDACrew</h4><p>EDACrew handles the Data Scientist agent, which performs the actual data analysis. After receiving the questions from QuestCrew, it generates and executes the Python code to answer each question, and then compiles the results into a markdown report</p><pre>@CrewBase<br>class EDACrew():<br> &quot;&quot;&quot;EDA crew&quot;&quot;&quot;<br> agents_config = &#39;config/eda/agents.yaml&#39;<br> tasks_config = &#39;config/eda/tasks.yaml&#39;<br><br> @llm<br> def llm_model(self):<br>  return ChatOpenAI(temperature=0.0,  # Set to 0 for deterministic output<br>                    model=&quot;gpt-4o-2024-08-06&quot;,  # Using the GPT-4 Turbo model<br>                    max_tokens=8000) <br> <br>  #return ChatAnthropic(temperature=0.2, model=&#39;claude-3-5-sonnet-20240620&#39;)<br><br>  # return ChatGoogleGenerativeAI(<br>  #   model=&quot;gemini-1.5-flash&quot;,<br>  #   temperature=0,<br>  #   max_tokens=4096,<br>  #   max_retries=2)<br> <br>  return ChatGroq(<br>   model=&quot;llama3.1-70b-versatile&quot;,<br>   temperature=0.0,<br>   max_retries=2,<br>  ) <br><br> @agent<br> def data_scientist(self) -&gt; Agent:<br>  return Agent(<br>   config=self.agents_config[&#39;data_scientist&#39;],<br>   verbose=True<br>  )<br> <br> @task<br> def datascience_task(self) -&gt; Task:<br>  return Task(<br>   config=self.tasks_config[&#39;datascience_task&#39;],<br>   tools=[pyrepl_tool]<br>  )<br> <br> @crew<br> def crew(self) -&gt; Crew:<br>  &quot;&quot;&quot;Creates the Llmeda crew&quot;&quot;&quot;<br>  eda_crew = Crew(<br>   agents=self.agents,<br>   tasks=self.tasks, # Automatically created by the @task decorator<br>   process=Process.sequential,<br>   verbose=True,<br>   output_log_file = &quot;eda.log&quot;<br>   # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/<br>  )<br>  <br>  return eda_crew</pre><h3>Main Execution Flow</h3><p>The main script orchestrates the entire process. It starts by reading the dataset metadata and initializing the agent operations. The QuestCrew is run first to generate the questions, followed by EDACrew, which performs the analysis. Finally, the results are consolidated into a markdown report.</p><pre><br>def read_file(file_path):<br>    with open(file_path, &#39;r&#39;) as file:<br>        content = file.read()<br>    return content<br><br>def generate_markdown_for_images(directory):<br>    # Get list of PNG files in the directory<br>    images = [img for img in os.listdir(directory) if img.endswith(&#39;.png&#39;)]<br><br>    # Start the markdown section<br>    markdown_content = &quot;### Plots \n\n&quot;<br><br>    # Loop through each image and generate markdown<br>    for img in images:<br>        image_path = os.path.join(directory, img)<br>        markdown_content += f&quot;![{img}]({image_path})\n\n&quot;<br><br>    return markdown_content<br><br>def run():<br>    &quot;&quot;&quot;<br>    Run the crew.<br>    &quot;&quot;&quot;<br><br>    print(f&quot;Current working directory: {os.getcwd()}&quot;)<br><br>    # Initilize the agentops for tracing of communication with LLMs<br>    agentops.init(auto_start_session=False)<br><br>    # Read the YAML config file<br>    with open(&#39;config.yaml&#39;, &#39;r&#39;) as f:<br>        config = yaml.safe_load(f)    # Read the config file<br><br>    # Reading configuarations<br>    metadata_txt = read_file(config[&#39;app&#39;][&#39;Metadata&#39;])<br>    datapath = config[&#39;app&#39;][&#39;DataPath&#39;]<br>    imagepath = config[&#39;app&#39;][&#39;ImagePath&#39;]<br>    num_questions = config[&#39;app&#39;][&#39;NumOfQuestions&#39;]<br><br>    print(f&quot;Metadata file location: {metadata_txt}&quot;)<br>    print(f&quot;Datapath location: {datapath}&quot;)<br>    print(f&quot;Plots location: {imagepath}&quot;)   <br><br>    # To store analysis for each questions.<br>    md_content = []<br>    <br>    agentops.start_session( tags = [&#39;question&#39;, &#39;hypothesis&#39;] )<br><br>    # Creating hypothesis or generating questions using QuestCrew<br>    q_inputs = {<br>        &#39;how_many&#39;: int(num_questions),<br>        &#39;metadata_info&#39;: metadata_txt,<br>    }<br><br>    # Run the agent<br>    qresult = QuestCrew().crew().kickoff(inputs=q_inputs)<br><br>    agentops.end_session(&quot;Success&quot;)<br><br>    if qresult is not None:        <br>        print(f&quot;Raw result from crew.kickoff: {qresult.raw}&quot;)<br>    <br>    qlist = qresult.pydantic<br>    for q in qlist.questions:<br>        print(f&quot;Question: {q}&quot;)            <br><br>    # Create the directories for storing the created plots<br>    for i in range(len(qlist.questions)):<br>        os.makedirs(f&quot;{imagepath}/q_{i}&quot;, exist_ok=True)   <br><br>    # Creating the EDACrews for generate code and answer those questions<br>    # Also to summarize the questions<br>    <br>    eda_inputs_list = [{<br>        &#39;question_str&#39;: q,<br>        &#39;metadata_info&#39;: metadata_txt,<br>        &#39;datapath_info&#39;: datapath,<br>        &#39;imagepath_dir&#39;: f&quot;{imagepath}/q_{i}&quot;} for i, q in enumerate(qlist.questions)]<br><br>    agentops.start_session(tags = [&#39;answer&#39;, &#39;analysis&#39;])<br><br>    # Run the agent<br>    final_results = EDACrew().crew().kickoff_for_each(inputs = eda_inputs_list)<br><br>    agentops.end_session(&quot;Success&quot;)<br><br>    # Consolidating the writing to a file. <br>    try:<br>        with open(&quot;final_analysis.md&quot;, &#39;w&#39;) as file:<br>            file.write(&quot;# Exploratory Data Analysis&quot; + &#39;\n\n&#39;)<br>            file.write(&quot;## Dataset Description&quot; + &#39;\n\n&#39;)<br>            file.write(metadata_txt + &#39;\n\n&#39;)<br>            for i, mdc in enumerate(final_results):<br>                file.write(f&quot;## EDA Analysis - {i+1}&quot; + &#39;\n\n&#39;)<br>                print(mdc.raw)<br>                file.write(mdc.raw + &#39;\n\n&#39;)<br>                file.write(generate_markdown_for_images(f&quot;{imagepath}/q_{i}&quot;) +&quot;\n\n&quot;)<br>        print(f&quot;Successfully wrote to final_analysis.md&quot;)<br>    except IOError as e:<br>        print(f&quot;An error occurred while writing to the file: {e}&quot;)<br><br>    agentops.end_session(&quot;Success&quot;)</pre><h3>Generating the Markdown Report</h3><p>The final step involves consolidating all the analyses into a markdown file. This report includes the dataset description, each question posed by the Business Consultant agent, the code used to answer it, and the resulting analysis.</p><p>Here is an example of generated EDA report.</p><pre># Exploratory Data Analysis<br><br>## Dataset Description<br><br>A retrospective sample of males in a heart-disease high-risk region of the Western Cape, South Africa. There are roughly two controls per case of CHD. Many of the CHD positive men have undergone blood pressure reduction treatment and other programs to reduce their risk factors after their CHD event. In some cases the measurements were made after these treatments. These data are taken from a larger dataset, described in Rousseauw et al, 1983, South African Medical Journal.<br><br>Column names and their description:<br><br>sbp - systolic blood pressure<br>tobacco - cumulative tobacco (kg)<br>ldl - low densiity lipoprotein cholesterol<br>adiposity - https://en.m.wikipedia.org/wiki/Body_adiposity_index<br>famhist - family history of heart disease (Present, Absent)<br>typea - type-A behavior<br>obesity - https://en.wikipedia.org/wiki/Obesity<br>alcohol - current alcohol consumption<br>age - age at onset<br>chd - response, coronary heart disease<br><br><br>## EDA Analysis - 1<br><br>### Question<br>How does the distribution of systolic blood pressure (sbp) differ between individuals with and without coronary heart disease (chd), and what does this suggest about the relationship between blood pressure and heart disease risk in this population?<br><br>### Code<br>```python<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy.stats import ttest_ind<br><br># Load the dataset<br>dataset_url = &#39;https://raw.githubusercontent.com/manaranjanp/MLIntroV1/main/Classification/SAheart.data&#39;<br>data = pd.read_csv(dataset_url)<br><br># Plot the distribution of systolic blood pressure for individuals with and without CHD<br>plt.figure(figsize=(10, 6))<br>sns.histplot(data[data[&#39;chd&#39;] == 1][&#39;sbp&#39;], color=&#39;red&#39;, label=&#39;CHD&#39;, kde=True, stat=&#39;density&#39;, bins=30)<br>sns.histplot(data[data[&#39;chd&#39;] == 0][&#39;sbp&#39;], color=&#39;blue&#39;, label=&#39;No CHD&#39;, kde=True, stat=&#39;density&#39;, bins=30)<br>plt.title(&#39;Distribution of Systolic Blood Pressure by CHD Status&#39;)<br>plt.xlabel(&#39;Systolic Blood Pressure&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.legend()<br>plt.savefig(&#39;/Users/manaranjanp/Documents/Work/MyLearnings/fastHTML/llmeda/q_0/sbp_distribution.png&#39;)<br>plt.show()<br><br># Perform a t-test to compare the means of the two groups<br>chd_sbp = data[data[&#39;chd&#39;] == 1][&#39;sbp&#39;]<br>no_chd_sbp = data[data[&#39;chd&#39;] == 0][&#39;sbp&#39;]<br>t_stat, p_value = ttest_ind(chd_sbp, no_chd_sbp)<br><br># Print the results of the t-test<br>print(f&#39;T-test statistic: {t_stat}&#39;)<br>print(f&#39;P-value: {p_value}&#39;)<br>```<br><br>### Code Output<br>```<br>T-test statistic: 4.204044124452311<br>P-value: 3.1515993239517745e-05<br>```<br><br>### Analysis<br>The analysis shows a significant difference in the distribution of systolic blood pressure (sbp) between individuals with and without coronary heart disease (CHD). The t-test statistic is 4.204, and the p-value is approximately 3.15e-05, which is much less than the conventional alpha level of 0.05. This indicates that the difference in systolic blood pressure between the two groups is statistically significant. The histogram plot further illustrates that individuals with CHD tend to have higher systolic blood pressure compared to those without CHD. This suggests that higher systolic blood pressure is associated with an increased risk of coronary heart disease in this population.<br><br>### Plots <br><br>![sbp_distribution.png](/Users/manaranjanp/Documents/Work/MyLearnings/fastHTML/llmeda-12Sept/demo/q_0/sbp_distribution.png)<br><br><br><br>## EDA Analysis - 2<br><br>### Question<br>Is there a significant correlation between cumulative tobacco consumption (tobacco) and low-density lipoprotein cholesterol (ldl) levels, and how might this relationship impact the risk of developing coronary heart disease in this high-risk region?<br><br>### Code<br>```python<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy.stats import pearsonr<br>import statsmodels.api as sm<br><br># Load the dataset<br>dataset_url = &#39;https://raw.githubusercontent.com/manaranjanp/MLIntroV1/main/Classification/SAheart.data&#39;<br>data = pd.read_csv(dataset_url)<br><br># Display the first few rows of the dataset<br>data.head()<br><br># Check correlation between tobacco and ldl<br>correlation, p_value = pearsonr(data[&#39;tobacco&#39;], data[&#39;ldl&#39;])<br>print(f&#39;Correlation between tobacco and ldl: {correlation}, with a p-value of {p_value}&#39;)<br><br># Plotting the relationship between tobacco and ldl<br>plt.figure(figsize=(10, 6))<br>sns.scatterplot(x=&#39;tobacco&#39;, y=&#39;ldl&#39;, data=data)<br>plt.title(&#39;Scatter plot of Tobacco vs LDL&#39;)<br>plt.xlabel(&#39;Cumulative Tobacco (kg)&#39;)<br>plt.ylabel(&#39;LDL Cholesterol&#39;)<br>plt.savefig(&#39;/Users/manaranjanp/Documents/Work/MyLearnings/fastHTML/llmeda/q_1/tobacco_ldl_correlation.png&#39;)<br>plt.show()<br><br># Logistic regression to see the impact on CHD<br>X = data[[&#39;tobacco&#39;, &#39;ldl&#39;]]<br>y = data[&#39;chd&#39;]<br>X = sm.add_constant(X)  # adding a constant<br><br>model = sm.Logit(y, X)<br>result = model.fit()<br>print(result.summary())<br>```<br><br>### Code Output<br>```<br>Correlation between tobacco and ldl: 0.15890545800595818, with a p-value of 0.000607828617738955<br><br>Optimization terminated successfully.<br>         Current function value: 0.575236<br>         Iterations 5<br>                           Logit Regression Results                           <br>==============================================================================<br>Dep. Variable:                    chd   No. Observations:                  462<br>Model:                          Logit   Df Residuals:                      459<br>Method:                           MLE   Df Model:                            2<br>Date:                Thu, 05 Sep 2024   Pseudo R-squ.:                  0.1084<br>Time:                        17:55:51   Log-Likelihood:                -265.76<br>converged:                       True   LL-Null:                       -298.05<br>Covariance Type:            nonrobust   LLR p-value:                 9.427e-15<br>==============================================================================<br>                 coef    std err          z      P&gt;|z|      [0.025      0.975]<br>------------------------------------------------------------------------------<br>const         -2.3305      0.293     -7.951      0.000      -2.905      -1.756<br>tobacco        0.1297      0.025      5.290      0.000       0.082       0.178<br>ldl            0.2447      0.053      4.607      0.000       0.141       0.349<br>==============================================================================<br>```<br><br>### Analysis<br>The correlation analysis between cumulative tobacco consumption and low-density lipoprotein cholesterol levels shows a positive correlation of approximately 0.159, which is statistically significant with a p-value of 0.0006. This indicates a weak but significant positive relationship between tobacco use and LDL levels.<br><br>The logistic regression results suggest that both tobacco consumption and LDL levels are significant predictors of coronary heart disease (CHD) in this dataset. The coefficients for tobacco and LDL are both positive, indicating that higher levels of these variables are associated with an increased risk of CHD. Specifically, the logistic regression model shows that for each unit increase in tobacco consumption, the log odds of having CHD increase by approximately 0.13, and for each unit increase in LDL, the log odds increase by approximately 0.24.<br><br>Overall, while the correlation between tobacco and LDL is weak, both factors independently contribute to the risk of developing CHD in this high-risk region.<br><br>### Plots <br><br>![tobacco_ldl_correlation.png](/Users/manaranjanp/Documents/Work/MyLearnings/fastHTML/llmeda-12Sept/demo/q_1/tobacco_ldl_correlation.png)</pre><p>Here is the link to the video, which goes through the detailed implementation of this ai agent.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe5VyHn5hbOw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De5VyHn5hbOw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe5VyHn5hbOw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a2485e7569d885a6f6713e33aa1bf4a/href">https://medium.com/media/3a2485e7569d885a6f6713e33aa1bf4a/href</a></iframe><h3>Summary: Revolutionising Data Analysis with AI</h3><p>This project represents a significant step forward in automating the EDA process. By leveraging the power of AI agents, we can generate insightful questions, conduct thorough analyses, and produce comprehensive reports — all in a fraction of the time it would take a human. This framework is not only efficient but also highly adaptable, making it suitable for a wide range of data analysis tasks across various domains.</p><p>As businesses continue to grapple with ever-growing datasets, solutions like this will become increasingly valuable. By automating routine analysis tasks, data scientists can focus on more strategic challenges, driving innovation and growth in their organisations. The future of data analysis is here, and it’s powered by AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=351478b424ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning OpenAI Models: Part 3— Model Evaluation]]></title>
            <link>https://medium.com/@manaranjanp/fine-tuning-openai-models-for-cricket-commentary-analysis-part-3-model-evaluation-87ba8c10a9f7?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ba8c10a9f7</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm-fine]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt-4o-mini]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 13:02:07 GMT</pubDate>
            <atom:updated>2024-08-31T13:22:51.490Z</atom:updated>
            <content:encoded><![CDATA[<p>In our journey to create an AI system capable of extracting structured information from cricket commentaries, we’ve covered data generation and model training in our previous posts: “<a href="https://medium.com/@manaranjanp/fine-tuning-openai-model-extracting-valuable-information-from-cricket-commentary-1e653ea9a19b">Part 1 — Data Generation</a>” and “<a href="https://medium.com/@manaranjanp/fine-tuning-openai-models-for-cricket-commentary-analysis-part-2-model-training-0926b0c60444">Part 2 — Model Training</a>”. Now, we arrive at a crucial stage: model evaluation. This step is vital in understanding whether our fine-tuning efforts have truly improved the model’s performance.</p><p>Model evaluation isn’t just about getting a single accuracy score. It’s a comprehensive process that involves comparing the fine-tuned model against the base model across various aspects of the task. In our case, we’re looking at how well each model extracts different pieces of information from cricket commentary.</p><h3>The Evaluation Process: From Commentary to Structured Data</h3><p>Before we delve into the code, let’s visualize what we’re trying to achieve. Imagine a piece of cricket commentary:</p><p>“Axar Patel steams in, Ben Stokes attempts a powerful slap down the ground, but Patel reacts quickly, catching the ball in his follow-through. A brilliant caught and bowled!”</p><p>Our model needs to transform this narrative into structured data. Here’s what we expect:</p><pre>expected_response = {<br>    &quot;bowler&quot;: &quot;Axar Patel&quot;,<br>    &quot;batsman&quot;: &quot;Ben Stokes&quot;,<br>    &quot;runs_scored&quot;: 0,<br>    &quot;is_out&quot;: True,<br>    &quot;wicket_type&quot;: &quot;Caught and Bowled&quot;,<br>    &quot;batsman_shot_type&quot;: &quot;Slap down the ground&quot;,<br>    &quot;bowling_type&quot;: &quot;Spin&quot;,<br>    &quot;fielding_position&quot;: &quot;Bowler&#39;s position&quot;,<br>    &quot;fielded_by&quot;: &quot;&quot;,<br>    &quot;caught_by&quot;: &quot;Axar Patel&quot;<br>}</pre><p>And here’s what our model might produce:</p><pre>model_response = {<br>    &quot;bowler&quot;: &quot;AXAR PATEL&quot;, <br>    &quot;batsman&quot;: &quot;Ben stokes&quot;, <br>    &quot;runs_scored&quot;: 1, <br>    &quot;is_out&quot;: True,<br>    &quot;wicket_type&quot;: &quot;caught&quot;, <br>    &quot;batsman_shot_type&quot;: &quot;Slap down the ground&quot;,<br>    &quot;bowling_type&quot;: &quot;spin&quot;, <br>    &quot;fielding_position&quot;: &quot;Bowler&#39;s position&quot;,<br>    &quot;fielded_by&quot;: &quot;John Doe&quot;, <br>    &quot;caught_by&quot;: &quot;axar patel&quot; <br>}</pre><p>Our evaluation script needs to compare these responses, understanding that some differences (like capitalization) aren’t significant, while others (like the number of runs scored) are crucial.</p><p>Let’s dive deeper into each component of our evaluation script:</p><h3>1. Extracting Content from JSON</h3><p>This function is crucial because our test data comes in a specific JSON format, containing system messages, user inputs, and expected outputs. By extracting and organizing this content, we prepare our data for processing by the model and subsequent evaluation.</p><pre>def extract_content(json_string):<br>    data = json.loads(json_string)<br># Initialize the result dictionary with empty strings for each role<br>    result = {<br>        &quot;system&quot;: &quot;&quot;,<br>        &quot;user&quot;: &quot;&quot;,<br>        &quot;assistant&quot;: &quot;&quot;<br>    }<br>    # Iterate through each message in the data<br>    for message in data[&#39;messages&#39;]:<br>        role = message[&#39;role&#39;]<br>        content = message[&#39;content&#39;]<br>        # If the role is one we&#39;re interested in (system, user, or assistant)<br>        if role in result:<br>            # If the content is a dictionary, convert it to a JSON string<br>            # This ensures consistency in how we handle different content types<br>            if isinstance(content, dict):<br>                result[role] = json.dumps(content)<br>            else:<br>                result[role] = content```<br>return result</pre><h3>2. Comparing Messages</h3><p>This function is the heart of our evaluation process. It compares the model’s output with the expected output field by field. The case-insensitive comparison for strings is particularly important in our cricket context. For instance, “Axar Patel” and “AXAR PATEL” should be considered a match, as the difference in capitalization doesn’t affect the accuracy of the extracted information.</p><pre>def compare_messages(message1, message2):<br>    result = {}<br>    # Get all unique keys from both messages<br>    all_keys = set(message1.keys()) | set(message2.keys())<br>    <br>    for key in all_keys:<br>        if key in message1 and key in message2:<br>            value1 = message1[key]<br>            value2 = message2[key]<br>            <br>            # Perform case-insensitive comparison for strings<br>            # This helps in handling minor discrepancies in text fields<br>            if isinstance(value1, str) and isinstance(value2, str):<br>                result[key] = value1.lower() == value2.lower()<br>            else:<br>                result[key] = value1 == value2<br>        else:<br>            # If a key is missing in either message, mark it as a mismatch<br>            result[key] = False<br>    <br>    return result</pre><h3>3. Aggregating Results</h3><p>After comparing individual responses, we need to see the bigger picture. This function takes all our comparison results and compiles them into a summary. The resulting DataFrame gives us a clear view of how the model performs across different fields. This is crucial for identifying which aspects of the task the model excels at and where it struggles.</p><pre>def aggregate_comparisons(comparison_results):<br>    aggregated = {}<br>    <br>    # Iterate through all comparison results<br>    for result in comparison_results:<br>        for key, value in result.items():<br>            if key not in aggregated:<br>                aggregated[key] = {&#39;matches&#39;: 0, &#39;mismatches&#39;: 0}<br>            <br>            # Count matches and mismatches for each field<br>            if value:<br>                aggregated[key][&#39;matches&#39;] += 1<br>            else:<br>                aggregated[key][&#39;mismatches&#39;] += 1<br>    <br>    # Create a DataFrame from the aggregated results<br>    df = pd.DataFrame.from_dict(aggregated, orient=&#39;index&#39;)<br>    df.index.name = &#39;field&#39;<br>    df.reset_index(inplace=True)<br>    # Calculate accuracy for each field<br>    df[&#39;accuracy&#39;] = df[&#39;matches&#39;] / (df[&#39;matches&#39;] + df[&#39;mismatches&#39;])<br>    return df</pre><h3>4. Creating API Request Prompt</h3><p>This function might seem simple, but it’s critical for ensuring consistent interaction with the OpenAI API. By formatting our prompts consistently, we ensure that any performance differences we observe are due to the model itself, not variations in how we’re querying it.</p><pre>def get_request_prompt(system_msg, user_msg):<br>    return [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: sys_msg}, <br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_msg}]</pre><h3>5. Calling the models</h3><p>This function is where we actually engage with the AI model. By using the parse method, we&#39;re asking the API to not just generate text, but to structure its output according to our CommenatryInfo schema. This is a key feature that helps ensure the model&#39;s output is in a consistent, analyzable format.</p><pre>def extractInformation(model, prompt) -&gt; CommenatryInfo:<br>    completion = client.beta.chat.completions.parse(<br>        model=model,<br>        messages=prompt,<br>        response_format=CommenatryInfo)<br># Extract the parsed response from the API result<br>    cric_commentary = completion.choices[0].message.parsed<br>    return cric_commentary</pre><h3>6. Reading JSONL Files</h3><p>JSONL (JSON Lines) is an excellent format for our test data, as it allows us to store multiple JSON objects in a single file, one per line. This function reads this file format, preparing our test cases for processing.</p><pre>def read_jsonl(file_path):<br>    with open(file_path, &#39;r&#39;) as file:<br>        try:<br>            # Read each line of the file, stripping whitespace<br>            messages = [line.strip() for line in file]<br>        except json.JSONDecodeError as e:<br>            # If there&#39;s an error parsing the JSON, print the error message<br>            print(f&quot;Error message: {str(e)}&quot;)<br>return messages</pre><h3>7. Invoking the Models</h3><p>In the main execution block, we process each test case through both the base model and the fine-tuned model. This allows for a direct comparison of their performance on identical inputs.</p><pre># Read messages from the JSONL file<br>    messages = read_jsonl(sys.argv[1])<br># List to store the results of comparing model outputs with baselines<br>    comparison_results = []<br>    # Process each message in the input file<br>    for msg in messages:<br>        # Extract content from the JSON message<br>        json_contents = extract_content(msg)<br>        # Create a prompt for the OpenAI API using the system message and user content<br>        prompt = get_request_prompt(sys_msg, json_contents[&#39;user&#39;])<br>        # Extract information using the OpenAI API<br>        # Note: The model identifier is hardcoded here. Consider making this configurable.<br>        cinfo = extractInformation(&quot;gpt-4o-mini-2024-07-18&quot;, prompt)<br>    <br>#        cinfo = extractInformation(&quot;ft:gpt-4o-mini-2024-07-18:personal::A2EkrtrO&quot;, prompt)<br>    <br>        # Compare the extracted information with the baseline (assistant) response<br>        # The baseline response is assumed to be in the &#39;assistant&#39; field of json_contents<br>        comparison_results.append(compare_messages(json.loads(json_contents[&#39;assistant&#39;]), cinfo.model_dump()))<br>    # Aggregate the comparison results to get overall performance metrics<br>    final_results = aggregate_comparisons(comparison_results)</pre><h3>Analysing the Results</h3><p>The image below gives us a side-by-side comparison of the base model and fine-tuned model performance. Let’s break this down further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFCgCKz6iu60cIFpjHFetQ.png" /></figure><p><strong>Significant Improvements:</strong></p><ul><li>batsman_shot_type: Accuracy increased from 0.505 to 0.59. This 8.5% improvement is substantial, suggesting our fine-tuning significantly enhanced the model&#39;s ability to identify specific cricket shots.</li><li>fielded_by: Improved from 0.86 to 0.89. While a smaller increase, this shows refinement in identifying fielding details.</li><li>caught_by: Increased from 0.92 to 0.94. This high accuracy got even better, crucial for correctly recording dismissals.</li></ul><p><strong>Consistent High Performance:</strong></p><ul><li>is_out: Both models achieved perfect accuracy (1.0). This suggests that determining whether a batsman is out is a relatively straightforward task for the model.</li><li>batsman: Maintained at 0.935. While not perfect, this high accuracy was consistent across both models.</li></ul><p><strong>Areas of Concern:</strong></p><ul><li>bowling_type: Decreased from 0.515 to 0.455. This 6% drop is significant and warrants investigation. It could indicate that our fine-tuning dataset may have introduced some bias or confusion in this category.</li></ul><p><strong>Overall Trend:</strong></p><p>The fine-tuned model shows improvements or maintains performance in 8 out of 10 categories. This suggests that our fine-tuning process was generally successful, but there’s still room for improvement.</p><h3>Conclusion and Next Steps</h3><p>Our evaluation reveals that fine-tuning has indeed improved our model’s performance in extracting cricket commentary information. However, the process has also highlighted areas that need further attention.</p><p>To build on this success and address the remaining challenges, we could:</p><ol><li>Conduct an error analysis on the bowling_type field. Are there specific types of bowling that the model is confusing? This could guide us in curating additional training data.</li><li>Increase the diversity of our training data, especially for fields that showed minimal improvement. This could involve sourcing commentary from a wider range of matches, commentators, or cricket formats.</li><li>Experiment with different fine-tuning approaches. We might try adjusting hyper-parameters, using different learning rates, or exploring techniques like few-shot learning within the fine-tuning process.</li><li>Perform a detailed error analysis across all fields. By examining the specific instances where the model makes mistakes, we might identify patterns that could inform further improvements.</li><li>Consider the trade-offs in our model. Is the slight decrease in bowling_type accuracy acceptable given the improvements in other areas? This depends on the specific use case for our model.</li></ol><p>Remember, model development is an iterative process. These evaluation results are not just a final score, but a roadmap for our next steps. By continuously cycling through the stages of data curation, model training, and thorough evaluation, we can push the boundaries of what’s possible in AI-powered sports analytics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ba8c10a9f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning OpenAI Models for Cricket Commentary Analysis: Part 2 — Model Training]]></title>
            <link>https://medium.com/@manaranjanp/fine-tuning-openai-models-for-cricket-commentary-analysis-part-2-model-training-0926b0c60444?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0926b0c60444</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[finetune-llm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 08:01:11 GMT</pubDate>
            <atom:updated>2024-09-02T13:51:03.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fine-tuning OpenAI Model: Part 2 — Model Training</h3><p>In our previous blog post, “<a href="https://medium.com/@manaranjanp/fine-tuning-openai-model-extracting-valuable-information-from-cricket-commentary-1e653ea9a19b">Fine-tuning OpenAI model: Part 1 — Data Generation</a>”, we discussed how to create a high-quality dataset for training a model to extract structured information from cricket commentaries. Now, let’s dive into the exciting world of model fine-tuning, where we’ll transform our base model into a cricket commentary analysis expert.</p><h3>What We’re Aiming For</h3><p>Before we delve into the technical details, let’s remind ourselves of our goal. We want to take a cricket commentary like this:</p><pre>&quot;Bumrah to Cummins, SIX, 126.4kph, innocuous lazy delivery, off a <br>back of a length sitting up on the pads. And Cummins swipes across <br>the line, getting it over short fine leg&quot;</pre><p>And have our fine-tuned model convert it into structured JSON data:</p><pre>{<br>  &quot;bowler&quot;: &quot;Bumrah&quot;,<br>  &quot;batsman&quot;: &quot;Cummins&quot;,<br>  &quot;runs_scored&quot;: 6,<br>  &quot;is_out&quot;: false,<br>  &quot;wicket_type&quot;: &quot;&quot;,<br>  &quot;batsman_shot_type&quot;: &quot;Swipe&quot;,<br>  &quot;bowling_type&quot;: &quot;Medium Pace&quot;,<br>  &quot;fielding_position&quot;: &quot;Short Fine Leg&quot;,<br>  &quot;fielded_by&quot;: &quot;&quot;,<br>  &quot;caught_by&quot;: &quot;&quot;<br>}</pre><p>This structured data will enable powerful analytics, real-time insights, and enhanced cricket coverage. Now, let’s explore how we achieve this through fine-tuning.</p><h3>Train and Test Set Creation</h3><p>Before we start fine-tuning, it’s crucial to split our generated data into training and test sets. This separation allows us to evaluate our model’s performance on unseen data, ensuring it generalizes well to new commentaries.</p><p>While our finetune.py script doesn&#39;t explicitly show this split, it&#39;s an important step in the process. Typically, you&#39;d want to allocate about 80% of your data for training and 20% for testing. You can use libraries like scikit-learn to perform this split:</p><pre>from sklearn.model_selection import train_test_split<br><br>with open(&#39;commentary.jsonl&#39;, &#39;r&#39;) as f:<br>    data = f.readlines()<br>train_data, test_data = train_test_split(data, test_size=0.4, random_state=42)<br>with open(&#39;train.jsonl&#39;, &#39;w&#39;) as f:<br>    f.writelines(train_data)<br>with open(&#39;test.jsonl&#39;, &#39;w&#39;) as f:<br>    f.writelines(test_data)</pre><p>This code reads our JSONL file, splits the data, and saves the train and test sets separately.</p><h3>Choosing a Smaller Model for Fine-tuning</h3><p>For our task, we’ve chosen the gpt-4o-mini-2024-07-18 model. This choice balances performance with efficiency:</p><ol><li>Computational Efficiency: Smaller models require less computational resources, making the fine-tuning process faster and more cost-effective.</li><li>Generalization: Sometimes, smaller models can generalize better to specific tasks, especially when we have a limited amount of training data.</li><li>Deployment Considerations: A smaller fine-tuned model will be quicker to serve in production environments, reducing latency for real-time applications.</li></ol><p>Let’s walk through the key components of our fine-tuning script:</p><h3>File Upload</h3><p>First, we upload our training file:</p><pre>def upload_file(filename: str) -&gt; Dict[str, Any]:<br>    try:<br>        with open(filename, &quot;rb&quot;) as file:<br>            return client.files.create(file=file, purpose=&quot;fine-tune&quot;)<br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error creating file: {e}&quot;)<br>        sys.exit(1)</pre><p>This function uploads our JSONL file to OpenAI’s servers. As we can see in the image below, our file commentary_short.jsonl is successfully uploaded and ready for fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*9UtiFB1-tLVKN8UvdCF_ww.png" /></figure><h3>Creating the Fine-tuning Job</h3><p>Next, we create the fine-tuning job:</p><pre>def create_finetune_job(training_file: str, model: str) -&gt; Dict[str, Any]:<br>    try:<br>        return client.fine_tuning.jobs.create(<br>            training_file=training_file,<br>            model=model,<br>            hyperparameters={&quot;n_epochs&quot;: 1, &quot;batch_size&quot;: 8}<br>        )<br>    except Exception as e:<br>        print(f&quot;Error creating fine-tuning job: {e}&quot;)<br>        sys.exit(1)</pre><p>This function sets up the fine-tuning job with our chosen model and training file. We’ve set n_epochs to 1 and batch_size to 8, but these can be adjusted based on your specific needs.</p><h3>Monitoring the Fine-tuning Process</h3><p>We monitor the progress of our fine-tuning job with this function:</p><pre>def monitor_finetune_job(job_id: str) -&gt; None:<br>    while True:<br>        time.sleep(30)<br>        try:<br>            job_status = client.fine_tuning.jobs.retrieve(job_id)<br>            print(f&quot;------------ Job Status: {job_status.status} --------------&quot;)<br>            if job_status.status in [&quot;failed&quot;, &quot;succeeded&quot;, &quot;cancelled&quot;]:<br>                            print(&quot;Job Completed. Detailed Events list:&quot;)<br>                            events = client.fine_tuning.jobs.list_events(fine_tuning_job_id=job_id)<br>                            for event in events:<br>                                print(f&#39;{datetime.fromtimestamp(event.created_at)} {event.message}&#39;)<br>                            <br>                            print(&quot;######## Fine-tuned model ###########&quot;)<br>                            print(f&quot;{job_status.fine_tuned_model}&quot;)<br>                            print(&quot;#####################################&quot;)<br>                            break<br>                    except Exception as e:<br>                        print(f&quot;Error monitoring job: {e}&quot;)<br>                        break</pre><p>This function provides real-time updates on the fine-tuning process, including any checkpoints created and the final model name.</p><h3>Training Loss and Epochs</h3><p>Training loss is a crucial metric that indicates how well our model is learning. In the image shown below, we can see the training loss curve for our fine-tuning job. The sharp initial decrease followed by a gradual leveling off is a good sign, indicating that our model is learning effectively without overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XUyffr4k7kuS2qUinie3A.png" /><figcaption>Training loss from finetuing</figcaption></figure><p>Our fine-tuning job ran for 3 epochs with a batch size of 3, as shown in the image below. The number of epochs and batch size can significantly impact the model’s performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYUqoIvJcxPnZpKUlwA07g.png" /><figcaption>Finetuning job details</figcaption></figure><ul><li>Epochs: More epochs allow the model to see the training data multiple times, potentially learning more nuanced patterns. However, too many epochs can lead to overfitting.</li><li>Batch Size: Smaller batch sizes can lead to more frequent model updates and sometimes better generalization, but they can also result in noisier gradients.</li></ul><p>In our case, 3 epochs seemed sufficient to achieve good performance without overfitting.</p><h3>Fine-tuning Results</h3><p>As we can see in the image below, our fine-tuning job completed successfully. The model went through several checkpoints and was evaluated against usage policies before being enabled for sampling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*d_lbRg5R70wOhOjJhy6umw.png" /></figure><p>The final fine-tuned model name is ft:gpt-4o-mini-2024-07-18:personal:cric-commentary-v1:9zPCGcgX. This model is now specialized in extracting structured information from cricket commentaries.</p><h3>Conclusion and Next Steps</h3><p>Fine-tuning an OpenAI model for cricket commentary analysis opens up exciting possibilities for enhancing cricket coverage and analytics. By transforming unstructured commentary into structured data, we enable a wide range of applications, from real-time match insights to detailed player performance analysis.</p><p>As next steps, consider:</p><ol><li>Evaluating the model’s performance on your test set to ensure it generalizes well.</li><li>Experimenting with different hyperparameters to optimize performance.</li><li>Integrating the fine-tuned model into a real-time cricket analysis system.</li></ol><p>Remember, the world of machine learning is ever-evolving. Stay curious, keep experimenting, and don’t hesitate to iterate on your model as you gather more data and insights.</p><p>What innovative applications can you envision for this cricket commentary analysis model? The possibilities are as vast as a cricket field on a sunny day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0926b0c60444" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning OpenAI models: Part 1 — Data Generation]]></title>
            <link>https://medium.com/@manaranjanp/fine-tuning-openai-model-extracting-valuable-information-from-cricket-commentary-1e653ea9a19b?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e653ea9a19b</guid>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[finetune-llm]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 07:30:07 GMT</pubDate>
            <atom:updated>2024-09-03T04:29:41.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Commentary to Clarity: Fine-tuning LLMs for Cricket Analysis</h3><p>In the fast-paced world of cricket, commentators paint vivid pictures with their words, capturing the essence of each delivery, shot, and fielding effort. But what if we could transform these rich narratives into structured data, unlocking new possibilities for analysis and insights? This is where the power of Large Language Models (LLMs) comes into play, specifically when fine-tuned for the nuances of cricket commentary.</p><h3>The Power of Structured Data: An Example</h3><p>Before we dive into the technical details, let’s look at a concrete example of what we’re aiming to achieve. Consider this snippet of cricket commentary:</p><p>Input Commentary:</p><pre>&quot;Bumrah to Cummins, SIX, 126.4kph, innocuous lazy delivery, off a back <br>of a length sitting up on the pads. And Cummins swipes across the line,<br>getting it over short fine leg&quot;<br><br>&quot;Chawla to Raina, 1 run, fifty for Raina. 29th in IPL. Not one of his best. <br>Quicker delivery on the stumps, clocked at 113kph, that&#39;s the pace of Bhatia.<br>Raina is hurried into the flick and sends it along the ground to deep mid-wicket&quot;<br><br>&quot;Siraj to A Russell, SIX, 150 up for Kolkata Knight Riders! Pitched up around<br> off, Russell reaches out for it and tonks it over long-off - possibly for<br> the longest six of the night. Chants of Kay, Kay, Aar all round the stadium!&quot;<br><br>&quot;Kuldeep Yadav to Rahane, out Bowled!! Oh, it&#39;s ugly when a batsman with <br>a Test hundred in almost every country tries circus tricks. Kuldeep fires <br>in the googly on middle and leg, Rahane gets across his stumps and tries to <br>whack it away behind point with a reverse sweep, misses it altogether and <br>ends up making a fool of himself.&quot;</pre><p>This single sentence packs a wealth of information about the game. To a cricket fan, it paints a vivid picture of the action. But for a computer to analyse this data effectively, we need to transform it into a structured format. Here’s what our fine-tuned model might produce:</p><p>Output JSON:</p><pre>{<br>  &quot;bowler&quot;: &quot;Bumrah&quot;,<br>  &quot;batsman&quot;: &quot;Cummins&quot;,<br>  &quot;runs_scored&quot;: 6,<br>  &quot;is_out&quot;: false,<br>  &quot;wicket_type&quot;: &quot;&quot;,<br>  &quot;batsman_shot_type&quot;: &quot;Swipe&quot;,<br>  &quot;bowling_type&quot;: &quot;Back of a length&quot;,<br>  &quot;fielding_position&quot;: &quot;Short Fine Leg&quot;,<br>  &quot;fielded_by&quot;: &quot;&quot;,<br>  &quot;caught_by&quot;: &quot;&quot;<br>}</pre><p>Let’s break down why this transformation is so powerful:</p><ol><li>Precise Data Extraction: The model has extracted key information like the bowler, batsman, and runs scored. This allows for accurate tracking of player statistics without manual data entry.</li><li>Contextual Understanding: The model has inferred that the delivery was “Medium Pace” based on the speed mentioned (126.4kph). This shows its ability to interpret cricket-specific information.</li><li>Shot Classification: The batsman’s action is classified as a “Swipe”, demonstrating the model’s understanding of cricket terminology and shot types.</li><li>Fielding Information: The model has captured the relevant fielding position, which can be crucial for analyzing field placements and strategies.</li><li>Implicit Information: The model correctly identifies that the batsman is not out and that no one caught or fielded the ball (as it went for six runs).</li></ol><p>This structured format enables various analytical possibilities:</p><ul><li>Player Performance Analysis: Easily track and compare players’ performances over time.</li><li>Strategy Insights: Analyse which types of deliveries are most effective against certain batsmen.</li><li>Commentary Quality Assessment: Evaluate the comprehensiveness of different commentators based on the information they provide.</li><li>Automated Highlights: Generate real-time highlights by identifying exciting moments (like this six) in the structured data.</li><li>Interactive Visualisations: Create dynamic, data-driven graphics for broadcasts or online platforms.</li></ul><p>By transforming unstructured commentary into this structured format, we bridge the gap between the narrative richness of cricket commentary and the precision needed for data-driven analysis. This opens up a world of possibilities for enhancing how we understand, analyze, and enjoy the game of cricket.</p><h3>The Need for Fine-tuning</h3><p>While general-purpose LLMs like GPT-4 are incredibly capable, they often lack the specialised knowledge and context required for domain-specific tasks. Cricket, with its unique terminology and rapid-fire commentary style, presents a particular challenge. Also smaller model can be used to extract information for a specific domain (here it is sports) instead of using larger models, which can be at a lower cost. Fine-tuning an LLM on cricket commentary data allows us to create a model that can:</p><ol><li>Understand cricket-specific jargon and context</li><li>Extract relevant information consistently</li><li>Output structured data in a format suitable for further analysis</li></ol><p>By fine-tuning, we’re essentially teaching the model to “think” like a cricket analyst, transforming unstructured commentary into valuable, actionable data.</p><p>Sometimes, the schema is also controlled for regulatory requirements (not necessary here) and make models return response using only a specific information. The models can be fine-tuned to return responses using a trained schema and change of schema is not permitted or restricted.</p><h3>The Fine-tuning Process: A Three-Step Journey</h3><p>Fine-tuning an LLM for cricket commentary analysis involves three main steps:</p><ol><li>Generate Instruction Dataset: Create a high-quality dataset of input-output pairs that demonstrate the desired behavior.</li><li>Fine-tune the Model: Use the instruction dataset to adjust the model’s parameters, enhancing its performance on the specific task.</li><li>Validate and Iterate: Test the fine-tuned model on new data, analyze its performance, and refine as needed.</li></ol><p>In this blog post, we’ll focus on the crucial first step: generating the instruction dataset.</p><h3>Generating the Instruction Dataset</h3><p>The key to successful fine-tuning lies in creating a diverse and representative dataset of cricket commentaries paired with their corresponding structured information. Let’s dive into the code that accomplishes this task.</p><h3>Setting the Stage</h3><p>First, let’s look at the foundational elements of our script:</p><pre>system_message = &quot;You are a cricket analyst who extracts information from commentary text based on the provided schema.&quot;<br><br>class CommenatryInfo(BaseModel):<br>    bowler: str<br>    batsman: str<br>    runs_scored: int<br>    is_out: bool<br>    wicket_type: str<br>    batsman_shot_type: str<br>    bowling_type: str<br>    fielding_position: str<br>    fielded_by: str<br>    caught_by: str<br><br>client = OpenAI()</pre><p>This setup imports necessary libraries, configures logging, and defines our CommenatryInfo model using Pydantic. The CommenatryInfo class is crucial as it defines the structure of our desired output, ensuring consistency and type safety.</p><h3>Extracting Information</h3><p>The heart of our data generation process lies in the extractInformation function:</p><pre>def get_request_prompt(commentary: str) -&gt; list:<br>    &quot;&quot;&quot;<br>    {&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, <br>     &quot;content&quot;: &quot;You are a cricket analyst who extracts information from commentary text&quot;}, <br>    {&quot;role&quot;: &quot;user&quot;, <br>     &quot;content&quot;: &quot;Siraj to Manoj Tiwary, FOUR, walks across towards off and effortlessly picks it away over backward square leg. Brilliantly timed yet again. Fine leg was up inside the ring and Tiwary picked his spot&quot;}]}<br>    &quot;&quot;&quot;<br>    return [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_message}, <br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: commentary}<br>    ]<br><br>def extractInformation(commentary: str) -&gt; CommenatryInfo:<br>    completion = client.beta.chat.completions.parse(<br>        model=&quot;gpt-4o-2024-08-06&quot;,<br>        messages=get_request_prompt(commentary),<br>        response_format=CommenatryInfo<br>    )<br>    return completion.choices[0].message.parsed</pre><p>This function takes a single commentary string and uses OpenAI’s API to extract structured information. The parse method is particularly powerful, as it ensures the response adheres to our CommenatryInfo schema.</p><h3>Processing Multiple Commentaries</h3><p>To handle multiple commentaries efficiently, we use the get_commentary_info function:</p><pre>def get_commentary_info(messages: list) -&gt; list:<br>    return [(msg, extractInformation(msg)) for msg in messages]</pre><p>This function applies our extraction process to a list of commentaries, returning pairs of original commentaries and their structured information.</p><h4>Understanding JSONL Format</h4><p>JSONL is a convenient format for storing structured data in a way that’s easy for machines to parse and for humans to read. Each line in a JSONL file is a valid JSON object, typically containing a single record. This format is ideal for our fine-tuning dataset because:</p><ol><li>It allows for easy processing of large datasets line by line.</li><li>It maintains the structure of our data, including nested objects.</li><li>It’s compatible with many machine learning tools and frameworks.</li></ol><p>Let’s look at an example of a single record in our JSONL file:</p><pre>{<br>  &quot;messages&quot;: [<br>    {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: &quot;You are a cricket analyst who extracts information from commentary text&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Aaron to Parthiv Patel, FOUR, lovely shot, Aaron - from round the wicket, slides this one onto Parthiv&#39;s hips, he gets inside the line, uses the angle and clips it behind square on the on-side for a boundary&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;assistant&quot;,<br>      &quot;content&quot;: &quot;{\&quot;bowler\&quot;: \&quot;Aaron\&quot;, \&quot;batsman\&quot;: \&quot;Parthiv Patel\&quot;, \&quot;runs_scored\&quot;: 4, \&quot;is_out\&quot;: false, \&quot;wicket_type\&quot;: \&quot;\&quot;, \&quot;batsman_shot_type\&quot;: \&quot;clip\&quot;, \&quot;bowling_type\&quot;: \&quot;round the wicket\&quot;, \&quot;fielding_position\&quot;: \&quot;behind square on the on-side\&quot;, \&quot;fielded_by\&quot;: \&quot;\&quot;, \&quot;caught_by\&quot;: \&quot;\&quot;}&quot;<br>    }<br>  ]<br>}</pre><p>Let’s break down this JSONL record:</p><ol><li>The entire record is a single JSON object containing a “messages” array.</li><li>The “messages” array contains three objects, each representing a part of the conversation:</li></ol><ul><li>The first object sets the system role, instructing the model to act as a cricket analyst.</li><li>The second object represents the user input, which is the cricket commentary.</li><li>The third object contains the assistant’s response, which is our structured JSON output.</li></ul><p>The assistant’s response is a stringified JSON object, containing the extracted information from the commentary.</p><p>This format effectively demonstrates to the model:</p><ul><li>The role it should assume (cricket analyst)</li><li>The input it will receive (cricket commentary)</li><li>The expected output format (structured JSON)</li></ul><p>In our JSONL file, each line will be a similar JSON object, representing a different commentary and its corresponding structured output. This approach allows us to provide numerous examples to the model during fine-tuning, helping it learn to consistently extract and structure information from cricket commentaries.</p><h3>Putting It All Together</h3><p>In the main execution block, we tie everything together:</p><pre>if __name__ == &quot;__main__&quot;:<br>    commentary_df = pd.read_csv(sys.argv[1])<br>    sample_commenatry_df = commentary_df.sample(int(sys.argv[2]))<br>    all_commentaries = get_commentary_info(sample_commenatry_df.Commentary)<br>    with open(sys.argv[3], &#39;w&#39;) as outfile:<br>        for commentary, commentary_info in all_commentaries:<br>            json.dump(format_request_response(commentary, commentary_info.model_dump()), outfile)<br>            outfile.write(&#39;\n&#39;)<br>    # Prepare and save CSV output<br>    df = pd.DataFrame([c.model_dump() for _, c in all_commentaries])<br>    df[&#39;commentary&#39;] = sample_commenatry_df.Commentary<br>    df[&#39;commentary_json&#39;] = [c.model_dump() for _, c in all_commentaries]<br>    df.to_csv(sys.argv[4], index=False)</pre><p>This script reads a CSV file of commentaries, samples a subset, processes each commentary, and saves the results in both JSONL and CSV formats.</p><h3>Validating Data Generation</h3><p>It is also imperative to validate the data quality before using the data for fine-tuing the model. The instruction data should be validated for data type check, role and message validation. There is an excellent article <a href="https://cookbook.openai.com/examples/chat_finetuning_data_prep">here</a>, which gives more detailed deep dive and code example. So, I urge the reader to read it. We will use the code provided for validating our code generation.</p><h3>Conclusion</h3><p>Generating an instruction dataset is a crucial first step in fine-tuning an LLM for specialised tasks like cricket commentary analysis. By leveraging powerful models like GPT-4 and tools like Pydantic, we can efficiently transform unstructured text into valuable, structured data.</p><p>This process opens up exciting possibilities for cricket analysis, from real-time match statistics to in-depth player performance studies. As we move forward with fine-tuning and validation, we’re not just creating a model; we’re building a bridge between the art of commentary and the science of data analysis.</p><p>What other sports or domains could benefit from similar fine-tuning approaches? How might this technology change the way we experience and analyse cricket matches? The possibilities are as boundless as a cricket field on a sunny day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e653ea9a19b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing LLMs for Automated Timeline Generation]]></title>
            <link>https://medium.com/@manaranjanp/harnessing-llms-for-automated-timeline-generation-a3e917cc73d3?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e917cc73d3</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fasthtml]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[anthropics]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 09:26:03 GMT</pubDate>
            <atom:updated>2024-08-28T09:26:03.749Z</atom:updated>
            <content:encoded><![CDATA[<p>In our data-driven world, the ability to quickly synthesize and visualize historical information is invaluable. This blog post explores how we can leverage Large Language Models (LLMs) to automatically generate timelines from Wikipedia content, focusing on the core functionality using Python, Pydantic, LangChain, and OpenAI’s GPT models.</p><h3>The Power of Timelines</h3><p>Imagine a journalist named Pawan working on a comprehensive article about the history of space exploration. With deadlines looming, Naveen Pawan to quickly grasp the key events and milestones spanning decades. Enter our LLM-powered timeline generator. Within minutes, Pawan inputs “space exploration” and receives a chronological list of pivotal moments — from Sputnik 1’s launch to the latest Mars rover landing. This timeline not only saves Pawan hours of research but also provides a structured foundation for the article, ensuring no critical events are overlooked.</p><p>This scenario illustrates how automated timeline generation can transform raw data into structured, chronological narratives, enhancing research efficiency and comprehension. Now, let’s dive into the implementation of this powerful tool, with a focus on the key libraries and detailed code explanations.</p><h3>AI tool to create a timeline</h3><p>The tools enables the user to select the LLM of his or her choice and creates a timeline dashboard for a given topic. The topic name and number of events to create the timeline can also be input by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9xI6WKbqdXdiB0gl5RrCQ.png" /></figure><p>The tools is available <a href="https://huggingface.co/spaces/Manaranjan/llmtimeline">here</a>. Please experiment with the tool.</p><h3>Key Libraries Overview</h3><p>Before we delve into the implementation, let’s briefly overview two crucial libraries we’ll be using:</p><h3>Pydantic</h3><p>Pydantic is a data validation and settings management library using Python type annotations. It enforces type hints at runtime, providing clear and informative error messages when data is invalid. Pydantic models are declarative, making them intuitive to define and use. The library seamlessly integrates with many Python frameworks and can automatically generate JSON schemas. In our project, Pydantic is vital for defining structured data models for our timeline events, ensuring that the data extracted by the LLM adheres to our specified format and types.</p><h3>LangChain</h3><p>LangChain is a framework for developing applications powered by language models. It provides a standardized interface for chains, a generic way to combine multiple components like prompts, language models, and other chains. LangChain facilitates prompt management, chat history handling, and seamless integration with various LLM providers. It also offers tools for working with different data sources and memory types. In our timeline generator, LangChain is crucial for creating a structured prompt, managing the interaction with the LLM, and parsing the output into our defined Pydantic models.</p><h3>Implementing Timeline Generation: A Step-by-Step Guide</h3><p>Now, let’s break down the implementation into detailed steps, providing in-depth explanations of each code snippet.</p><h3>Step 1: Setting Up the Environment</h3><p>First, let’s import the necessary libraries:</p><pre>import os<br>import pandas as pd<br>import traceback<br>from datetime import datetime<br>from typing import Literal<br>from pydantic import BaseModel, Field<br>from fasthtml.common import * <br>from langchain_core.prompts import PromptTemplate<br>from langchain.output_parsers import PydanticOutputParser<br>from langchain_openai import ChatOpenAI<br>from langchain_anthropic import ChatAnthropic<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain_community.utilities.wikipedia import WikipediaAPIWrapper<br>from langchain_community.tools.wikipedia.tool import WikipediaQueryRun</pre><p>Let’s break down these imports:</p><ul><li>os and json: Standard Python libraries for operating system interactions and JSON handling.</li><li>pandas: A powerful data manipulation library, used here for creating and managing our timeline dataframe.</li><li>datetime: For handling date and time objects in our events.</li><li>typing: Provides support for type hints, which we’ll use in our Pydantic models.</li><li>pydantic: For defining our data models with built-in validation.</li><li>langchain_core.prompts: Allows us to create structured prompts for our LLM.</li><li>langchain.output_parsers: Helps in parsing the LLM output into our defined Pydantic models.</li><li>langchain_openai, langchain_google_genai, and langchain_anthropic: Interfaces for OpenAI, Google and Anthropic LLMs.</li><li>langchain_community.utilities.wikipedia: Provides tools for fetching content from Wikipedia.</li></ul><h3>Step 2: Defining Data Models with Pydantic</h3><p>Now, let’s create our data models using Pydantic:</p><pre>class Event(BaseModel):<br>    time: datetime = Field(description=&quot;When the event occurred&quot;)<br>    description: str = Field(description=&quot;A summary of what happened. Not more than 20 words.&quot;)<br>    sentiment: Literal[&quot;Positive&quot;, &quot;Negative&quot;] = Field(..., description=&quot;Categorization of the event sentiment&quot;)<br><br>class EventResponse(BaseModel):<br>    events: List[Event] = Field(max_length=20, description=&quot;List of events extracted from the context&quot;)</pre><p>Let’s break this down:</p><ul><li>Event class:</li><li>time: A datetime field representing when the event occurred.</li><li>description: A string field for a brief summary of the event, limited to 20 words.</li><li>sentiment: A Literal field that can only be “Positive” or “Negative”, representing the event’s sentiment.</li><li>EventResponse class:</li><li>events: A list of Event objects, with a maximum of 20 events.</li></ul><p>The Field function is used to provide additional metadata and validation rules for each field. This structure ensures that our LLM output will conform to this specific format, making it easier to process and analyze the timeline data.</p><h3>Step 3: Setting Up the LLM Chain</h3><p>Now, let’s set up our LangChain components:</p><pre>parser = PydanticOutputParser(pydantic_object=EventResponse)<br><br>event_extraction_template = &quot;&quot;&quot;<br>Extract the time based informations or events from the context and return a list of events with time,  event description and event sentiment type whether it was positive or negative event.<br>The context may contain information about people, organization or any other entity. <br>&lt;context&gt;<br>{context}<br>&lt;/context&gt;<br>The response must follow the following schema strictly. There will be penalty for not following the schema.<br>&lt;schema&gt;<br>{format_instructions}<br>&lt;/schema&gt;<br>Must ensure the event belongs to the topic {topic} and try to get at least {numevents} unique events possible from the context.<br>Output:<br>&quot;&quot;&quot;<br>event_prompt = PromptTemplate(<br>    input_variables=[&quot;context&quot;],<br>    partial_variables={&quot;format_instructions&quot;: parser.get_format_instructions()},<br>    template=event_extraction_template<br>)</pre><p>Here’s what’s happening:</p><ol><li>We create a PydanticOutputParser that will parse the LLM’s output into our EventResponse model.</li><li>We define an event_extraction_template. This is a crucial part of our implementation as it instructs the LLM on how to process the input and format the output. Let’s break it down:</li></ol><ul><li>It asks the LLM to extract time-based information from the given context.</li><li>It specifies that the events should include time, description, and sentiment.</li><li>It emphasizes the need for a detailed and unique list of events.</li><li>It includes placeholders for the context ({context}) and format instructions ({format_instructions}).</li><li>It emphasizes the need for a detailed and unique list of events.</li><li>It includes placeholders for the context ({context}) and format instructions ({format_instructions}).</li></ul><p>We create a PromptTemplate using this template. The input_variables specify what will be passed to the prompt (in this case, the context), and partial_variables includes the format_instructions from our parser.</p><p>This setup ensures that our LLM will receive clear instructions on how to process the input and format the output according to our Pydantic model.</p><h3>Step 4: Configuring the Language Model</h3><p>Next, we’ll create a function to set up either OpenAI’s , Anthropic’s or Google’s Gemini language model based on user preference:</p><pre>def getModel(model, key):<br>    if(model == &#39;OpenAI Gpt-o&#39;):<br>        os.environ[&#39;OPENAI_API_KEY&#39;] = key<br>        return ChatOpenAI(temperature=0,  # Set to 0 for deterministic output<br>                    model=&quot;gpt-4o-2024-08-06&quot;,  # Using the GPT-4 Turbo model<br>                    max_tokens=8000)  # Limit the response length<br>    elif (model == &#39;Anthropic Claude&#39;):<br>        os.environ[&#39;ANTHROPIC_API_KEY&#39;] = key<br>        return ChatAnthropic(model=&#39;claude-3-5-sonnet-20240620&#39;)  # Limit the response length<br>    else:<br>        os.environ[&#39;GOOGLE_API_KEY&#39;] = key<br>        return ChatGoogleGenerativeAI(<br>            model=&quot;gemini-1.5-pro&quot;,<br>            temperature=0,<br>            max_tokens=8000,<br>            max_retries=2,<br>        )</pre><p>This function does the following:</p><ol><li>It takes two parameters: model (to choose between OpenAI and Anthropic) and key (the API key).</li><li>Depending on the chosen model:</li></ol><ul><li>For OpenAI, it sets the API key in the environment variables and returns a ChatOpenAI instance.</li><li>temperature=0 ensures deterministic output.</li><li>We’re using the “gpt-4–1106-preview” model, which is GPT-4 Turbo.</li><li>max_tokens=4000 limits the response length.</li><li>For Anthropic, it sets the API key and returns a ChatAnthropic instance using the Claude 3 Opus model.</li></ul><p>This setup allows flexibility in choosing the LLM provider while encapsulating the configuration details.</p><h3>Step 5: Fetching Wikipedia Content</h3><p>For fetching Wikipedia content, we’ll use the WikipediaQueryRun tool:</p><pre>wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())<br>wiki_content = wikipedia.run(topic)</pre><p>This code:</p><ol><li>Creates a WikipediaQueryRun instance, which is a tool for querying Wikipedia.</li><li>Uses the run method to fetch content for a given topic.</li></ol><p>This abstraction simplifies the process of retrieving relevant information from Wikipedia, providing our LLM with rich context for timeline generation.</p><h3>Step 6: Generating the Timeline</h3><p>Now, let’s create the core function that orchestrates the timeline generation process:</p><pre>def generate_timeline(topic, llm):<br>    <br>    try:    <br>        wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())<br>        wiki_content = wikipedia.run(topic)<br>    <br>        chain = event_prompt | llm | parser<br>        result = chain.invoke({&quot;context&quot; : wiki_content, <br>                               &quot;topic&quot;: topic, <br>                               &quot;numevents&quot;: numevents})<br>    <br>        df = pd.DataFrame([event.dict() for event in result.events])<br>        df = df.sort_values(&quot;time&quot;, ascending=True).reset_index(drop=True)<br>        <br>        # Save to CSV<br>        df.to_csv(f&quot;{topic.replace(&#39; &#39;, &#39;_&#39;)}_timeline.csv&quot;, index=False)<br>        print(f&quot;Timeline saved to &#39;{topic.replace(&#39; &#39;, &#39;_&#39;)}_timeline.csv&#39;&quot;)<br>        <br>        return df<br>    except Exception as e:<br>        print(f&quot;Error parsing LLM output: {str(e)}&quot;)<br>        return None</pre><p>Let’s break down this function:</p><ol><li>It takes two parameters: topic (the subject for the timeline) and llm (the configured language model).</li><li>It fetches Wikipedia content for the given topic using WikipediaQueryRun.</li><li>It creates an LLMChain using the provided LLM and our predefined prompt.</li><li>It runs the chain with the Wikipedia content as context, which:</li></ol><ul><li>Sends the content to the LLM with our structured prompt.</li><li>Receives the LLM’s response, which should be a list of events.</li></ul><p>In the try block:</p><ul><li>It parses the LLM’s output using our Pydantic parser.</li><li>Converts the parsed events into a pandas DataFrame.</li><li>Sorts the events chronologically and resets the index.</li><li>Adds a formatted date string column (‘TimeStr’).</li><li>Saves the timeline to a CSV file, naming it based on the topic.</li><li>Returns the DataFrame for further use.</li></ul><p>If any error occurs during parsing or processing, it’s caught in the except block, printed, and the function returns None.</p><p>This function encapsulates the entire process of timeline generation, from fetching data to processing the LLM output and saving the results.</p><h3>Step 7: Using the Timeline Generator</h3><p>Finally, here’s how we can use our timeline generator:</p><pre># Example usage<br>topic = &quot;Space Exploration&quot;<br>llm = getModel(&#39;OpenAI&#39;, &#39;your-api-key-here&#39;)<br>timeline_df = generate_timeline(topic, llm)<br><br>if timeline_df is not None:<br>    print(timeline_df.head())<br>else:<br>    print(&quot;Failed to generate timeline.&quot;)</pre><p>This code snippet demonstrates the usage of our timeline generator:</p><ol><li>We define the topic (“Space Exploration” in this case).</li><li>We get an instance of the LLM using our getModel function, specifying OpenAI as the provider and passing the API key.</li><li>We call generate_timeline with our topic and LLM.</li><li>If successful, we print the first few rows of the resulting DataFrame.</li><li>If there was an error, we print a failure message.</li></ol><p>This simple interface allows users to easily generate timelines for any topic of interest, leveraging the power of LLMs and Wikipedia data.</p><h3>The Video Blog</h3><p>Below video that takes you through the tool and the code walkthrough.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnMgNW8rJqrQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnMgNW8rJqrQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnMgNW8rJqrQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8205cd59d1feaf322f64bf7b38690b9b/href">https://medium.com/media/8205cd59d1feaf322f64bf7b38690b9b/href</a></iframe><h3>Conclusion</h3><p>By leveraging the power of LLMs, Wikipedia, and Python libraries like Pydantic and LangChain, we’ve created a robust tool for generating timelines on any given topic. This approach demonstrates the potential of AI in research and data synthesis, offering a powerful way to quickly organize and understand historical information.</p><p>Whether you’re a journalist like Pawan, a researcher, or a data enthusiast, this tool opens up new possibilities for exploring and understanding chronological data. As LLMs continue to evolve, the potential for even more sophisticated timeline generation and analysis tools is immense. This implementation serves as a starting point, inviting further enhancements such as improved event extraction, sentiment analysis refinement, or integration with visualization libraries for creating interactive timelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e917cc73d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing AI for Intelligent Q&A Generation: A Deep Dive into CrewAI]]></title>
            <link>https://medium.com/@manaranjanp/harnessing-ai-for-intelligent-q-a-generation-a-deep-dive-into-crewai-97540e7e4f3f?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/97540e7e4f3f</guid>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[fasthtml]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 09:07:19 GMT</pubDate>
            <atom:updated>2024-08-28T09:12:29.342Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-paced world, where information overload is a constant challenge, the ability to quickly extract key insights from lengthy documents is invaluable. Imagine a tool that could read through complex case studies, dense reports, or extensive articles, and not only generate relevant questions but also provide accurate answers and even evaluate the quality of those Q&amp;A pairs. This is exactly what our innovative AI-powered Q&amp;A generation system, built using the CrewAI framework, accomplishes.</p><h3>The Power of AI-Driven Q&amp;A Generation: A Short Story</h3><p>Meet Purvi, a busy management consultant tasked with analyzing a 100-page report on emerging market trends. Traditionally, this would require hours of careful reading and note-taking. But with our AI-powered Q&amp;A generation tool, Purvi’s workflow is transformed.</p><p>She feeds the report into the system, which quickly generates a set of insightful questions covering various aspects like key facts, SWOT analysis, critical decisions, and ethical considerations. Not only does it provide these questions, but it also produces comprehensive answers and even grades the quality of each Q&amp;A pair.</p><p>In a matter of minutes, Purvi has a well-organized summary of the report’s key points, complete with thought-provoking questions and detailed answers. This allows her to quickly grasp the essence of the report and focus her energy on strategic analysis rather than information gathering.</p><h3>Q&amp;A Generation tool</h3><p>Here is a simple summarization <a href="https://huggingface.co/spaces/Manaranjan/llmqaagent">tool</a> that an help quickly summarize the documents, given the topics of summarization. It automatically creates the sections and summarizes information in each section and also provide extended information for each summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZr9O8kIZuUZu-Iz3CKGlg.png" /></figure><p>Now, let’s dive into how this powerful tool is implemented using CrewAI Agent Framework.</p><h3>Understanding LLM Agents</h3><p>Large Language Model (LLM) agents are AI-powered entities that leverage the capabilities of advanced language models to perform specific tasks. These agents are designed to understand and generate human-like text, making them ideal for a wide range of applications, from content creation to complex problem-solving.</p><p>LLM agents work by processing input text, understanding the context and requirements, and generating appropriate responses or actions. They can be fine-tuned or prompted to specialize in particular domains or tasks, allowing them to leverage their broad knowledge base for specific applications.</p><p>Key features of LLM agents include:</p><ol><li>Natural language understanding and generation</li><li>Contextual awareness</li><li>Task-specific specialization through fine-tuning or prompting</li><li>Ability to process and synthesize large amounts of information</li><li>Adaptability to various domains and applications</li></ol><p>In our Q&amp;A generation system, LLM agents play crucial roles as question generators, answer providers, and quality evaluators, each leveraging the power of language models to perform their specialized tasks.</p><h3>Introduction to the CrewAI Framework</h3><p>CrewAI is an innovative framework designed to orchestrate multiple AI agents to work together on complex tasks. It provides a structured approach to creating, managing, and executing workflows that involve multiple specialized AI agents.</p><p>Key features of CrewAI include:</p><ol><li>Agent Definition: Easily create specialized agents with defined roles, goals, and backstories.</li><li>Task Management: Define and manage tasks for each agent, including input requirements and expected outputs.</li><li>Workflow Orchestration: Coordinate the execution of tasks across multiple agents in a specified order.</li><li>Flexible Integration: Seamlessly integrate with various LLM providers and tools.</li><li>Output Handling: Manage and process the outputs from each agent and task.</li></ol><p>In our Q&amp;A generation system, CrewAI allows us to create a team of specialised agents (QuestionGenerator, AnswerGenerator, and Grader) and orchestrate their tasks to work together seamlessly. This enables us to break down the complex process of Q&amp;A generation and evaluation into manageable, specialized steps, each handled by an expert agent.</p><p>By leveraging CrewAI, we can create more sophisticated and effective AI systems that can tackle complex, multi-step problems in a structured and efficient manner.</p><h3>Implementing Q&amp;A Agents with CrewAI: A Step-by-Step Guide</h3><p>Our Q&amp;A generation system is built using the CrewAI framework, which allows us to create a team of specialized AI agents working together to accomplish complex tasks. Let’s break down the implementation into steps and examine the key code snippets in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WozwD8ksT1iOG1PHD26kA.png" /></figure><h3>Step 1: Setting Up the Environment</h3><p>First, we import the necessary libraries and set up logging:</p><pre>import os<br>import sys<br>import json<br>import PyPDF2<br>import pandas as pd<br>import logging<br>import configparser<br>from typing import List<br>from pydantic import BaseModel, Field, ValidationError<br>from crewai import Agent, Task, Crew, Process<br>from langchain_openai import ChatOpenAI</pre><p>This setup is crucial for our project:</p><ul><li>os and sys are used for system operations and command-line argument handling.</li><li>json is used for JSON data processing.</li><li>PyPDF2 allows us to read PDF files.</li><li>pandas is used for data manipulation and CSV file creation.</li><li>logging helps us track the execution of our script.</li><li>configparser is used to read configuration files.</li><li>pydantic is used for data validation and settings management.</li><li>crewai is the core framework we’re using for our AI agents.</li><li>langchain_openai provides an interface to OpenAI’s language models.</li></ul><h3>Step 2: Defining Data Models</h3><p>We use Pydantic to define our data models, ensuring type safety and easy serialization:</p><pre>class Question(BaseModel):<br>    context: str<br>    text: str<br>    question_type: str = Field(description=&quot;One of the question types mentioned in the instruction.&quot;)<br><br>class Answer(BaseModel):<br>    text: str<br>class QAPair(BaseModel):<br>    question: Question<br>    answer: Answer<br>class GradedQAPair(BaseModel):<br>    question: Question<br>    answer: Answer<br>    rating: int = Field(..., ge=1, le=5)<br>    explanation: str <br>class QuestionList(BaseModel):<br>    questions: List[Question]<br>class QAPairList(BaseModel):<br>    qa_pairs: List[QAPair]<br>class GradedQAPairList(BaseModel):<br>    graded_qa_pairs: List[GradedQAPair]</pre><p>These Pydantic models are crucial for our data structure:</p><ul><li>Question includes the context, the question text, and the question type.</li><li>Answer simply contains the answer text.</li><li>QAPair combines a question and its corresponding answer.</li><li>GradedQAPair extends QAPair with a rating (1-5) and an explanation for the grade.</li><li>QuestionList, QAPairList, and GradedQAPairList are used to manage lists of these objects.</li></ul><p>Using Pydantic models allows us to easily validate our data structure and catch any inconsistencies early in the process.</p><h3>Step 3: Creating Specialized Agents</h3><p>We define three specialized agents using the CrewAI framework:</p><pre>class QuestionGenerator(Agent):<br>    def __init__(self, llm):<br>        super().__init__(<br>            role=&quot;Question Generator&quot;,<br>            goal=&quot;Generate relevant questions based on the case study text&quot;,<br>            backstory=&quot;You are an expert in creating insightful questions from management case studies. You specialize in creating diverse types of questions.&quot;,<br>            llm=llm,<br>            verbose=True<br>        )<br><br>class AnswerGenerator(Agent):<br>    def __init__(self, llm):<br>        super().__init__(<br>            role=&quot;Answer Generator&quot;,<br>            goal=&quot;Provide accurate answers to questions using the given context&quot;,<br>            backstory=&quot;You are a knowledgeable expert in management studies, capable of answering complex questions based on case study information. You ensure your answers are comprehensive and directly relevant to the questions asked.&quot;,<br>            llm=llm,<br>            verbose=True<br>        )<br><br>class Grader(Agent):<br>    def __init__(self, llm):<br>        super().__init__(<br>            role=&quot;Grader&quot;,<br>            goal=&quot;Validate and rate question-answer pairs for quality, completeness, and relevance&quot;,<br>            backstory=&quot;You are an experienced evaluator of management case study analyses. You have a keen eye for detail and can effectively assess the quality, completeness, and relevance of questions and answers in the context of management studies.&quot;,<br>            llm=llm,<br>            verbose=True<br>        )</pre><p>Each agent is a specialized AI entity with a specific role:</p><ul><li>The QuestionGenerator creates insightful questions based on the input text.</li><li>The AnswerGenerator provides comprehensive answers to these questions.</li><li>The Grader evaluates the quality of the question-answer pairs.</li></ul><p>By giving each agent a specific role, goal, and backstory, we’re leveraging the power of role-playing in AI to get more focused and relevant outputs.</p><h3>Step 4: Defining Tasks for Each Agent</h3><p>For each agent, we define a corresponding task:</p><pre>class QuestionGenerationTask(Task):<br>    def __init__(self, agent: QuestionGenerator):<br>        super().__init__(<br>            description=&quot;&quot;&quot;<br>            Generate a set of {num_questions} relevant questions from the given case study text given in the context.  <br>            Ensure each question is clear, focused, and promotes deep understanding of the case.<br>            The question can be based on any of the following topics: {instructions}<br>            Case study text: <br>            &lt;context&gt;<br>            {text_chunk}<br>            &lt;/context&gt;<br>            &quot;&quot;&quot;,<br>            agent=agent,<br>            output_pydantic=QuestionList,<br>            expected_output=f&quot;A list of Question objects&quot;<br>        )<br>class AnswerGenerationTask(Task):<br>    def __init__(self, agent: AnswerGenerator, task: QuestionGenerationTask):<br>        super().__init__(<br>            description=&quot;&quot;&quot;<br>            Produce accurate and comprehensive answers for the generated questions using the given context. <br>            Use both the original text and the specific questions provided.<br>            Ensure each answer is:<br>            - Directly relevant to the question asked<br>            - Based on information from the case study<br>            - Clear and well-structured<br>            - Give elaborate answers with detailed context and descriptions<br>            - Not more than 500 words<br>            &quot;&quot;&quot;,<br>            context = [task],<br>            agent=agent,<br>            output_pydantic=QAPairList,<br>            expected_output=f&quot;A list of Question Answer Pair objects&quot;<br>        )<br>class GradingTask(Task):<br>    def __init__(self, agent: Grader, task: AnswerGenerationTask):<br>        super().__init__(<br>            description=&quot;&quot;&quot;<br>            Evaluate and rate each question-answer pair on a scale of 1 to 5 for based on overall quality, completeness, and relevance based on the context given.<br>            Provide a brief explanation for each rating.<br>            &quot;&quot;&quot;,<br>            context = [task],<br>            agent=agent,<br>            output_pydantic=GradedQAPairList,<br>            expected_output=f&quot;A list of GradedQAPair&quot;<br>        )</pre><p>Each task is carefully defined with specific instructions:</p><ul><li>QuestionGenerationTask provides detailed guidelines on how to generate questions, including the types of questions to be created.</li><li>AnswerGenerationTask outlines the criteria for good answers, ensuring they are relevant, comprehensive, and well-structured.</li><li>GradingTask provides instructions on how to evaluate and rate the Q&amp;A pairs.</li></ul><p>The context parameter in AnswerGenerationTask and GradingTask allows these tasks to access the output of previous tasks, creating a chain of dependencies.</p><h3>Step 5: Creating the CrewManager</h3><p>The CrewManager orchestrates the entire process:</p><pre>class CrewManager:<br>  def __init__(self, llm):<br>      self.question_generator = QuestionGenerator(llm)<br>      self.answer_generator = AnswerGenerator(llm)<br>      self.grader = Grader(llm)<br>      self.question_task = QuestionGenerationTask(self.question_generator)<br>      self.answer_task = AnswerGenerationTask(self.answer_generator, self.question_task)<br>      self.grading_task = GradingTask(self.grader, self.answer_task)<br><br>      self.crew = Crew(<br>          agents=[self.question_generator, self.answer_generator, self.grader],<br>          tasks=[self.question_task, self.answer_task, self.grading_task],<br>          process=Process.sequential<br>      )</pre><p>The CrewManager is the central orchestrator of our system:</p><ul><li>It initialises all the agents and tasks.</li><li>It creates a Crew object, which manages the execution of tasks by the agents.</li><li>The Process.sequential parameter ensures that tasks are executed in order, with each task using the output of the previous task as input.</li></ul><h3>Step 6: Executing the Q&amp;A Generation Process</h3><p>In the main execution block, we set up the CrewManager and run the process:</p><pre>if __name__ == &quot;__main__&quot;:<br>    # Check command-line arguments<br>    if len(sys.argv) &lt; 3:<br>        print(&quot;Please provide a PDF filename and number of questions as arguments.&quot;)<br>        sys.exit(1)<br># Get input parameters<br>    pdf_filename = sys.argv[1]<br>    sample_text = read_pdf(pdf_filename)<br>    num_questions = sys.argv[2]<br>    # Read configuration and set up OpenAI API<br>    config = configparser.ConfigParser()<br>    config.read(&#39;agent.ini&#39;)<br>    os.environ[&quot;OPENAI_API_KEY&quot;] = config[&#39;OpenAI&#39;][&#39;API_KEY&#39;]<br>    # Initialize language model<br>    llm = ChatOpenAI(temperature=0, model=&quot;gpt-4o&quot;, max_tokens=1000)<br>    # Create and run CrewManager<br>    crew_manager = CrewManager(llm)<br>    result = crew_manager.crew.kickoff(<br>                inputs={<br>                    &quot;num_questions&quot;: num_questions,<br>                    &quot;text_chunk&quot;: sample_text,<br>                    &quot;instructions&quot;: instructions<br>                }<br>            )<br>    # Process and save results<br>    if isinstance(result, GradedQAPairList):<br>        data = [<br>            {<br>                &#39;Question&#39;: graded_qa.question.text,<br>                &#39;Type&#39;: graded_qa.question.question_type,<br>                &#39;Answer&#39;: graded_qa.answer.text,<br>                &#39;Ratings&#39;: graded_qa.rating, <br>                &#39;Explanation&#39;: graded_qa.explanation<br>            } for graded_qa in result.graded_qa_pairs<br>        ]<br>        <br>        df = pd.DataFrame(data)<br>        df.to_csv(f&quot;{pdf_filename.split(&#39;.&#39;)[0]}.csv&quot;, index=True)<br>        print(f&quot;Results saved to {pdf_filename.split(&#39;.&#39;)[0]}.csv&quot;)<br>    else:<br>        print(f&quot;Unexpected result type: {type(result)}&quot;)<br>        print(result)</pre><p>This main execution block ties everything together:</p><ol><li>It checks for correct command-line arguments (PDF filename and number of questions).</li><li>It reads the PDF file and extracts the text.</li><li>It sets up the OpenAI API key from a configuration file.</li><li>It initialises the language model (in this case, GPT-4).</li><li>It creates a CrewManager and runs the Q&amp;A generation process.</li><li>Finally, it processes the results, converting them into a pandas DataFrame and saving them as a CSV file.</li></ol><h3>The Blog Video</h3><p>Here is also the video on how to use the tool, which also takes you through the code implementation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoJWG-zj--UU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoJWG-zj--UU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoJWG-zj--UU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/838bff6a5173f56fcc67fde3d58ab61a/href">https://medium.com/media/838bff6a5173f56fcc67fde3d58ab61a/href</a></iframe><h3>The Q&amp;A Generation Workflow</h3><p>Let’s break down how these components work together:</p><ol><li><strong>Question Generation</strong>: The QuestionGenerator agent reads the input text and generates a list of relevant questions based on the provided instructions.</li><li><strong>Answer Generation</strong>: The AnswerGenerator agent takes these questions and the original text, producing comprehensive answers for each question.</li><li><strong>Grading</strong>: The Grader agent evaluates each question-answer pair, assigning a quality rating and providing an explanation for the rating.</li><li><strong>Result Processing</strong>: The final output is a list of graded question-answer pairs, which is then formatted and saved as a CSV file for easy analysis.</li></ol><p>This workflow, as illustrated in the provided image, allows for a sophisticated, multi-step analysis of complex documents, leveraging the power of AI to extract and evaluate key information.</p><h3>Conclusion</h3><p>By harnessing the power of AI through the CrewAI framework, we’ve created a powerful tool for automated Q&amp;A generation and evaluation. This system can significantly streamline the process of analyzing lengthy documents, allowing professionals like Purvi to focus on high-level analysis and decision-making rather than getting bogged down in information extraction.</p><p>As AI continues to evolve, tools like this will become increasingly crucial in helping us navigate the vast seas of information we encounter daily. By automating the process of question generation, answering, and evaluation, we’re not just saving time — we’re enhancing our ability to derive meaningful insights from complex data sources.</p><p>The modular nature of this system, with its specialized agents and tasks, allows for easy expansion and customization. For instance, you could add new types of questions, implement more sophisticated grading criteria, or even integrate additional AI models for specific domain expertise.</p><p>As we continue to push the boundaries of AI-assisted information processing, tools like this Q&amp;A generation system will play a pivotal role in transforming how we interact with and derive value from complex information sources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97540e7e4f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Powered Document Summarization]]></title>
            <link>https://medium.com/@manaranjanp/ai-powered-document-summarization-02dda4e6681a?source=rss-ebd214554fa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/02dda4e6681a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fasthtml]]></category>
            <category><![CDATA[summarize]]></category>
            <dc:creator><![CDATA[Manaranjan Pradhan]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 08:50:51 GMT</pubDate>
            <atom:updated>2024-08-28T09:01:48.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Information Overload Dilemma</h3><p>These days, we’re always getting lots and lots of information thrown at us. It doesn’t matter if you’re a teacher getting ready for class, a business person looking at reports, or a researcher trying to keep up with new studies. Everyone has the same problem: How do you quickly find the important stuff in all that reading?</p><h3>Imagine this scenario:</h3><p>Rahul is a high school student who takes business classes. He has to read a really long case study for class. It’s important for him to understand it so he can follow the teacher’s lessons and join in class discussions. But he doesn’t have much time.</p><p>Now, Rahul has a new trick. He can use a smart computer tool that uses AI. He just uploads his long case study to this tool. In just a few minutes, the tool gives him a short, easy-to-read summary.</p><p>Before, Rahul would have spent hours reading every page carefully. Now, he gets the main ideas quickly. This saves him a lot of time. With all this extra time, Rahul can think about what he learned and be ready to talk about it in class.</p><p>This isn’t just a student’s fantasy — it’s the reality that cutting-edge AI technology is bringing to fruition. Let’s dive deep into the inner workings of this revolutionary tool and explore how it’s transforming the way we process and understand information.</p><h3>Summarization tool</h3><p>Here is a simple summarization <a href="https://huggingface.co/spaces/Manaranjan/llmsummary">tool</a> that an help quickly summarize the documents, given the topics of summarization. It automatically creates the sections and summarizes informatio in each section and also provide extended information for each summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1CFQP6mWR7mH0TlfteOFw.png" /></figure><h3>The Magic Behind the Curtain: How AI Summarization Works</h3><p>At its core, the document summarization system we’re exploring leverages the power of Large Language Models (LLMs) like OpenAI’s GPT-4 or Anthropic’s Claude. These sophisticated AI models have been trained on vast amounts of text data, enabling them to understand and generate human-like text with remarkable accuracy. But how does our specific implementation harness this power? Let’s break it down step by step.</p><h3>1. Setting the Stage: Environment and Dependencies</h3><p>The foundation of our summarization tool is built on a robust set of Python libraries and frameworks. Here’s a closer look at the key components:</p><pre>import io<br>import os<br>import traceback<br>from pydantic_core import from_json<br>from fasthtml.common import * <br>from PyPDF2 import PdfReader<br>from langchain.chains.summarize import load_summarize_chain<br>from langchain_core.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_anthropic import ChatAnthropic<br>from pydantic import BaseModel, Field, ValidationError<br>from langchain.output_parsers import PydanticOutputParse</pre><p>This setup combines several powerful tools:</p><ul><li>fasthtml for creating a responsive web interface</li><li>PyPDF2 for handling PDF file inputs</li><li>langchain for orchestrating the AI models and summarization process</li><li>pydantic for defining structured data models and validating outputs</li></ul><h3>2. Structuring the Summary: Pydantic Models</h3><p>One of the key innovations in this implementation is the use of Pydantic models to define a clear structure for the AI-generated summaries. This ensures consistency and allows for easy parsing and display of the results.</p><pre>class SummaryLine(BaseModel):<br>    summary_item: str = Field(description=&quot;Actual summary sentence that contains highlighting key data points or information.&quot;, <br>                              max_length=200)<br>    keywords: List[str] = Field(description=&quot;A list of exact words or phrases in the summary item that highlights most important data points or key ideas.&quot;)<br>    brief_descripton_of_summary: str = Field(description=&quot;This is elaborate description to provide context or background to the summary item.&quot;,<br>                                             min_length=200,                                             <br>                                             max_length=500)<br><br>class TopicSummaries(BaseModel):<br>    topic: str = Field(description=&quot;Topics of summary as mentioned in the instructions.&quot;)<br>    summaries: List[SummaryLine] = Field(description=&quot;This a list summary for a topic with each one having it&#39;s own keywords and context.&quot;,<br>                                         min_items=3, <br>                                         max_items=5)<br>class CompleteSummary(BaseModel):<br>    summaries_list: List[TopicSummaries]</pre><p>This structured approach allows us to:</p><ol><li>Clearly define what each part of the summary should contain</li><li>Set constraints on length and content</li><li>Ensure that the AI model’s output adheres to a consistent format</li></ol><h3>3. Guiding the AI: Crafting the Perfect Prompt</h3><p>The heart of effective AI summarization lies in providing clear, detailed instructions to the model. Our implementation uses a carefully crafted template:</p><pre>summarize_template = &quot;&quot;&quot;<br>Write a concise summary of the case study given in the context. The summary should be based on the following topics.<br>&quot;&quot;&quot;<br><br>summary_sections = &quot;&quot;&quot;<br>- Factual: Facts or information that contains numbers, dates, events etc. that are mostly quantitative or qualitative data<br>- SWOT: Key Strength, weakness, opportunities or threats that are mentioned in the case study<br>- Decisions and Outcomes: Key decisions taken and it&#39;s successful or failed outcomes and reasons<br>- Ethical and Governance: Key considerations from ethical and governance perspective<br>&quot;&quot;&quot;<br>context_str = &quot;&quot;&quot;<br>&lt;context&gt;<br>{context_content}<br>&lt;/context&gt;<br>The response must follow the following schema strictly. There will be penalty for not following the schema.<br>&quot;&quot;&quot;</pre><p>This template does several crucial things:</p><ol><li>It specifies the overall task (summarizing a case study)</li><li>It outlines specific topics to be covered, ensuring a comprehensive summary</li><li>It provides a structure for the AI to follow, improving consistency and readability</li></ol><p>This is how the actually format instruction looks like</p><pre>{<br>  &quot;$defs&quot;: {<br>    &quot;SummaryLine&quot;: {<br>      &quot;properties&quot;: {<br>        &quot;summary_item&quot;: {<br>          &quot;description&quot;: &quot;Actual summary sentence that contains highlighting key data points or information.&quot;,<br>          &quot;maxLength&quot;: 200,<br>          &quot;title&quot;: &quot;Summary Item&quot;,<br>          &quot;type&quot;: &quot;string&quot;<br>        },<br>        &quot;keywords&quot;: {<br>          &quot;description&quot;: &quot;A list of exact words or phrases in the summary item that highlights most important data points or key ideas.&quot;,<br>          &quot;items&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>          },<br>          &quot;title&quot;: &quot;Keywords&quot;,<br>          &quot;type&quot;: &quot;array&quot;<br>        },<br>        &quot;brief_descripton_of_summary&quot;: {<br>          &quot;description&quot;: &quot;This is elaborate description to provide context or background to the summary item.&quot;,<br>          &quot;maxLength&quot;: 500,<br>          &quot;minLength&quot;: 200,<br>          &quot;title&quot;: &quot;Brief Descripton Of Summary&quot;,<br>          &quot;type&quot;: &quot;string&quot;<br>        }<br>      },<br>      &quot;required&quot;: [<br>        &quot;summary_item&quot;,<br>        &quot;keywords&quot;,<br>        &quot;brief_descripton_of_summary&quot;<br>      ],<br>      &quot;title&quot;: &quot;SummaryLine&quot;,<br>      &quot;type&quot;: &quot;object&quot;<br>    },<br>    &quot;TopicSummaries&quot;: {<br>      &quot;properties&quot;: {<br>        &quot;topic&quot;: {<br>          &quot;description&quot;: &quot;Topics of summary as mentioned in the instructions.&quot;,<br>          &quot;title&quot;: &quot;Topic&quot;,<br>          &quot;type&quot;: &quot;string&quot;<br>        },<br>        &quot;summaries&quot;: {<br>          &quot;description&quot;: &quot;This a list summary for a topic with each one having it&#39;s own keywords and context.&quot;,<br>          &quot;items&quot;: {<br>            &quot;$ref&quot;: &quot;#/$defs/SummaryLine&quot;<br>          },<br>          &quot;maxItems&quot;: 5,<br>          &quot;minItems&quot;: 3,<br>          &quot;title&quot;: &quot;Summaries&quot;,<br>          &quot;type&quot;: &quot;array&quot;<br>        }<br>      },<br>      &quot;required&quot;: [<br>        &quot;topic&quot;,<br>        &quot;summaries&quot;<br>      ],<br>      &quot;title&quot;: &quot;TopicSummaries&quot;,<br>      &quot;type&quot;: &quot;object&quot;<br>    }<br>  },<br>  &quot;properties&quot;: {<br>    &quot;summaries_list&quot;: {<br>      &quot;items&quot;: {<br>        &quot;$ref&quot;: &quot;#/$defs/TopicSummaries&quot;<br>      },<br>      &quot;title&quot;: &quot;Summaries List&quot;,<br>      &quot;type&quot;: &quot;array&quot;<br>    }<br>  },<br>  &quot;required&quot;: [<br>    &quot;summaries_list&quot;<br>  ]<br>}</pre><h3>4. The Summarization Engine: Bringing It All Together</h3><p>The onepass_summarize function is where all these components come together to produce the final summary:</p><pre>def onepass_summarize(pages, summary_sections, model):<br>    # This function performs a one-pass summarization of the given pages<br>    # It takes three parameters:<br>    # - pages: The text content to be summarized<br>    # - summary_sections: Instructions on what sections to include in the summary<br>    # - model: The AI model to use for summarization (e.g., GPT-4, Claude)<br><br># Combine different parts of the template to create a comprehensive instruction set for the AI<br>    onepass_summary_template = summarize_template + summary_sections + context_str + &quot;{format_instructions}&quot;<br>    # summarize_template: General instructions for summarization<br>    # summary_sections: Specific sections to include in the summary<br>    # context_str: Placeholder for the actual content to be summarized<br>    # {format_instructions}: Will be replaced with instructions on how to format the output<br>    # Create a parser that will ensure the AI&#39;s output matches our predefined structure<br>    output_parser = PydanticOutputParser(pydantic_object=CompleteSummary)<br>    # CompleteSummary is a Pydantic model that defines the expected structure of the summary<br>    # Get formatting instructions from the parser<br>    # These instructions tell the AI how to structure its output<br>    format_instructions = output_parser.get_format_instructions()<br>    # Create a prompt template using our combined instruction set<br>    prompt = PromptTemplate.from_template(onepass_summary_template)<br>    # This template will be filled with the actual content to summarize<br>    # Create a &quot;chain&quot; that processes the input through several steps:<br>    # 1. Fill the prompt template with content<br>    # 2. Send to the AI model for processing<br>    # 3. Parse the output to ensure it matches our expected structure<br>    summary_chain = prompt | model | output_parser<br>    # Invoke the chain with our content and format instructions<br>    summaries = summary_chain.invoke({<br>        &quot;context_content&quot;: pages,  # The actual text to summarize<br>        &quot;format_instructions&quot;: format_instructions  # How to format the output<br>    })<br>    # Return the structured summaries<br>    return summaries</pre><p>This function:</p><ol><li>Combines the various template components into a single, comprehensive instruction set</li><li>Sets up a parser to ensure the output matches our predefined structure</li><li>Creates a “chain” that processes the input through the AI model and formats the output</li><li>Invokes this chain with the document content and awaits the structured summary</li></ol><h3>5. User Interface using fastHtml</h3><p>The summary <a href="https://huggingface.co/spaces/Manaranjan/llmsummary">tool</a> is created using a new framework called <a href="https://www.fastht.ml/">fastHtml</a> developed by [Jeremy Howard] (https://www.linkedin.com/in/howardjeremy/) and his [team] (https://www.answer.ai/). I loved his deep learning course on <a href="https://www.fast.ai/">fast.ai</a> and a big fan of his teachigs.</p><p>I wanted to give the web framework a try as it empowers you to create web applications completely Python without any knowldge of css and javascript or any other web framework.</p><p>Here is also the video on how to use the tool, which also takes you through the code implementation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeV9sEBng9so&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeV9sEBng9so&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FeV9sEBng9so%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d9f03fed8d572ef83cacf4e7a0ad23d/href">https://medium.com/media/7d9f03fed8d572ef83cacf4e7a0ad23d/href</a></iframe><h3>Beyond the Classroom: Real-World Applications</h3><p>The applications of this AI-powered summarization tool extend far beyond of education, for example:</p><ol><li><strong>Business Intelligence</strong>: Executives can quickly digest lengthy market reports, competitor analyses, and financial statements, allowing for faster, more informed decision-making.</li><li><strong>Legal Research</strong>: Lawyers can efficiently review case law and legal documents, extracting key precedents and arguments in a fraction of the time.</li><li><strong>Academic Research</strong>: Scholars can stay up-to-date with the latest publications in their field, quickly grasping the main contributions of new papers.</li><li><strong>Journalism</strong>: Reporters can rapidly process large volumes of information from various sources, helping them to identify key story angles and fact-check efficiently.</li></ol><h3>The Future of Information Processing and Consumption</h3><p>We’re entering a new time where there’s more information than ever before. Tools like this AI helper that can quickly sum up long documents aren’t just nice to have — we really need them now. There’s so much to read and learn these days, and being able to understand it all quickly can make a big difference in how well we do at work and in life.</p><p>So the next time you have too many things to read and feel overwhelmed, remember this: AI can be your helper. With just one click, it can make things clearer and easier to understand. This new way of dealing with lots of information is here now, and it’s going to keep getting better and better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02dda4e6681a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>