Back to topics

03 Basic Usage of LangChain and Python Basics

Basic Calls of LangChain

LangChain currently supports three types of models:

  1. LLMs (Large Language Models): A general term in technology, referring to Transformer architecture models trained on massive parameters and large volumes of text. Their core capability is understanding and generating natural language.

  2. Chat Models: A subdivision within the application domain, LLMs optimized for dialogue scenarios. Their core capability is simulating turn-based human conversation interactions, mainly serving chat scenarios.

  3. Text Embedding Models: They accept text as input and output vector representations of the text.

from langchain_community.llms.tongyi import Tongyi

# Do not use qwen3-max, because qwen3-max is a chat model, while qwen-max is a large language model
# The content here might be outdated; let's learn it for now
model = Tongyi(model="qwen-max")

# Call the invoke method to ask the model a question; this outputs the complete result at once
res = model.invoke(input="Hello")
print(res)

# Call the stream method to ask the model a question; it returns results in chunks, streaming output
res = model.stream(input="hi")
for chunk in res:
	# print adds a newline character \n by default; to concatenate strings, we use end=""
	# print() by default buffers the content and only flushes when the buffer is full
	# flush=True means force immediate output without buffering, showing characters as they come.
	print(chunk, end="", flush=True)

Basic Usage

model = ChatTongyi(model="qwen3-max")
# Now it's recommended to use system, user, assistant roles
# instead of system, human, ai
messages = [
	("system", "You are a frontier poet"),
	("user", "Write a Tang poem"),
	("assistant","At noon they weed with hoes; their sweat drips on the soil"),
	("user","Based on the format of the previous reply, write another Tang poem")
]

for chunk in model.stream(input = message):
	print(chunk.content, end="", flush=True)

Prompt Templates

Similar to template strings in TypeScript. They are divided into one-shot prompt templates and few-shot prompt templates.

from langchain_core.prompts import PromptTemplate
from langchain_community.llms.tongyi import Tongyi

# To be used in a chain, not just a template string
# one-shot
prompt_template = PromptTemplate.from_template(
	"My neighbor's surname is {lastname} and just had a {gender}. Please help me come up with a name."
)
# Inject prompt
prompt_text = prompt_template.format(lastname="Zhang", gender="daughter")

# few-shot
example_template = PromptTemplate.from_template("Word: {word}, Antonym: {antonym}")
example_data = [
	{"word": "big", "antonym": "small"},
	{"word": "up", "antonym": "down"}
]
few_shot_prompt = FewShotPromptTemplate(
	example_prompt=example_template,
	examples=example_data,
	prefix="Give the antonym of the given word. Examples are as follows:",
	suffix="Based on the examples, tell me: what is the antonym of {input_word}?",
	input_variables=['input_word']
)
# Final prompt
prompt_text = few_shot_prompt.invoke(input={"input_word":"left"}).to_string()

model = Tongyi("qwen-max")
res = model.invoke(input = prompt_text)

# PromptTemplate can be added to a chain
chain = prompt_template | model
chain.invoke(input = {"lastname": "Zhang" , "gender": "daughter"})

From TypeScript’s Perspective on Python

Q: Does Python not need await when calling asynchronous functions?

A: model.invoke(...) is a synchronous call, so no await is needed; the underlying implementation handles it. However, if you use an asynchronous interface, you would need await.

Q: Does Python require explicit parameter names when passing arguments?

A: No. Python supports both positional and keyword arguments. You can even mix them in the same function call. The community recommendation is to use keyword arguments as much as possible for better readability.

def greet(greeting, name):
    print(f"{greeting}, {name}")

# Positional arguments
greet("Hello", "Li")     # Hello, Li

# Keyword arguments
greet(name="Li", greeting="Hello")

# Mixed (positional must come before keyword)
greet("Hello", name="Li")

Q: Python’s from module import something is the opposite of TypeScript’s import something from module. How does the community view this?

A: Some joke that "TypeScript programmers will definitely write it backwards in their first week of Python", but seriously, the Python community feels that the word order of from module import something aligns more with natural language — "take something from module". The design philosophies differ; neither is right or wrong.

Q: How do you write comments in Python? I see some use # and others use """. What’s the difference? Do comments inside loops also need leading spaces?

A: # is a true comment. The interpreter ignores it completely. """ is a string literal, not a comment. It essentially creates a string that is not assigned to any variable. Because it "writes but doesn't affect execution", it looks like a comment. It’s usually used for multi-line documentation. Docstrings written with """ can be retrieved via .__doc__. Comments inside loops/functions need leading spaces because Python uses indentation to define code blocks. Comments follow the code and must align with the indentation of the enclosing block.

def greet(name):
    """Greets someone"""
    return f"Hello {name}"

print(greet.__doc__)  # Output: Greets someone

for i in range(5):
# No indentation → Error: IndentationError: unexpected indent
    print(i)

Q: In Python, can you declare a variable simply by writing the variable name? Is there no distinction between variables and constants?

A: No distinction. Python has no true constants. The community uses all-uppercase names to indicate constants, but it’s just a convention.

Q: Does Python's True need to be capitalized?

A: Python treats True and False as keywords (technically built-in constants), and they are case-sensitive. These built-in constants are actually subclasses of int; True == 1, False == 0, and you can even use them as numbers.

print(True + True)   # 2

Q: Are square brackets arrays? Are arrays type-sensitive? What are the parentheses inside?

A: Yes, they are arrays. In Python, they are called lists. Lists are not type-sensitive; you can put anything in them. For example:

my_list = [42, "hello", True, 3.14, None, [1, 2, 3]]

A: Parentheses () denote tuples, which can be thought of as immutable arrays. Tuples are used in messages because they enforce a fixed message format, semantically indicating that "the two items are bound together and should not be modified separately".

Q: Are Python strings sensitive to quote types? What features do f-strings have?

A: In Python, 'hello' and "hello" are completely equivalent. By prefixing a string with f or F, you can directly write Python expressions inside curly braces {}, which are evaluated at runtime and embedded. F-strings have many features, such as arbitrary expressions, formatting control, dictionary access, debug mode, etc. We'll cover them later.

name = "Asuka"
age = 14
print(f"I am {name}, {age} years old.")
# Output: I am Asuka, 14 years old.