AI Engineering Full Course | 8+ Hours  | LLMs, RAG, LangChain, LangGraph, AI Agents

AI Engineering Full Course | 8+ Hours | LLMs, RAG, LangChain, LangGraph, AI Agents

Introduction to the AI Engineering Course

Overview of the Course

  • The course aims to teach essential AI engineering concepts through a project-oriented approach, focusing on practical applications.
  • Participants will build 10 real-world projects, covering tools and concepts such as LLMs, vector databases, and embedding models.
  • Prerequisite knowledge required is basic Python programming skills.

Project Breakdown

Project Descriptions

  • The first project involves creating a chatbot from scratch with features like memory and token streaming for cost efficiency.
  • In the second project, participants will implement sentiment analysis to classify customer feedback without using NLM but rather natural language inference (NLI).
  • The third project focuses on embeddings, which are crucial for building semantic search systems.

Advanced Projects

Further Project Insights

  • Project four introduces retrieval augmented generation (RAG), an important skill in AI engineering.
  • In project five, an AI agent will be developed that can utilize various tools autonomously.
  • Project six explores prompt templates and structured outputs to manage model responses effectively.

Memory Management and Middleware

Enhancing User Interaction

  • The seventh project enhances memory management by allowing users to save conversations in a database for future reference.
  • In project eight, middleware will be implemented to give users control over AI actions requiring permission.

Setting Up the Development Environment

Initial Setup Instructions

  • This session covers setting up a Python environment necessary for developing projects using Visual Studio Code (VS Code).
  • Users need to install VS Code from its official site and ensure they have the correct version of Python installed from python.org.

Creating Your First Project

Starting with Chatbot Development

  • A new folder named "AI engineering" is created where the main file chatbot.py will reside for coding purposes.
  • Essential extensions like Python and Pylint must be installed in VS Code to enhance functionality as an IDE.

Formatting and Running Code

Improving Coding Efficiency

  • Autopep8 is recommended as a formatter for adhering to PEP 8 standards; settings can automate formatting upon saving files.
  • Coderunner extension allows running code directly within VS Code's terminal instead of output tabs where user input cannot be entered.

Virtual Environment Creation

Managing Dependencies

  • A virtual environment is created using Pipenv, isolating dependencies specific to this project without affecting global installations.

Configuring Interpreter Settings

  • The address of the virtual environment needs configuration in both Coderunner settings and VS Code interpreter settings for proper execution.

Beginning Chatbot Development

Implementing Basic Functionality

  • The main function structure begins with defining main() which initializes user interaction through input prompts.

Understanding Execution Context

Script Execution Logic

  • An explanation of how Python executes scripts based on special variable __name__, determining if it runs directly or imported elsewhere.

Building Bot Logic

Connecting User Input

  • User inputs are captured via input() function; these inputs are then processed by a bot function designed to return predefined responses initially.

Testing Initial Bot Response

Running the Program

  • Upon executing the program, initial tests show static responses until further enhancements connect it with real LLM capabilities.

Transitioning Towards LLM Integration

Preparing for Advanced Features

  • Discussion shifts towards integrating chatbots with large language models (LLMs), emphasizing understanding underlying processes before implementation.

Defining Roles: AI Engineer vs ML Engineer

Career Path Clarification

  • Distinction made between roles: ML engineers focus on building models while AI engineers leverage pre-trained models for application development.

Introduction to NLP Concepts

Natural Language Processing Explained

  • NLP enables computers to understand human language through algorithms; historical context provided regarding RNN versus transformer architectures.

Understanding Language Models

  • Explanation of LM (Language Model), followed by LLM (Large Language Model), highlighting their training data sources primarily from internet content.

(Timestamps not included)

Mechanism Behind LLM Operations

  • Basic operational loop described where LLM predicts one token at a time during text generation processes until completion tokens signal end of response generation.

1581 ]( Timestamps not included )

Exploring Hugging Face Platform

  • Hugging Face introduced as an essential resource hub offering free access to various AI models, datasets, fostering community collaboration similar to GitHub's functionalities.

Understanding Model Variations

Different Versions of Models

  • Popular models often have multiple variations, with the underlying architecture remaining similar but differing in parameters.
  • For instance, models can range from 8 billion to 70 billion parameters, showcasing significant differences in capability and performance.

The Importance of Model Cards

  • A model card serves as documentation for a model, detailing its creator, training methods, datasets used, and evaluation benchmarks.
  • Users can assess whether a model fits their needs by reviewing the information provided in the model card.

Exploring Hugging Face

  • Users are encouraged to explore Hugging Face's interface to familiarize themselves with various models and their functionalities.
  • Hugging Face provides guidance on using models through different libraries and offers notebooks for beginners.

Choosing and Using Models

Commercial vs. Open Source Models

  • For commercial models like Sonnet by Anthropic, users must purchase access through the provider.
  • Open-source models found on platforms like Hugging Face can be run locally or accessed via an API from a deployed provider.

