← Writing
AI & Generative AI

LangChain Model I/O Basics

Data Mastery Series — Episode 26: LangChain Website (Part 1)

8 Oct 20247 min readLangChainRAGDashboard
LangChain Series · Part 16 of 19

LangChain Model I/O Basics

Data Mastery Series — Episode 26: LangChain Website (Part 1)

Connect with me and follow our journey: Linkedin, Facebook


Welcome back to the Data Mastery Series! In our previous episodes, we dove into various summarization techniques and explored the power of multimodal AI. Today, let’s switch gears a bit and return to the basics with LangChain, a fantastic tool for connecting with AI language models.

If you’re just joining us, feel free to catch up on earlier episodes to build a solid foundation:

Note: As we dive into LangChain, I’ll be sharing my lecture notes from studying the LangChain documentation. I hope this content proves helpful to you as well!

Reference Source: https://python.langchain.com/v0.1/docs/modules/model%5Fio/

Today, we’ll focus on Model I/O, LangChain’s gateway to utilizing powerful language models. Here are the essential points I’ve gathered from my exploration of LangChain’s documentation.

1. Model I/O

LangChain supports two main model types:

  • Chat Models: These take in a string (text) and return a string as output.
  • Large Language Models (LLMs): These handle a list of messages as input and output.

Example - Chat Models

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

text = "Which purchase should I prioritize first: a car or a house?"
messages = [HumanMessage(content=text)]

chat_model = ChatOpenAI(api_key=openai_api_key, model="gpt-4")
chat_model.invoke(messages)

Output

'''
AIMessage(content="The decision between buying a car or a house first largely depends on your personal needs, financial situation and long-term goals. \n\nIf you live in a city where public transportation is accessible and efficient, you might want to prioritize buying a house first. This could be a better investment in the long run.\n\nHowever, if you live in a place where having a car is essential for commuting to work or other daily activities, then you might prioritize buying a car.\n\nYou also need to consider your financial situation. Do you have enough savings for the down payment on a house? Can you afford the regular maintenance, insurance, and other costs associated with owning a car?\n\nRemember, it's important to not stretch yourself too thin financially. It's always best to consult with a financial advisor before making such big purchase decisions. They can help you analyze your financial health and guide you towards the best decision based on your individual circumstances.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 182, 'prompt_tokens': 20, 'total_tokens': 202, 'completion_tokens_details': {'audio_tokens': None, 'reasoning_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'gpt-4-0613', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-888e592d-5738-459b-9813-475866cc5434-0', usage_metadata={'input_tokens': 20, 'output_tokens': 182, 'total_tokens': 202, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 0}})
'''

Example - LLMs

from langchain_openai import OpenAI

llm = OpenAI(api_key=openai_api_key)
llm.invoke(text)

Output

'''
This decision ultimately depends on your individual circumstances and priorities. Some factors to consider include your financial situation, current living situation, transportation needs, and long-term goals.
If you currently do not own a car and rely on public transportation or other means of transportation, purchasing a car may be a more pressing need. This can provide you with increased mobility and independence, making it easier to commute to work, run errands, and travel.
On the other hand, if you already own a car and are looking to purchase a house, you may want to prioritize saving for a down payment and building your credit score in order to secure a favorable mortgage. Owning a house can provide stability, build equity, and potentially offer tax benefits.
Ultimately, it is important to carefully consider your financial situation and long-term goals before making a decision. It may also be helpful to consult with a financial advisor to determine the best course of action for your specific situation.
'''

Notice how chat_model.invoke(messages) returns a list of messages, while llm.invoke(text) gives a simple string response.

2. Prompt Templates

Often, we don’t directly feed user input to the model. Instead, we use Prompt Templates to add context, helping the model understand our task.

Example - Prompt Templates

from langchain_core.prompts import PromptTemplate

prompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")
formatted_prompt = prompt.format(product="colorful socks")
print(formatted_prompt)

Output

'''
What is a good name for a company that makes colorful socks?
'''

3. Output parsers

Output Parsers allow us to define the format we want our AI response to follow. For example, if we need a list:

Output parsers Example

from langchain.output_parsers import CommaSeparatedListOutputParser

output_parser = CommaSeparatedListOutputParser()
parsed_output = output_parser.parse("hi, bye")
print(parsed_output)

Output

'''
['hi', 'bye']
'''

4. Composing with LangChain Expression Language (LCEL)

LCEL helps streamline the process by connecting inputs, prompt templates, models, and output parsers into one smooth workflow. Here’s a quick example:

Composing with LCEL

from langchain.output_parsers import CommaSeparatedListOutputParser

chat_prompt = ChatPromptTemplate.from_template(template)
chat_prompt = chat_prompt.partial(format_instructions=output_parser.get_format_instructions())
chain = chat_prompt | chat_model | output_parser
chain.invoke({"text": "colors"})

Output

'''
['Red', 'Blue', 'Green', 'Yellow', 'Purple']
'''

In this example, the chat_prompt uses a template to guide the AI, chat_model handles the language model tasks, and output_parser structures the output as a list.

LangChain offers an intuitive way to connect with language models, simplifying tasks like formatting, input handling, and creating smooth workflows. I hope today’s overview helps you get started with the basics of LangChain. In our next episode, we’ll dive even deeper, so stay tuned!

Thank you for reading, and let’s continue building our AI skills together!


Data Science Explore the world of data science with Donato_Story

Dashboard Discover the power of data visualization with Donato_Story

Donato_Journey Join me on my journey (Thai version)

Course_Review Discover the training courses with Donato_Story (Thai version)

I really value your thoughts and feedback. Please share any comments or questions you have below, or reach out to me on:

Medium: medium.com/donato-story
Facebook: web.facebook.com/DonatoStory
Linkedin: linkedin.com/in/nattapong-thanngam

Originally published on Medium

Related