LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical…
From the publisher’s feed, collected in the ZeroLabs newsroom.
🚀 LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical ExamplesIntroductionWhen people start learning LangChain, they often think a “model” simply means ChatGPT or Gemini.In reality, LangChain provides a unified interface for working with different types of AI models from multiple providers such as OpenAI, Google, Anthropic, and Hugging Face.Without LangChain, switching between providers would require rewriting API calls and adapting to different response formats. LangChain solves this problem by offering a consistent abstraction layer over various models.What are Models in LangChain?Models are the core interfaces through which we interact with AI models. It is one of the core building blocks of a LangChain application.Models take input, process it, and generate meaningful output.Types Of ModelsLanguage Model:Language Models are AI systems designed to understand, generate, and process natural language.Examples: GPT-4, Claude, Gemini, and LlamaThese models are primarily used in: Chatbots, Content Generation, Coding Assistants, and AI Agents.Embedding Model:An embedding model converts text into a list of numbers( a vector) that captures the meaning of the text. This places semantically similar text close together in vector space"Tokyo is the capital of Japan." -----> [0.234, -0.129, 0.845, ...] (Text) (VectorThese vectors allow machines to understand semantic similarity.Embedding Models are heavily used in: Semantic Search, Recommendation Systems, RAG Applications, Vector DatabasesLanguage ModelWhat are LLMs?General-purpose models that are used for raw text generation. They take a string (plain text) and return a string (plain text). These are old traditional models and are not used much now.Input: "What is the capital of Japan?"Output: Tokyo is the capital of Japan.Using OpenAI LLM: The following code uses OpenAI’s traditional completion model.Input:from langchain_openai import OpenAIfrom dotenv import load_dotenvload_dotenv()llm = OpenAI(model="gpt-3.5-turbo-instruct")result = llm.invoke("What is the capital of Japan?")print(result)Explanation:OpenAI() creates an LLM object.invoke() sends a text prompt.The model returns plain text.Output:Tokyo is the capital of Japan.What are Chat Models?Language models that are specialized for conversational tasks. They take a sequence of messages as input and return chat messages as output ( as opposed to using plain text). These are traditionally newer models and are used more in comparison to the LLMsChat Models understand roles such as: System, User, AssistantThis makes them ideal for: Chatbots, AI Assistants, Agents, Customer Support SystemsOpenAI Chat Model: The following example uses GPT-4 through LangChain.from langchain_openai import ChatOpenAIfrom dotenv import load_dotenvload_dotenv()model = ChatOpenAI( model="gpt-4", temperature=0.9)result = model.invoke( "What is the capital of Japan?")print(result.content)Understanding Temperature: Temperature controls randomness.0.0 → Deterministic0.5 → Balanced1.0 → CreativeLower values produce predictable outputs while higher values generate more diverse responses.2. Google Gemini Chat Model: LangChain provides a unified interface for Google’s Gemini models.from langchain_google_genai import ChatGoogleGenerativeAIfrom dotenv import load_dotenvload_dotenv()model = ChatGoogleGenerativeAI( model='gemini-1.5-pro')result = model.invoke( 'What is the capital of Japan?')print(result.content)ExplanationEven though the provider changed from OpenAI to Google, the interface remains almost identical.This is one of the biggest advantages of LangChain.3. Anthropic Claude Chat Model: Claude can be integrated in the same way.from langchain_anthropic import ChatAnthropicfrom dotenv import load_dotenvload_dotenv()model = ChatAnthropic( model='claude-3-5-sonnet-20241022')result = model.invoke( 'What is the capital of Japan?')print(result.content)Notice that only the provider changes while the LangChain workflow remains the same.4. Hugging Face API Modelfrom huggingface_hub import InferenceClientfrom dotenv import load_dotenvimport osload_dotenv()client = InferenceClient( api_key=os.getenv("HUGGINGFACEHUB_API_TOKEN"))result = client.chat_completion( model="meta-llama/Llama-3.1-8B-Instruct", messages=[ { "role": "user", "content": "What is the capital of Japan?" } ])print( result.choices[0].message.content)ExplanationHere we use Meta’s Llama model through Hugging Face’s hosted inference API.5. Running Hugging Face LocallyInstead of paying for APIs, you can run open-source models on your own machinefrom langchain_huggingface import ( ChatHuggingFace, HuggingFacePipeline)llm = HuggingFacePipeline.from_model_id( model_id='TinyLlama/TinyLlama-1.1B-Chat-v1.0', task='text-generation', pipeline_kwargs={ "temperature": 0.5, "max_new_tokens": 100 })model = ChatHuggingFace(llm=llm)result = model.invoke( "What is the capital of Japan?")print(result.content)Why Run Locally?Better privacyNo API costFull control over the modelEmbedding ModelsWhile Language Models generate text, Embedding Models generate vectors.OpenAI Embedding Model: Embedding a query using OpenAI.from langchain_openai import OpenAIEmbeddingsembedding = OpenAIEmbeddings( model='text-embedding-3-large', dimensions=32)result = embedding.embed_query( "Tokyo is the capital of Japan.")print(result)output: [0.12, -0.43, 0.89, ...]2. Embedding Multiple Documents: We can embed multiple documents simultaneouslyfrom langchain_openai import OpenAIEmbeddingsembedding = OpenAIEmbeddings( model='text-embedding-3-large', dimensions=32)documents = [ "Tokyo is the capital of Japan.", "Osaka is the second largest city in Japan.", "Japan is famous for its technology and culture."]result = embedding.embed_documents( documents)print(result)3. Hugging Face Embeddings: Open-source embeddings can also be generated locally.from langchain_huggingface import HuggingFaceEmbeddingsembedding = HuggingFaceEmbeddings( model_name='sentence-transformers/all-MiniLM-L6-v2')documents = [ "Tokyo is the capital of Japan." "Osaka is the second-largest city in Japan." "Japan is famous for its technology and culture."]result = embedding.embed_documents(documents)print(result)LLM vs Chat Model vs Embedding ModelReal-World Example: Finding the Most Relevant Document Using EmbeddingsOne of the most powerful applications of Embedding Models is Semantic Search.Unlike traditional keyword search, semantic search focuses on the meaning of the text rather than exact word matches.Let’s see this in action.from langchain_openai import OpenAIEmbeddingsfrom dotenv import load_dotenvfrom sklearn.metrics.pairwise import cosine_similarityload_dotenv()embedding = OpenAIEmbeddings( model='text-embedding-3-large', dimensions=300)documents = [ "LangChain helps developers build applications powered by large language models.", "RAG improves LLM responses by retrieving relevant information from external documents.", "Vector databases store embeddings and enable semantic search.",]query = "How does RAG help AI applications?"doc_embeddings = embedding.embed_documents(documents)query_embedding = embedding.embed_query(query)scores = cosine_similarity( [query_embedding], doc_embeddings)[0]index, score = sorted( list(enumerate(scores)), key=lambda x: x[1])[-1]print("Query:", query)print("Most Relevant Document:")print(documents[index])print("Similarity Score:", score)Step 1: Convert Documents into Vectors: The embedding model transforms each document into a numerical representation called a vector."LangChain helps developers build applications powered by large language models." ↓[0.42, -0.18, 0.67, ...]"RAG improves LLM responses by retrieving relevant information from external documents." ↓[0.31, 0.54, -0.22, ...]"Vector databases store embeddings and enable semantic search." ↓[0.76, -0.09, 0.44, ...]These vectors capture the semantic meaning of the text rather than just individual keywords.Step 2: Convert the Query into a Vector: Suppose the user asks:How does RAG help AI applications?The query is also converted into a vector using the same embedding model.Query ↓Embedding Model ↓Query VectorNow both the documents and the query exist in the same vector space, allowing us to compare their meanings mathematically.Step 3: Calculate Similarity: We use Cosine Similarity to measure how closely the query vector matches each document vector.scores = cosine_similarity( [query_embedding], doc_embeddings)[0]A higher similarity score indicates that the document is more relevant to the query.Expected Output:Query: How does RAG help AI applications?Most Relevant Document:RAG improves LLM responses by retrieving relevant information from external documents.Similarity Score: 0.92The exact similarity score may vary depending on the embedding model used.Why This is PowerfulNotice that the query is:How does RAG help AI applications?while the document contains:RAG improves LLM responses by retrieving relevant information from external documents.The query does not exactly match the document text, yet the embedding model understands that both are discussing the same concept: how RAG enhances the performance of language models by providing relevant external knowledge.Traditional keyword-based search relies heavily on exact word matches, whereas embeddings capture the underlying meaning of the text. This allows semantic search systems to retrieve relevant information even when different wording is used.This ability to understand meaning rather than exact keywords is what makes embeddings the foundation of modern RAG systems, AI search engines, recommendation systems, and intelligent knowledge retrieval applications.ConclusionModels are the foundation of every LangChain application.LLMs generate text from text.Chat Models power conversational AI systems.Embedding Models convert text into vectors for semantic understanding.Together, these models enable the creation of chatbots, AI assistants, semantic search engines, and Retrieval-Augmented Generation (RAG) applications.In the next article, we’ll explore Prompts in LangChain and learn how to control model behavior using Prompt Templates, Chat Prompts, and Dynamic Prompt Engineering.If you found this article helpful, consider following me for more such contentConnect with me on LinkedIn: https://www.linkedin.com/in/atulkumar8/🚀 LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.