Recommended Provider: Grock

  • The course will utilize Grock due to its generous free tier that allows experimentation without financial commitment.
  • Grock is distinct from other services (e.g., Elon Musk's chatbot), focusing instead on providing AI tools for learning purposes.

Advantages of Using Grock

Generosity of Free Tier

  • Grock’s free tier is beneficial for learners; it rarely imposes limits during experiments compared to other providers.

Pricing Structure

  • Even when transitioning to paid plans, Grock remains competitively priced while offering a variety of capable models suitable for diverse tasks.

Setting Up Your Environment

Creating an Account and API Key

  • Users need to create an account on Grock and generate an API key essential for accessing services.

Playground Features

  • The playground allows users to interact directly with available models before integrating them into applications.

Understanding APIs and Wrappers

Interaction Through APIs

  • Queries are sent through APIs; this process resembles entering URLs in browsers but occurs within applications instead.

Utilizing Wrappers

  • Wrappers simplify interactions with APIs by handling complexities such as authentication and request construction automatically.

Benefits of Standardization

Simplifying Collaboration

  • Using wrappers standardizes communication with providers, making it easier for teams to collaborate without confusion over parameters or requests.

Transitioning from Theory to Practice

Installing Necessary Packages

  • To begin coding a chatbot project, users must install the OpenAI wrapper alongside necessary dependencies using pip commands.

Managing API Keys Securely

Best Practices for Security

  • It’s crucial not to hard-code API keys into source code; instead, use environment variables stored securely outside the main application codebase.

Understanding LLM Responses and Roles

Extracting Single Items from Responses

  • In most cases, the response from a language model (LLM) will contain only one item, which is extracted for further processing.
  • The format of the response includes a role (e.g., assistant) and content, similar to how user messages are structured.

User and Assistant Roles

  • The user sends messages with the role "user," while responses from the LLM have the role "assistant."
  • The instructor reassures learners that these concepts will be revisited multiple times for clarity.

Testing Communication with LLM

  • A demonstration shows successful communication with an LLM by asking questions like "What is the capital of France?" and receiving accurate responses.

Parameters for Sending Requests to Providers

Key Parameters Explained

  • When sending requests to an LLM provider, several parameters must be specified, starting with the model type.
  • Messages are sent as a list rather than a single message; this will be clarified later in the discussion.

Role Definitions in Messages

  • Each message has a defined role: system, user, or assistant. These roles are common across AI engineering contexts.
  • The user role represents what users ask; the assistant role indicates responses generated by the LLM.

System Role and Instructions

Purpose of System Role

  • System messages provide instructions to guide how models should respond during interactions.

Temperature Parameter in Model Responses

Understanding Temperature Settings

  • Temperature affects creativity and randomness in model outputs; lower values yield more deterministic results while higher values encourage variability.

Practical Applications of Temperature

  • For factual tasks like coding, lower temperatures ensure consistent responses; creative tasks benefit from higher temperatures for varied outputs.

Max Tokens Limitations

Defining Max Tokens

  • Max tokens set limits on how many tokens (words/phrases processed by models), controlling output length based on requirements or costs.

Implications of Token Limits

  • Setting max tokens creates hard limits that may not allow natural completion of thoughts within specified constraints.

Streaming Responses from Models

Benefits of Streaming

  • Streaming allows models to generate responses piece-by-piece rather than waiting for complete answers, enhancing user experience during interactions.

Creating Continuous Conversations

Implementing Conversation Loops

  • To mimic real-life chatbot experiences, implementing loops allows users to continue asking questions until they choose to terminate interaction.

Input Handling Improvements

  • User inputs are cleaned using methods like strip (to remove spaces around input).
  • Inputs are converted to lowercase ensuring uniformity regardless of capitalization used by users.

Managing Conversation History

  • Users need conversation history stored at application level since LLM does not retain memory between queries. This ensures context is maintained throughout interactions.

Storing Queries and Responses

  • By appending both user queries and model responses into a list structure before sending new queries back to the model ensures continuity in conversations.

Utilizing System Role Effectively

Adding Instructions via System Role

  • Incorporating system messages at beginning helps define behavior expectations for models effectively guiding their responses according to specific needs.

Foundation Models Overview

  • Foundation models possess broad knowledge but often require customization through prompt engineering or additional resources tailored towards specific applications or domains.

Understanding Tokens in Language Models

The Concept of Tokens

  • Tokens are the basic units that language models (LLMs) use to process text. For example, the phrase "I love AI" can be broken down into three tokens: "I," "love," and "AI."
  • A token may represent a complete word, part of a word, or punctuation. For instance, the word "interesting" could be split into two tokens: "inter" and "esting."
  • Different models utilize different tokenizers which determine how text is divided into tokens. Each model has its own vocabulary for processing text.

Token Probability Distribution

  • When predicting the next token in a sequence, LLMs consider context and generate a probability distribution for potential candidates based on their vocabulary.
  • Example probabilities might show that certain words fit better grammatically than others; for instance, “happy” might have a higher probability than “went.”

Non-deterministic Behavior of LLMs

  • The probabilistic nature of token selection allows LLMs to exhibit creativity and non-determinism in responses.
  • Various parameters like temperature influence how these probabilities affect token generation.

Tokenization Process

  • Text input is converted into numerical representations called token IDs through a tokenizer before being processed by an LLM.
  • This conversion results in an array of token IDs that represent the original text.

Importance of Token Management

Cost Management with Tokens

  • Understanding tokens is crucial for cost management as many AI services charge based on the number of tokens processed.
  • Input tokens refer to those sent to the model while output tokens are generated by it; pricing often varies between these two types.

Counting Tokens Before and After Requests

  • There are two scenarios where counting tokens is necessary: before sending requests and after receiving responses from an LLM.

Post-request Token Counting

  • After receiving a response from an LLM, metadata typically indicates how many input and output tokens were used.

Pre-request Token Counting Challenges

  • Counting tokens before sending requests requires knowledge about specific tokenizers since different models tokenize differently.

Implementing Token Tracking in Code

Setting Up Variables for Tracking Tokens

  • A global variable named total_tokens is created to keep track of consumed tokens throughout conversations with the model.

Updating Total Tokens During Conversations

  • Each time a response is received from the model, total consumed tokens are updated using values from response metadata.

Refactoring Code with Object-Oriented Programming

Transitioning to Object-Oriented Design

  • To improve maintainability as features grow, transitioning to object-oriented programming (OOP), specifically creating classes, becomes essential.

Creating Chatbot Class Structure

  • A new class called Chatbot encapsulates previous global variables as attributes within its constructor for better organization.

Defining Methods Within Class

Methods such as bot (for communication with LMs), chat (for conversation loops), and later report (for observability metrics), are defined within this class structure.

Adding Cost Calculation Feature

Enhancing Reporting Functionality

  • The report method now calculates costs associated with input and output tokens separately based on hypothetical pricing structures.

Tokenization and Counting Tokens

Introduction to Tokenization

  • The process begins with tokenizing user input before sending it to the bot method, allowing for better handling of text data.
  • The program prints token IDs associated with each word in the user's input, providing insight into how text is processed.

Counting Tokens

  • Using Python's built-in len function, the number of tokens can be easily counted from a list generated by the tokenizer.
  • Knowing the number of tokens before sending a request to an LLM (Large Language Model) can serve as a guard against exceeding limits.

Implementing Token Limits

  • A variable called token_count is introduced to store the number of tokens, enabling conditional checks on user input length.
  • If user input exceeds a predefined limit (e.g., 10 tokens), an error message prompts users to shorten their input.

Handling Different Models and Tokenizers

Adapting to Various Models

  • When using models outside OpenAI's family, such as Llama or others from Hugging Face, it's important to recognize that different tokenizers may yield slightly different results.
  • For most tasks, approximate token counts are sufficient; exact numbers are not always necessary.

Accessing Specific Tokenizers

  • In cases where precise token counts are needed for specific models like Llama, utilizing Hugging Face's Transformers library becomes essential.
  • An access token may be required for certain functionalities within this library; creating one is recommended for enhanced access.

Setting Up Transformers Library

Installation and Importing

  • The Transformers library must be installed via pip and imported into the codebase for use in managing model-specific tokenization.

Utilizing AutoTokenizer Class

  • Instead of using TikToken, the AutoTokenizer class from Transformers is employed to handle model-specific encoding processes effectively.

Managing Total Token Consumption

Implementing Total Token Limits

  • A new feature allows setting a total limit on tokens consumed during conversations; if exceeded, further interaction is halted with an appropriate message.

Testing Implementation

  • After implementing both individual prompt limits and total consumption limits, testing confirms that exceeding these thresholds correctly terminates interactions.

Streaming Responses from LLM

Changing Response Behavior

  • To enhance user experience, responses from the LLM can now be streamed rather than waiting for complete generation before displaying output.

Iterating Over Streamed Responses

  • By setting streaming arguments in requests, responses become iterable chunks that can be processed incrementally as they arrive.

Storing Complete Responses

Building Full Response History

  • As chunks arrive during streaming mode, they are concatenated into a single response string while also being printed immediately for real-time feedback.

Understanding Context Window Limitations

Defining Context Window

  • Each LLM has a fixed context window size which dictates how many tokens (input + output combined), it can process at once.

Strategies for Managing Context Windows

Sliding Window Approach

  • This strategy involves keeping only recent messages (e.g., last five), discarding older ones as new messages come in. It helps maintain relevance but risks losing important context over time.

Managing Conversation History in Python

Implementing Message Trimming

  • The use of negative indexing allows selection of the last four non-system messages, stored in a variable called trimmed_messages.
  • After gathering system messages and trimmed messages, Python's unpacking syntax is utilized to create a new conversation history.
  • A token limit was exceeded during testing; adjustments were made to increase it for better performance.
  • Upon running tests, the program successfully separated system messages from user queries, retaining only the last four relevant messages.

Transitioning to Summarization Approach

  • The second approach involves summarizing older messages instead of deleting them, preserving more information.
  • This strategy is common in AI applications where maintaining context is crucial while managing conversation history.

Implementation Steps for Summarization

  • An attribute named iteration is introduced to track the number of conversation iterations, initialized at zero.
  • At the beginning of each loop iteration, this attribute increments by one to monitor message counts effectively.
  • A new method called summarize_messages is defined but initially left unimplemented for future development.

Conditional Summarization Logic

  • To ensure summarization occurs every five messages, a modulus operator checks if the current iteration count is divisible by five before proceeding.
  • System and other messages are separated similarly to previous methods; older messages will be summarized while recent ones are preserved.

Finalizing Summary Integration

  • Older and newer message lists are created using bracket notation and unpacked into two variables: early_messages and last_messages.
  • An LLM call summarizes early messages with guidance provided through a system message that instructs on key facts retention.

Testing New Conversation Management Strategy

Running Tests on New Implementation

  • After implementing summarization logic, tests confirm successful integration as users interact with the chatbot about various topics.

Introduction to Sentiment Analysis Project

Overview of Sentiment Analysis Task

  • Sentiment analysis determines whether text conveys positive, negative, or neutral sentiments; applicable across numerous AI tasks like customer feedback evaluation.

Approaches to Implementing Sentiment Analysis

  • Two approaches discussed: utilizing an LLM similar to previous projects or employing specialized models designed specifically for sentiment analysis tasks.

Setting Up Sentiment Analysis with LLM

Initial Setup for LLM-Based Analysis

  • A new file named sentiment_analysis.py is created; necessary libraries such as OpenAI are imported alongside environmental variable access setup.

Defining Core Functionality

  • A method named sentiment_analysis receives text input and returns model responses after wrapping it in appropriate structure for processing.

Understanding Prompt Engineering

Conceptual Framework of Prompt Engineering

  • Prompt engineering controls model behavior through input examples; different prompts yield varied outputs even when using the same model.

Examples of Effective Prompting Techniques

  • F-shot prompting provides examples demonstrating expected behavior; this helps guide models toward desired outputs without lengthy explanations.

Importance of Example Selection

  • Choosing representative examples covering diverse scenarios enhances model understanding while avoiding excessive token usage.

Understanding Zero-Shot Classification

Introduction to Zero-Shot Classification

  • Zero-shot classification allows models to classify data without needing a labeled dataset for training, focusing on the ability of pre-trained NLI models.
  • Traditionally, classification tasks require extensive labeled datasets; for example, tagging articles by programming languages like JavaScript or Python.
  • A typical approach involves training a model on thousands of labeled articles to predict categories for new, unlabeled articles.

Advantages of Zero-Shot Classification

  • With zero-shot classification, we can use a general-purpose NLI model that understands relationships between text statements and candidate labels without retraining.
  • This flexibility allows changing candidate labels (e.g., from programming languages to health topics) without altering the underlying model.
  • The models used in zero-shot classification are smaller than large language models (LLMs), making them more efficient and easier to run locally.

Overview of BERT and DistilBERT

Introduction to BERT

  • BERT stands for Bidirectional Encoder Representations from Transformers; it processes text bidirectionally and captures contextual meanings effectively.
  • Context is crucial in understanding words with multiple meanings; for instance, "blue" can refer to color or emotion depending on surrounding words.

Knowledge Distillation

  • DistilBERT is a smaller version of BERT created through knowledge distillation, which trains a compact model to replicate the performance of larger models while reducing computational requirements.
  • This technique enables retaining useful performance while minimizing size and resource consumption.

Model Architecture: Encoder vs. Decoder

Understanding Model Types

  • BERT is an encoder-only model designed for understanding text rather than generating it; this makes it suitable for tasks like natural language inference (NLI).
  • In contrast, decoder models generate output based on input representations; they are essential in tasks requiring text generation such as translation.

Cross Encoders

  • Cross encoders process two pieces of text together, allowing direct comparison and relationship learning between inputs—useful in relevance ranking systems.

Implementing Zero-Shot Classification

Using Hugging Face Models

  • To implement zero-shot classification using Hugging Face's transformers library, users can choose between pipelines (simpler interface with less control) or auto classes (more complex but offers greater control).

Code Implementation Steps

  • Replace previous LLM calls with classifier pipeline setup specifying task type as zero-shot classification along with the chosen model name.

Running the Model Locally

Execution Process

  • Upon first execution, the model downloads necessary weights into memory; subsequent runs will be faster due to caching.

Changing Candidate Labels

  • Demonstrating flexibility in zero-shot classification: changing candidate labels from sentiment analysis categories (positive/negative/neutral) to broader topics like health or fitness shows adaptability without retraining the model.

Introduction to Embeddings

Conceptual Overview

  • Embeddings convert various forms of information into numerical representations that capture meaning—similar to how humans form mental images when processing information.

Applications of Embeddings

  • Useful in semantic search where meaning matters over exact keyword matches.
  • Employed in recommendation systems and spam detection by representing messages numerically for classifiers.

Exploring MiniLM

Details about MiniLM

  • The project will utilize MiniLM—a compact transformer embedding model designed for efficiency across various applications including semantic search and sentence similarity.

Understanding Sentence Embeddings

Introduction to the Model

  • The model utilizes a method called "encode" to embed sentences, storing the results in a variable named embeddings.
  • The initial run of the program may take longer due to model downloading and initialization; subsequent runs are faster.
  • The output dimensions indicate that four embeddings were generated, each containing 384 numerical values, representing points in a 384-dimensional space.

Semantic Search Basics

  • The session introduces semantic search, aiming to find the most similar sentence from a collection based on a new query.
  • Each query is converted into an embedding vector for comparison with existing sentence embeddings.
  • Cosine similarity is highlighted as a common metric for measuring similarity between vectors, ranging from -1 (opposite directions) to 1 (same direction).

Implementing Similarity Functionality

Coding Similarity Calculation

  • The code imports utilities from sentence transformers for calculating cosine similarity and sets up functions for finding closest matches.
  • A function named find_closest is defined to return the most similar sentence based on input query and list of sentences.

Finding Closest Sentence

  • Variables closest_index and closest_score are initialized to track the best match during iteration through embeddings.
  • Cosine similarity scores are calculated within a loop comparing each sentence's embedding against the query embedding.

Running Semantic Search

Testing Implementation

  • After implementing the function manually, it identifies "today is a sunny day" as the closest match for the query "I'm feeling great today."

Utilizing Built-in Functions

  • It’s noted that there exists a built-in utility function called semantic_search, which simplifies this process by requiring pre-computed embeddings.

Introduction to Retrieval-Augmented Generation (RAG)

RAG Overview

  • RAG systems address limitations of LLM models by providing access to relevant information at query time.

Limitations of LLM Models

  • Knowledge cutoffs restrict models' ability to provide accurate answers about recent events or specific company policies without external data retrieval.

Addressing Hallucinations in AI Responses

Problematic Responses

  • Hallucinations occur when models generate incorrect information due to lack of context or relevant data.

Enhancing Accuracy with RAG

  • RAG improves response accuracy by retrieving relevant documents before generating answers, thus reducing hallucination risks.

Components of RAG Systems

Breakdown of RAG Elements

  • RAG consists of three main components: retrieval (finding relevant info), augmentation (enhancing input), and generation (producing responses).

Importance of Retrieval

The retriever component plays a crucial role in ensuring quality responses by sourcing only pertinent information related to user queries.

Challenges with Providing Full Context

Context Window Limitations

  • (

14951)s Sending entire documents can exceed context window limits or lead to unnecessary processing costs when irrelevant information is included.

Quality Over Quantity

  • Providing excessive irrelevant details can hinder focus on critical information needed for accurate responses.

Implementing Chunk-Based Retrieval

Chunking Process

  • Documents should be split into smaller chunks before generating embeddings; this allows more efficient retrieval during user queries.

Final Steps in RAG Implementation

  • Combining retrieved chunks with user queries enables LLM models to generate informed responses based on augmented context.

Building a Rack Project from Scratch

Introduction to the Knowledge Base

  • The project begins with an emphasis on investing time for future benefits, introducing a 25-page PDF that details symptoms of approximately 100 diseases.
  • Each disease is described in a paragraph, and the PDF will be made available for download to assist viewers in following along.

Utilizing Langchain and PiPDF

  • The tutorial will utilize PiPDF for reading the PDF and Langchain, a framework that simplifies AI application development by providing reusable components.
  • Langchain aids in organizing code, reducing complexity, and can be applied beyond rack systems.

Document Object Structure

  • A document object in Langchain consists of page content and metadata, allowing consistent handling of information regardless of its source.
  • Metadata includes essential identifiers like file name and page number, which are crucial for tracking information sources during development.

Reading the PDF File

  • The process involves creating a function to read the PDF using PiPDF's reader object to extract text from each page into document objects.
  • Each document object captures both content and metadata (source file name and page number), facilitating easier debugging and reference tracking.

Importance of Metadata

  • Storing metadata is vital for identifying original information sources when answering user queries or debugging issues within the system.
  • Metadata enhances trustworthiness by providing references back to original documents when presenting answers to users.

Testing the Functionality

Initial Testing Results

  • After implementing the reading function, it successfully processes 25 pages into document objects containing both content and metadata.

Chunking Process

Need for Chunking

  • Full pages contain too much information; chunking is necessary to ensure relevant sections about specific diseases can be retrieved accurately.

Implementing Text Splitters

  • Instead of manually splitting text, developers typically use existing text splitters provided by frameworks like Langchain.
  • Recursive character splitting preserves natural boundaries while keeping chunks manageable in size without breaking sentences awkwardly.

Configuring Text Splitters

Setting Up Parameters

  • The recursive character text splitter will be configured with parameters such as chunk size (110 tokens), ensuring context preservation through overlap (10 tokens).

Splitting Documents into Chunks

Executing Document Splitting

  • Using the configured splitter allows processing all documents at once, resulting in smaller chunks suitable for embedding while retaining their associated metadata.

Summary of Progress So Far

Overview of Achievements

  • Successfully converted a 25-page PDF into 183 smaller document objects through chunking, preparing them for embedding processes ahead.

Converting Chunks into Embeddings

Preparing for Vectorization

  • Transitioning from raw data to high-dimensional vector space requires converting each chunk into embeddings using models like All Mini LM via Langchain integration.

Normalizing Embeddings

Understanding Normalization

  • Normalizing vectors ensures efficient similarity calculations during retrieval processes by scaling vectors uniformly within high-dimensional space.

Generating Embeddings

Extracting Text Content

  • List comprehension extracts text from each chunk before passing it to generate embeddings efficiently while maintaining consistency with Langchain’s structure.

Next Steps: Vector Database Integration

Moving Forward

  • The next phase involves utilizing a vector database designed specifically for storing embeddings rather than relying on Python lists alone.

Understanding Vector Databases and Memory Management

Memory Management in Vector Storage

  • When using a Python list to store vectors, they occupy memory during program execution but disappear upon termination. This becomes problematic as datasets grow larger.
  • For example, storing 10 million 384-dimensional vectors requires approximately 14 GB of memory, which can exceed the capacity of typical computers with 16 GB RAM.
  • A vector database allows for data persistence on disk, enabling management of large datasets that cannot fit entirely in memory.

Search Performance Challenges

  • With millions of vectors, brute force search methods become inefficient and costly due to the need to compare each query against every vector.
  • Vector databases utilize specialized indexing techniques like approximate nearest neighbor algorithms to enhance retrieval efficiency without sacrificing accuracy.

Integrating Chroma into Applications

Setting Up Chroma

  • To integrate Chroma with LangChain, install it using pip install langchain chroma and import it into your project.
  • Define a collection name (e.g., "medical data") for organizing records within Chroma; if it exists, Chroma connects to it; otherwise, it creates a new one.

Configuring Embedding Models

  • Specify the embedding model used by passing the constructed model to Chroma. This simplifies the process as Chroma handles embedding generation automatically when documents are added.

Distance Metrics in Vector Comparison

Choosing Distance Metrics

  • The distance metric is crucial for comparing vectors; cosine distance is preferred over cosine similarity in this context.
  • Cosine distance is calculated as 1 - textcosine similarity, while squared L2 distance measures differences between vector components.

Collection-Level Configuration

  • It's important to set the distance metric at collection creation since changing it later does not affect existing collections.

Managing Document Ingestion with Unique IDs

Adding Documents Without Duplicates

  • Using vector_store.add_documents, you can add document objects directly without extracting text manually. However, duplicate entries may occur if unique IDs are not assigned.

Preventing Duplicate Records

  • To avoid duplicates when adding documents, generate unique IDs for each chunk using Python's built-in hashlib module before storage.

Implementing a Retrieval-Augmented Generation (RAG)

Creating a Conversation Loop

  • Develop a conversation loop similar to previous chatbot projects where user input serves as the search query passed to the vector store for retrieval.

Utilizing Similarity Search Methods

  • Use LangChain's similarity_search_with_score method to retrieve relevant chunks based on user queries while also obtaining associated scores for evaluation purposes.

Evaluating RAG System Performance

Observability During Development

  • It’s essential to inspect retrieved documents during development by printing them or saving them for tracking changes over time.

Evaluation Metrics

  • Evaluate retrieval effectiveness through metrics such as Mean Reciprocal Rank (MRR), focusing particularly on whether relevant information appears among top results.

Finalizing Integration with Language Models

Instruction Design for Language Models

  • Craft system prompts instructing models on how to respond grounded in retrieved contexts rather than relying solely on pre-existing knowledge or assumptions.

Sending Queries and Context

  • Create an LLM function that combines user queries with context from retrieved chunks before sending requests and returning responses effectively.

Implementing Document Processing and Querying

Extracting Information from Chunks

  • The speaker discusses using enumerate to index chunks of data, unpacking tuples into variables named doc and score.
  • Metadata extraction is performed using formatted strings, with placeholders for source, page number, and retrieval score (not similarity score).
  • The content is concatenated using the join method with a specified separator before calling the language model function (lm) with user input.

Debugging Issues in Code

  • An error occurs due to loading environment variables after their intended use; this is corrected by adjusting the code sequence.
  • After debugging, the program successfully answers a query about high blood pressure symptoms by retrieving relevant information from a vector database.

Finalizing Document Processing

  • The application retrieves relevant chunks and combines them into context for improved responses based on user queries.
  • The implementation highlights that every run of the program repeats document processing unnecessarily; separating ingestion from querying is suggested as an improvement.

Introduction to AI Agents

Understanding AI Agents

  • The speaker introduces AI agents as crucial components in AI engineering, emphasizing their growing importance in solving complex tasks beyond simple chatbots.

Limitations of Current Models

  • Previous models lacked sufficient information for certain tasks; retrieval augmented generation (RAG) was introduced to enhance response quality by providing external context.

Need for Action-Oriented Responses

  • Many applications require models not just to generate answers but also to perform actions like retrieving real-time data or interacting with services.

Tool Utilization in AI Agents

Mechanism of Tool Use

  • An AI agent uses an LLM (language model), which decides when to utilize available tools based on user queries and tool descriptions provided during setup.

Example Scenario: Weather Retrieval

  • A practical example illustrates how an LLM can request current weather data through a defined tool instead of relying solely on its training knowledge.

Workflow of Tool Requests

Step-by-Step Process Overview

  • When a user asks about current weather conditions, the LLM identifies the need for external data and requests execution of the appropriate tool.

Handling Tool Calls

  • This process involves multiple calls: one for determining if a tool is needed and another for generating final responses based on retrieved results.

Framework Support for Complex Applications

Managing Complexity in Agent Systems

  • Frameworks like Langchain simplify connecting LLM tools while managing complexities associated with executing multiple steps within agent systems.

Transitioning to Langchain Integration

Setting Up New Environment

  • The speaker transitions from OpenAI's wrapper to Langchain's wrapper for Groq, highlighting differences in parameter handling between integrations.

Building an AI Agent

Initial Chatbot Development

  • A class called agent is created that initializes an LLM instance along with conversation history management through message classes.

Testing Basic Functionality

  • Initial tests confirm that the chatbot maintains conversation history effectively across multiple interactions without any tools implemented yet.

Defining the Get Weather Function

Overview of the Function

  • The function get_weather is defined to take a city name as a string and return a dictionary containing weather information.
  • It includes a docstring that describes its purpose, which is essential for documentation and understanding by other developers.

Importance of Documentation

  • The docstring serves not only for human readability but also aids AI models like LangChain in determining when to call this function based on user requests.
  • A clear description ensures that the model can accurately identify when it needs to invoke the tool, preventing errors from vague or misleading descriptions.

Choosing the Right Model

Model Selection Considerations

  • The choice of model impacts functionality; smaller models may struggle with complex tasks, leading to incorrect tool calls or invalid arguments.
  • It's crucial to instruct the model appropriately regarding tool usage without assuming it will always need one.

Constructing the Agent Class

Initializing the Agent

  • The agent class is constructed using create_agent, specifying both the model and tools available for use.
  • Currently, only one tool (get_weather) is added, demonstrating how LangChain orchestrates interactions seamlessly.

Testing Tool Invocation

Running Tests

  • Initial tests show no tool invocation until specific queries about weather are made.
  • Upon asking about Paris's weather, successful execution confirms that the agent can now utilize tools effectively.

Understanding Tool Calling Complexity

Behind-the-scenes Mechanics

  • Tool calling involves multiple steps: checking if a tool is requested, validating arguments, executing functions, and returning results back to the model.
  • This complexity necessitates careful implementation of what’s termed as a "tool calling loop."

Approaches to Implementing Tool Calling

Different Methods Explained

  • Three main approaches exist: binding tools directly to models (lower-level), using create_agent (higher-level abstraction), and employing Langraph for explicit control over workflows.

Integrating Web Search Capabilities

Enhancing Information Retrieval

  • Introducing Tavi allows integration of web search capabilities into applications, addressing limitations such as knowledge cutoffs in LLM responses.

Connecting Tools to Agents

Adding New Functionalities

  • A new search tool (tab_search) is created alongside existing functionalities like weather retrieval. This enhances agent capabilities significantly.

Comparing Information Sources

Similarities Between Projects

  • Both previous projects (PDF extraction and web searching via Tavi API integration), while different in data sources, share an overarching goal of enhancing information accessibility for users.

Introduction to Model Context Protocol (MCP)

Standardizing Tool Integration

  • MCP aims at standardizing how AI applications connect with external tools across various programming environments. This reduces redundancy in integrations across projects.

Workflow Summary Using MCP

Flow Explanation

  • The workflow involves connecting an AI application with an MCP server where available tools are advertised. The LLM decides which tool it needs based on provided descriptions before invoking them through an MCP client.

Introduction to Prompt Template Class

Overview of Prompt Templates

  • The prompt template class is a simple yet powerful tool in LangChain, allowing users to create reusable templates with dynamic placeholders.
  • It enables the generation of content that varies based on user-specific data, such as names and brand names, without rewriting entire strings.
  • Placeholders are defined using curly braces within a string, which can later be filled with actual values when generating output.

Creating a Dynamic Email Template

  • To convert a regular string into a prompt template, an instance of the prompt template class is created by passing the template string and variable names.
  • The format method allows for inserting specific values into the placeholders; for example, filling in "Alex" for username and "Neon Learn" for brand name.
  • This approach separates the structure of prompts from their specific values, enhancing reusability across different contexts.

Transition to Chat Prompt Template

Purpose of Chat Prompt Template

  • Unlike standard prompt templates, chat prompt templates handle sequences of messages from various roles (user, AI, system), making them ideal for chatbot applications.
  • They allow developers to represent different message types effectively while maintaining context throughout conversations.

Implementing Chat Prompt Templates

  • The from_messages method creates chat prompt templates from lists of tuples representing messages with specified roles and content.
  • A practical example involves creating a translation application where source and target languages are dynamic rather than hardcoded.

Connecting Prompts to Language Models

Building Workflows with LCEL Syntax

  • LCEL syntax facilitates connecting components in LangChain using pipe operators to create workflows that pass outputs as inputs between components seamlessly.
  • Components must support the runnable interface; both prompts and language models can produce runnable objects suitable for this syntax.

Executing Chains

  • By invoking methods on chains instead of manually managing data flow between components, developers streamline processes significantly.

Enhancing Conversations with History

Incorporating Conversation History

  • Including conversation history allows LLM responses to be more relevant by considering previous interactions during ongoing dialogues.
  • A new class called messages_placeholder is introduced to manage conversation histories effectively within chat prompts.

Practical Example: Translation Application

  • In this scenario, examples are provided in conversation history to guide LLM formatting expectations through few-shot prompting techniques.

Understanding Structured Output

Importance of Structured Responses

  • Structured output ensures that LLM responses contain specific fields like product name or price necessary for further application use cases.

Implementing Structured Output with Pydantic

  • Pydantic serves as an effective tool for validating data structures against defined schemas while integrating smoothly within LangChain projects.

Practical Application Using Pydantic

Extracting Information from Text

  • A project demonstrates how Pydantic can extract structured information about individuals (e.g., Elon Musk's details), ensuring predictable formats through validation rules.

Implementing Structured Output in Lang Chain

Defining User Schema

  • The net worth of the user is specified, along with expected data types for each field and descriptions of their contents.
  • A lower temperature setting (e.g., 0.1) is recommended to ensure factual responses without creativity when dealing with structured outputs.

Using LLM with Structured Output

  • The method with structured output allows specifying schemas that models should follow, enhancing the structure of outputs.
  • Input from a paragraph on Elon Musk's Wikipedia page is processed using this structured approach, yielding organized results like name, age, companies, and net worth.

Validation and Extraction

  • The model successfully extracts information according to the defined schema instead of returning arbitrary text; Pyantic validates the resulting data against expected types.

Understanding Checkpoints in Lang Chain

Purpose of Checkpoints

  • Checkpoints are crucial for saving and restoring application states, including conversation history to save time during interactions.
  • An agent is created using a function that does not initially include any tools but serves as a basic conversational chatbot.

Managing Conversation History

  • LLMs do not remember previous conversations automatically; thus, conversation history must be stored manually to provide context for future interactions.
  • Storing conversation history in a Python list poses limitations since it disappears once the program terminates; persistent storage solutions are necessary for long-term access.

Utilizing Lang Graph Checkpointers

Features of Checkpointers

  • Lang Graph provides mechanisms for saving and restoring graph state across multiple invocations without manual management of conversation history.
  • An in-memory saver is used initially for simplicity before transitioning to database storage later on.

Implementation Steps

  • System messages need alternative handling since they were previously stored within message lists; explicit instructions can now be passed directly through agent creation arguments.

Thread IDs and Multiple Sessions

Importance of Thread IDs

  • Thread IDs allow distinguishing between multiple independent conversation histories within an application, enabling users to switch contexts seamlessly.

Configuration Dictionary Setup

  • A configuration dictionary containing thread ID information must be created before invoking agents to maintain separate session histories effectively.

Switching Between Sessions

Session Management Logic

  • Users can switch sessions by entering specific commands (e.g., "CH"), updating the active session variable accordingly while maintaining distinct histories.

Testing Session Functionality

  • Successful implementation allows users to ask questions relevant to their current session context without confusion or overlap between different topics discussed earlier.

Transitioning Conversation History Storage to PostgreSQL

Database Setup Requirements

  • PostgreSQL is chosen as the database solution for storing conversation history persistently; installation steps are briefly outlined for user guidance.

Connecting Application with PostgreSQL

  • Connection strings must be configured correctly within environment variables before integrating PostgreSQL savers into the application logic.

Accessing Conversation Messages Directly

Retrieving Historical Messages

  • The agent's get state method enables direct access to past messages associated with specific thread IDs without needing complex queries.

Conclusion on UUID Usage

  • In real-world applications, utilizing UUID (Universally Unique Identifier), generated easily in Python, enhances identification practices beyond simple session names.

Understanding Middleware in Agent Life Cycle

Middleware Customization

  • Middleware allows customization of an agent's behavior without starting from scratch, fitting into the agent life cycle.
  • An agent sends messages to a language model (LLM), which may request tool calls; middleware can intervene at various stages of this process.
  • Specific middleware can be defined to run before processing requests or calling models, enhancing control over these interactions.

Implementing Middleware

  • Two key middleware examples are "before agent" and "before model," which can be imported from Lang Chain agents.
  • Decorators are used to convert functions into middleware, allowing for easy integration with the agent's lifecycle.
  • Lang Chain provides numerous pre-built middleware options that add capabilities without requiring additional coding.

Practical Applications of Middleware

Summarization Middleware

  • Summarization middleware simplifies managing conversation history by summarizing older messages while retaining recent ones.
  • Human-in-the-loop middleware ensures human approval for actions taken by AI agents, such as sending emails.

PII and Model Fallback

  • PII (Personally Identifiable Information) middleware detects and masks sensitive information before it reaches external models.
  • Model fallback middleware automatically switches to a secondary model if the primary one fails, ensuring continuity in operations.

Using Summarization Middleware in Practice

Implementation Steps

  • To use summarization middleware, import it from Lang Chain agents and create an instance with necessary parameters like model and thresholds.
  • Recent updates have deprecated certain arguments; new parameters include 'trigger' for token limits and 'keep' for message retention settings.

Introduction to Lang Graph

Building Blocks of Lang Graph

  • Lang Graph enables building complex workflows using nodes (actions), edges (connections), and state (data flow).
  • Nodes represent actions like LLM calls or database queries, while edges determine execution order based on completed actions.

Defining State Structure

  • A structured approach using TypedDict is recommended for defining expected keys and values within the state schema.

Creating Nodes and Edges in Lang Graph

Node Functions

  • Define node functions representing actions within the workflow; each function should return only fields that need updating.

Compiling the Graph

  • Use a builder object to register nodes, define edges, compile the graph, and invoke it with initial state values.

Decision Making in AI Agents

Conditional Logic Implementation

  • Decision-making involves conditional logic where specific conditions dictate which node executes next within a graph structure.

Example Workflow

  • A simple example illustrates multiplying a number by two or adding one based on whether the current state exceeds ten.

Building a Graph for Essay Writing with LLMs

Introduction to the Project

  • The project aims to utilize Large Language Models (LLMs) to write, evaluate, and revise an essay based on feedback.
  • It integrates various concepts learned throughout the course, emphasizing practical application.

Setting Up Environment Variables

  • The environment variables are loaded using the env method to facilitate LLM calls.
  • Importing necessary components like typed dict and defining keys such as topic, draft, score, and feedback is essential for managing state.

Defining State Structure

  • A class called content state is created to structure the essay's attributes: topic (string), draft (string), score (integer), feedback (string), and revision count (integer).
  • Each field serves a specific purpose; for instance, feedback from one LLM helps improve drafts generated by another.

Preventing Infinite Loops

  • A guard flag is introduced to prevent infinite loops in case the essay does not achieve a desired score after multiple revisions.

Implementing Graph Components

Identifying Graph Nodes

  • Three main nodes are identified: one for writing drafts, another for reviewing them, and a conditional function that determines if further revisions are needed.

Setting Up the Graph Structure

  • The graph structure is established using state graph, registering nodes like "write draft" and "review draft."

Running the Graph Workflow

Initializing State Values

  • An initial state containing values such as topic ("why sleep matters for learning"), empty draft, zero score, no feedback yet, and revision count set to zero is prepared.

Printing Results After Execution

  • Once executed successfully, results including final draft content, number of revisions made, and final score will be printed out.

Implementing Logic in Functions

Revision Conditions Implementation

  • The first function checks if the score meets or exceeds 8; if not met after three revisions it terminates to avoid endless loops.

Review Draft Functionality

  • This node prompts an LLM to evaluate the current essay version by assigning a score from 1 to 10 along with concise feedback.

Generating Draft Content

Writing Draft Logic

  • The logic involves generating an initial paragraph based on provided topics while incorporating reviewer feedback when revising existing drafts.

Final Testing of Workflow

Adjustments Made During Testing

  • Various conditions were tested during execution; adjustments included changing target scores which influenced how many revisions were required before achieving satisfactory results.

Introduction to Multi-Agent Systems

Concept Overview

  • Multi-agent systems involve multiple specialized agents working together rather than relying on a single agent with all tools available.

Benefits of Multi-Agent Systems

Specialization Advantages

  • Specialized agents can manage complex tasks more efficiently by focusing on specific responsibilities instead of overwhelming one agent with too many tools.

Supervisor Approach in Multi-Agent Systems

Implementation Strategy

  • In this approach , one main agent coordinates tasks among specialized agents without needing constant supervision .

Turn any video into a summary like this

YouTube links, meetings, lectures. With transcripts, search, and chat.

Video description

Ladies and gentlemen, welcome aboard NeonLearn flight AI-10. 🚀 Our journey to becoming an AI Engineer includes 10 projects, 10 planets to explore, from building a chatbot from scratch to multi-agent systems. 🪐 1. CHATBOT: Build a streaming chatbot from scratch with the Groq API. Learn tokens and tokenizers, context management, conversation summarization, token budgets and cost estimation. 🪐 2. CLASSIFIER: Sentiment analysis with an LLM, plus a bonus: zero-shot classification with NLI models running locally via Hugging Face Transformers. 🪐 3. EMBEDDINGS: Turn text into vectors with Sentence Transformers, then measure meaning with cosine similarity and build semantic search. 🪐 4. RAG: Chat with your own PDFs. Learn chunking, embeddings, the Chroma vector store, grounded prompting and answers with source citations. 🪐 5. AGENT: Build AI agents with LangChain that use tools such as web search with Tavily and custom tools, and get real work done for you. 🪐 6. STRUCTURED: Get reliable structured output from LLMs, extracting clean data into Pydantic models with JSON schema. 🪐 7. MEMORY: Give your agents long-term memory with checkpointers and PostgreSQL, and keep separate conversation threads. 🪐 8. MIDDLEWARE: Control agent behavior with middleware, such as automatic conversation summarization. 🪐 9. LANGGRAPH: Design stateful workflows as graphs, such as a write → review → revise loop that improves until it's good enough. 🪐 10. MULTI-AGENT: Build a team of AI agents with the supervisor pattern, where one agent delegates to specialist agents. 📘 FLIGHT MANUAL (GitHub Repository) All the course code is waiting for you on board: https://github.com/mohamad-sw/ai-engineering-tutorial ⭐ If this journey helps you, please give the repo a star. It helps more passengers find this flight. 🧭 FLIGHT PLAN 🛫 BOARDING 00:00:00 – Course Introduction 00:04:27 – Setting Up the Development Environment 🪐 PLANET CHATBOT 00:13:35 – Building the Chat Function 00:18:10 – What is an LLM 00:26:51 – What is Hugging Face? 00:36:14 – Using the Groq Provider 00:41:43 – Using a Wrapper to Interact with LLMs 00:49:42 – Sending Requests to the LLM 01:04:31 – LLM Parameters 01:13:45 – Adding a Conversation Loop 01:18:26 – Conversation History 01:23:02 – Implementing Conversation History 01:26:20 – System Role 01:32:52 – What Are Tokens? 01:41:26 – Counting Total Tokens 01:48:01 – Making the Program Object-Oriented 01:57:45 – Calculating Cost 02:03:56 – Tiktoken 02:10:45 – Using Any Model's Tokenizer 02:19:49 – Streaming 02:30:31 – Context Window Management: The Sliding Window Strategy 02:44:06 – Summarizing Conversation History 🪐 PLANET CLASSIFIER 02:55:53 – Sentiment Analysis 03:03:39 – Prompt Engineering 03:10:23 – Natural Language Inference (NLI) 03:18:52 – BERT Model 03:25:10 – Using Pipeline to Run a Model 🪐 PLANET EMBEDDINGS 03:32:48 – What Are Embeddings? 03:40:43 – All-MiniLM-L6-v2 03:42:40 – Using Sentence Transformers Models 03:47:02 – Semantic Search 🪐 PLANET RAG 03:58:35 – Retrieval-Augmented Generation (RAG) 04:08:10 – The Retrieval Component 04:16:27 – Preparing the Knowledge Base 04:27:46 – Data Chunking 04:38:30 – Converting Chunks into Embeddings 04:46:09 – Using the Chroma Vector Database 04:59:29 – Generating IDs for Chunks 05:04:21 – Retrieving Chunks from the Vector Database 05:13:34 – Generation 🪐 PLANET AGENT 05:26:02 – What Is an AI Agent? 05:35:59 – Using the LangChain Wrapper 05:42:04 – Adding a Conversation Loop 05:48:24 – Building an Agent with create_agent Function 06:00:28 – Three Approaches to Building an Agent 06:04:37 – Building a Web Search Agent 06:11:20 – The MCP Protocol 🪐 PLANET STRUCTURED 06:18:43 – Dynamic Prompts 06:21:52 – The PromptTemplate Class 06:26:28 – The ChatPromptTemplate Class 06:35:15 – The MessagesPlaceholder Class 06:39:55 – Generating Structured Output 06:50:36 – Extracting Information with Structured Output 🪐 PLANET MEMORY 06:55:55 – Checkpointers 07:00:27 – Using InMemorySaver 07:06:28 – Switching Between Conversations 07:10:24 – Using PostgresSaver 07:18:18 – Reading Messages from the Database 🪐 PLANET MIDDLEWARE 07:22:32 – What Are Middlewares? 07:30:25 – Summarization Middleware 🪐 PLANET LANGGRAPH 07:35:03 – What Is LangGraph? 07:48:15 – Conditional Edges 07:55:42 – Automated Article Writing and Revision System 🪐 PLANET MULTI-AGENT 08:16:00 – Multi-Agent Systems 08:21:31 – The Supervisor Approach 🎟️ Boarding is free. If you know someone who dreams of becoming an AI Engineer, share this flight with them. Your captain will be grateful. 🙏 💬 Leave a message for the captain in the comments. He reads them all. ℹ️ This course is not affiliated with or sponsored by any of the services or tools used in it. Please fasten your seatbelts and keep your engines on. 🚀 #AIEngineering #LLM #RAG #AIAgents #LangChain #LangGraph #Python