### Install langchain-dev-utils via pip
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Use pip to install the core package or the full-featured version with optional dependencies. This command works on Python 3.11 and later. No additional setup is required beyond a working Python environment.
```bash
pip install -U langchain-dev-utils
# Install the full-featured version:
pip install -U langchain-dev-utils[standard]
```
--------------------------------
### Register and Load a Chat Model Provider (Python)
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Demonstrates how to register a custom chat model provider (e.g., vLLM) and then load a specific model using the library's utilities. The example prints a simple invocation result. Requires the `langchain-dev-utils` package installed.
```python
from langchain_dev_utils.chat_models import (
register_model_provider,
load_chat_model,
)
# Register the model provider
register_model_provider(
provider_name="llm",
chat_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
# Load the model
model = load_chat_model("vllm:qwen3-4b")
print(model.invoke("Hello"))
```
--------------------------------
### Load Embedding Model and Embed Query
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Loads an embedding model and uses it to generate an embedding for a given text query. This snippet demonstrates the initial setup for text embedding.
```python
from langchain_dev_utils.embeddings import load_embeddings
# Load the embedding model
embeddings = load_embeddings("vllm:qwen3-embedding-4b")
emb = embeddings.embed_query("Hello")
print(emb)
```
--------------------------------
### Parallel Pipeline Orchestration
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Illustrates the setup for parallel graph orchestration using `parallel_pipeline`. This function allows combining state graphs to run in parallel. It requires a list of sub-graphs, a state schema, and a function to define parallel execution branches.
```python
from langchain_dev_utils.pipeline import parallel_pipeline
# Example usage would go here, defining sub_graphs, state_schema, and branches_fn
```
--------------------------------
### Batch Register Multiple Chat Model Providers (Python)
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Streamline application setup by registering multiple chat model providers simultaneously. This function accepts a list of dictionaries, where each dictionary defines a provider configuration, including its name, class, or API details. This is useful when an application needs to interact with various model services.
```python
from langchain_dev_utils.chat_models import (
batch_register_model_provider,
load_chat_model,
)
from langchain_core.language_models.fake_chat_models import FakeChatModel
# Register multiple providers in a single call
batch_register_model_provider([
{
"provider": "fakechat",
"chat_model": FakeChatModel,
},
{
"provider": "vllm",
"chat_model": "openai-compatible",
"base_url": "http://localhost:8000/v1",
},
])
# Use any registered provider
fake_model = load_chat_model("fakechat:test-model")
vllm_model = load_chat_model("vllm:qwen3-4b")
response = vllm_model.invoke("Hello, how are you?")
print(response.content)
```
--------------------------------
### Parallel Pipeline with Langchain Dev Utils
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Enables the creation of parallel multi-agent pipelines where agents execute concurrently. This example shows the import for `parallel_pipeline` and `create_agent`, suggesting concurrent execution capabilities. Further implementation details would be needed to define the parallel execution logic.
```python
from langchain_dev_utils.pipeline import parallel_pipeline
from langchain_dev_utils.agents import create_agent
from langchain.agents import AgentState
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
from langgraph.types import Send
# Example placeholder for parallel pipeline setup
# Further implementation would define the agents and their parallel execution logic.
```
--------------------------------
### Agent Orchestration with Summarization and Plan Middleware
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Demonstrates how to create an agent with PlanMiddleware for planning and SummarizationMiddleware for summarization. It takes agent configuration and user messages as input and outputs the agent's response. Requires langchain-dev-utils and a compatible model provider like vLLM.
```python
from langchain_dev_utils.agents.middleware import (
SummarizationMiddleware,
PlanMiddleware,
)
agent=create_agent(
"vllm:qwen3-4b",
name="plan-agent",
middleware=[PlanMiddleware(), SummarizationMiddleware(model="vllm:qwen3-4b")]
)
response = agent.invoke({"messages": [{"role": "user", "content": "Give me a travel plan to New York"}]}))
print(response)
```
--------------------------------
### Sequential Pipeline Orchestration with Multiple Agents
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Builds a sequential pipeline of agents using `sequential_pipeline`. Each agent is designed for a specific task (time, weather, user queries) and uses the vLLM model provider. The pipeline takes a list of agents and a state schema, then invokes the pipeline with initial messages.
```python
from langchain.agents import AgentState
from langchain_core.messages import HumanMessage
from langchain_dev_utils.agents import create_agent
from langchain_dev_utils.pipeline import sequential_pipeline
from langchain_dev_utils.chat_models import register_model_provider
register_model_provider(
provider_name="vllm",
chat_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
# Build a sequential pipeline (all sub-graphs execute in order)
graph = sequential_pipeline(
sub_graphs=[
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_time],
system_prompt="You are a time query assistant. You can only answer the current time. If the question is unrelated to time, please directly respond that you cannot answer.",
name="time_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_weather],
system_prompt="You are a weather query assistant. You can only answer the current weather. If the question is unrelated to weather, please directly respond that you cannot answer.",
name="weather_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_user],
system_prompt="You are a user query assistant. You can only answer the current user. If the question is unrelated to users, please directly respond that you cannot answer.",
name="user_agent",
),
],
state_schema=AgentState,
)
response = graph.invoke({"messages": [HumanMessage("Hello")]})
print(response)
```
--------------------------------
### Build LangChain Parallel Pipeline with Multiple Agents
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Demonstrates building a parallel pipeline with multiple specialized agents using the langchain-dev-utils library. Creates three agents (time, weather, user) that execute concurrently, each with domain-specific tools and system prompts. The pipeline is invoked with a message and returns aggregated responses from all agents.
```python
graph = parallel_pipeline(
sub_graphs=[
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_time],
system_prompt="You are a time query assistant. You can only answer the current time. If the question is unrelated to time, please directly respond that you cannot answer.",
name="time_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_weather],
system_prompt="You are a weather query assistant. You can only answer the current weather. If the question is unrelated to weather, please directly respond that you cannot answer.",
name="weather_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_user],
system_prompt="You are a user query assistant. You can only answer the current user. If the question is unrelated to users, please directly respond that you cannot answer.",
name="user_agent",
),
],
state_schema=AgentState,
)
response = graph.invoke({"messages": [HumanMessage("Hello")]})
print(response)
```
--------------------------------
### Create Langchain Agent with Extended Model Support
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Creates a Langchain agent using an extended `create_agent` function that supports models loadable via `load_chat_model` in addition to standard `BaseChatModel` instances. Requires `AgentState` from `langchain.agents` and a `tool` definition.
```python
from langchain_dev_utils.agents import create_agent
from langchain.agents import AgentState
from langchain_core.tools import tool
import datetime
@tool
def get_current_time() -> str:
"""Get the current timestamp"""
return str(datetime.datetime.now().timestamp())
# Assuming 'model' can be loaded via load_chat_model (e.g., "vllm:qwen3-4b")
# agent = create_agent("vllm:qwen3-4b", tools=[get_current_time], name="time-agent")
# response = agent.invoke({"messages": [{"role": "user", "content": "What time is it?"}]})
# print(response)
```
--------------------------------
### Sequential Pipeline with Langchain Dev Utils
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Creates sequential multi-agent pipelines where agents execute one after another. This utilizes `sequential_pipeline` and `create_agent` from langchain_dev_utils. It requires defining specialized tools, agents, and a state schema.
```python
from langchain_dev_utils.pipeline import sequential_pipeline
from langchain_dev_utils.agents import create_agent
from langchain.agents import AgentState
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
import datetime
# Define specialized tools
@tool
def get_current_time() -> str:
"""Get current time"""
return str(datetime.datetime.now())
@tool
def get_current_weather(city: str) -> str:
"""Get current weather"""
return f"Weather in {city}: Sunny"
@tool
def get_current_user() -> str:
"""Get current user"""
return "User: John Doe"
# Create sequential pipeline
graph = sequential_pipeline(
sub_graphs=[
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_time],
system_prompt="You are a time assistant. Only answer time-related questions.",
name="time_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_weather],
system_prompt="You are a weather assistant. Only answer weather questions.",
name="weather_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_user],
system_prompt="You are a user assistant. Only answer user-related questions.",
name="user_agent",
),
],
state_schema=AgentState,
graph_name="sequential_agents_pipeline",
)
# Execute sequential pipeline
response = graph.invoke({
"messages": [HumanMessage("Hello, I need time, weather, and user info")]
})
# Each agent processes in sequence
for msg in response["messages"]:
print(f"{msg.type}: {msg.content[:100]}")
```
--------------------------------
### Create Agents with String Model Specification
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Creates LangGraph agents using a string-based model specification. This function requires registering a model provider and defining tools. It takes model name, tools, system prompt, and agent name as input and returns an agent instance.
```python
from langchain_dev_utils.agents import create_agent
from langchain_dev_utils.chat_models import register_model_provider
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage
import datetime
# Register model provider
register_model_provider(
provider_name="vllm",
chat_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
# Define tools
@tool
def get_current_time() -> str:
"""Get current time"""
return str(datetime.datetime.now().timestamp())
@tool
def get_current_weather(city: str) -> str:
"""Get current weather for a city"""
return f"Weather in {city}: Sunny, 72°F"
# Create agent with string model specification
agent = create_agent(
"vllm:qwen3-4b",
tools=[get_current_time, get_current_weather],
system_prompt="You are a helpful assistant.",
name="weather-time-agent"
)
# Invoke agent
response = agent.invoke({
"messages": [HumanMessage("What's the time and weather in Paris?")]
})
# Access response
print(response["messages"][-1].content)
```
--------------------------------
### Human-in-the-Loop Tool Calling with Decorators in Python
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
This Python code demonstrates how to add human approval or editing to tool calls using decorators. It supports both synchronous and asynchronous tools, allowing for custom handlers to manage user interactions. Dependencies include `langchain_dev_utils.tool_calling`, `langchain_core.tools`, `langgraph.types`, and `asyncio`.
```python
from langchain_dev_utils.tool_calling import (
human_in_the_loop,
human_in_the_loop_async,
InterruptParams,
)
from langchain_core.tools import tool
from langgraph.types import interrupt
import datetime
import asyncio
# Synchronous tool with default handler
@human_in_the_loop
@tool
def get_current_time() -> str:
"""Get current timestamp"""
return str(datetime.datetime.now().timestamp())
# Custom handler for more control
def custom_handler(params: InterruptParams):
response = interrupt(
f"About to call '{params['tool_call_name']}' with args: {params['tool_call_args']}. Approve?"
)
if response["type"] == "accept":
return params["tool"].invoke(params["tool_call_args"])
elif response["type"] == "edit":
return params["tool"].invoke(response["args"])
else:
return "Tool call rejected by user"
@human_in_the_loop(handler=custom_handler)
@tool
def sensitive_operation(data: str) -> str:
"""Perform sensitive operation on data"""
return f"Processed: {data}"
# Async tool with human-in-the-loop
@human_in_the_loop_async
@tool
async def async_fetch_data(url: str) -> str:
"""Asynchronously fetch data from URL"""
await asyncio.sleep(1)
return f"Data from {url}"
# Use with agent
from langchain_dev_utils.agents import create_agent
agent = create_agent(
"vllm:qwen3-4b",
tools=[get_current_time, sensitive_operation],
name="approval-agent"
)
```
--------------------------------
### Basic Parallel Pipeline with Agents
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
This snippet creates a parallel pipeline graph with three specialized agents for time, weather, and user information, allowing concurrent execution. It depends on LangChain-Dev-Utils functions like parallel_pipeline and create_agent, along with custom tools and a VLLM model. Inputs are messages to invoke the graph, producing a response aggregating agent outputs; limitations include assuming predefined tools and state schema.
```python
graph = parallel_pipeline(
sub_graphs=[
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_time],
system_prompt="You are a time assistant.",
name="time_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_weather],
system_prompt="You are a weather assistant.",
name="weather_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_user],
system_prompt="You are a user assistant.",
name="user_agent",
),
],
state_schema=AgentState,
graph_name="parallel_agents_pipeline",
)
# Execute parallel pipeline - all agents run concurrently
response = graph.invoke({
"messages": [HumanMessage("Get all available information")]
})
```
--------------------------------
### Register an Embedding Model Provider (Python)
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Shows how to register an embedding model provider such as vLLM for use with LangChain utilities. After registration, the provider can be referenced when loading embeddings elsewhere in the code. The snippet only covers registration.
```python
from langchain_dev_utils.embeddings import register_embeddings_provider, load_embeddings
# Register the embedding model provider
register_embeddings_provider(
provider_name="vllm",
embeddings_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
```
--------------------------------
### Dynamic Parallel Pipeline with Branching
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
This code defines a dynamic branching function to selectively route messages to agents and builds a parallel pipeline that invokes agents based on the branch logic. Dependencies include LangChain-Dev-Utils for pipeline creation, custom tools, and VLLM model integration. Inputs are initial messages triggering the dynamic branch, yielding targeted responses; it supports conditional agent execution but requires a custom branches_fn implementation.
```python
def dynamic_branch_fn(state):
"""Dynamically determine which agents to run"""
return [
Send("weather_agent", {"messages": [HumanMessage("Get weather in NYC")]}),
Send("time_agent", {"messages": [HumanMessage("Get current time")]}),
]
dynamic_graph = parallel_pipeline(
sub_graphs=[
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_time],
name="time_agent",
),
create_agent(
model="vllm:qwen3-4b",
tools=[get_current_weather],
name="weather_agent",
),
],
state_schema=AgentState,
branches_fn=dynamic_branch_fn,
graph_name="dynamic_parallel_pipeline",
)
response = dynamic_graph.invoke({
"messages": [HumanMessage("Hello")]
})
```
--------------------------------
### Format List Content with Options
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Formats a list of items (messages, documents, or strings) into a single string with custom separators and optional numbering. Utilizes the `format_sequence` function.
```python
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, ToolMessage
from langchain_core.documents import Document
from langchain_dev_utils.message_conversion import format_sequence
# Example with strings
text_formatted = format_sequence([
"str1",
"str2",
"str3"
], separator="\n", with_num=True)
# Example with mixed types (uncomment to run)
# mixed_content = [
# HumanMessage(content="User query"),
# Document(page_content="Document content"),
# "A simple string",
# AIMessage(content="AI response")
# ]
# formatted_mixed = format_sequence(mixed_content, separator="---")
# print(text_formatted)
```
--------------------------------
### Format Sequences with Langchain Dev Utils
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Formats lists of messages, documents, or strings into structured text. Supports custom separators and optional numbering. Requires langchain_dev_utils.message_convert and relevant langchain core components.
```python
from langchain_dev_utils.message_convert import format_sequence
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.documents import Document
# Format messages
messages = [
HumanMessage(content="What is AI?"),
AIMessage(content="AI is artificial intelligence."),
HumanMessage(content="How does it work?"),
]
formatted_messages = format_sequence(messages, separator="\n---\n", with_num=True)
print(formatted_messages)
# Output: "---\n1. What is AI?\n---\n2. AI is artificial intelligence.\n---\n3. How does it work?"
# Format documents
documents = [
Document(page_content="First paragraph of text."),
Document(page_content="Second paragraph of text."),
Document(page_content="Third paragraph of text."),
]
formatted_docs = format_sequence(documents, separator="\n\n", with_num=False)
print(formatted_docs)
# Format strings
items = ["Item one", "Item two", "Item three"]
formatted_list = format_sequence(items, separator="\n", with_num=True)
print(formatted_list)
# Output: "-\n1. Item one\n-\n2. Item two\n-\n3. Item three"
```
--------------------------------
### Batch Register Multiple Embedding Providers (Python)
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Register multiple embedding model providers simultaneously using a list of configuration dictionaries. This is beneficial for applications that require switching between or utilizing different embedding models. Once registered, providers can be loaded and used for embedding queries or documents.
```python
from langchain_dev_utils.embeddings import (
batch_register_embeddings_provider,
load_embeddings,
)
from langchain_core.embeddings.fake import FakeEmbeddings
# Register multiple embedding providers
batch_register_embeddings_provider([
{
"provider": "fakeembeddings",
"embeddings_model": FakeEmbeddings,
},
{
"provider": "vllm",
"embeddings_model": "openai-compatible",
"base_url": "http://localhost:8000/v1",
},
])
# Use different providers as needed
fake_emb = load_embeddings("fakeembeddings:test-model", size=1024)
vllm_emb = load_embeddings("vllm:qwen3-embedding-4b")
query = "semantic search example"
result = vllm_emb.embed_query(query)
print(f"Query embedding generated: {len(result)} dimensions")
```
--------------------------------
### Convert Reasoning Content in Python
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
These Python functions convert model reasoning content into visible text, allowing for custom tags around internal thoughts or explanations. It supports converting reasoning in complete messages, synchronous streaming chunks, and asynchronous streaming chunks. Dependencies include `langchain_dev_utils.message_convert` and `langchain_dev_utils.chat_models`.
```python
from langchain_dev_utils.message_convert import (
convert_reasoning_content_for_ai_message,
convert_reasoning_content_for_chunk_iterator,
aconvert_reasoning_content_for_chunk_iterator,
)
from langchain_dev_utils.chat_models import load_chat_model
model = load_chat_model("vllm:qwen3-4b")
# Convert reasoning in complete message
response = model.invoke("Explain quantum entanglement")
response_with_reasoning = convert_reasoning_content_for_ai_message(
response,
think_tag=("", "")
)
print(response_with_reasoning.content)
# Output: "[internal reasoning]Quantum entanglement is..."
# Convert reasoning in streaming chunks
for chunk in convert_reasoning_content_for_chunk_iterator(
model.stream("Solve this math problem: 2+2"),
think_tag=קל("", "")
):
print(chunk.content, end="", flush=True)
# Async streaming with reasoning
async def process_async_stream():
async for chunk in aconvert_reasoning_content_for_chunk_iterator(
model.astream("Explain relativity"),
think_tag=קל("", "")
):
print(chunk.content, end="", flush=True)
# import asyncio
# asyncio.run(process_async_stream())
```
--------------------------------
### Apply Human-in-the-Loop to Tool Functions
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Decorators (`human_in_the_loop` for sync, `human_in_the_loop_async` for async) that enable pausing execution of tool functions to allow for human intervention or custom handling. Requires `datetime` and `tool` from `langchain_core.tools`.
```python
from langchain_dev_utils import human_in_the_loop
from langchain_core.tools import tool
import datetime
@human_in_the_loop
@tool
def get_current_time() -> str:
"""Get the current timestamp"""
return str(datetime.datetime.now().timestamp())
```
--------------------------------
### Merge Streaming Chunks into AIMessage in Python
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
This Python utility merges multiple streaming `AIMessageChunk` objects into a single `AIMessage`. This simplifies processing by consolidating fragmented responses. It requires `langchain_dev_utils.message_convert` and `langchain_dev_utils.chat_models` for loading the chat model.
```python
from langchain_dev_utils.message_convert import merge_ai_message_chunk
from langchain_dev_utils.chat_models import load_chat_model
model = load_chat_model("vllm:qwen3-4b")
# Collect streaming chunks
chunks = []
for chunk in model.stream("Write a short poem about AI"):
chunks.append(chunk)
print(chunk.content, end="", flush=True)
# Merge into single message
merged_message = merge_ai_message_chunk(chunks)
print(f"\n\nFull response: {merged_message.content}")
print(f"Token usage: {merged_message.response_metadata}")
```
--------------------------------
### Register and Load Custom Chat Model Provider (Python)
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Register a custom chat model provider, such as a vLLM deployed model with an OpenAI-compatible API, and then load it for use. This allows extending LangChain's built-in model support. It takes a provider name, chat model identifier, and optionally a base URL. The loaded model can then be invoked for generating responses.
```python
from langchain_dev_utils.chat_models import (
register_model_provider,
load_chat_model,
)
# Register a vLLM-deployed model with OpenAI-compatible API
register_model_provider(
provider_name="vllm",
chat_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
# Load and use the registered model
model = load_chat_model("vllm:qwen3-4b", temperature=0.7)
response = model.invoke("What is the capital of France?")
print(response.content)
# Output: "The capital of France is Paris."
# Alternative: Load with separate provider parameter
model = load_chat_model("qwen3-4b", model_provider="vllm", temperature=0.5)
response = model.invoke("Explain quantum computing in simple terms")
print(response.content)
```
--------------------------------
### Register and Load Custom Embedding Provider (Python)
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
Register custom embedding model providers to integrate with any OpenAI-compatible embedding API or custom embedding class. The function takes a provider name, embedding model identifier, and an optional base URL. After registration, embeddings can be generated for single queries or batches of documents.
```python
from langchain_dev_utils.embeddings import (
register_embeddings_provider,
load_embeddings,
)
# Register a vLLM-deployed embedding model
register_embeddings_provider(
provider_name="vllm",
embeddings_model="openai-compatible",
base_url="http://localhost:8000/v1",
)
# Load and use the embedding model
embeddings = load_embeddings("vllm:qwen3-embedding-4b")
embedding_vector = embeddings.embed_query("Hello world")
print(f"Embedding dimension: {len(embedding_vector)}")
# Output: "Embedding dimension: 4096"
# Batch embed multiple documents
documents = ["First document", "Second document", "Third document"]
doc_embeddings = embeddings.embed_documents(documents)
print(f"Embedded {len(doc_embeddings)} documents")
```
--------------------------------
### Check and Parse Tool Calls in Python
Source: https://context7.com/tbice123123/langchain-dev-utils/llms.txt
This Python code checks if an AI message contains tool calls and extracts tool information. It utilizes functions from `langchain_dev_utils.tool_calling` to parse single or multiple tool calls from a model's response. Dependencies include `langchain_core.tools` and `langchain_dev_utils.chat_models`.
```python
import datetime
from langchain_core.tools import tool
from langchain_dev_utils.tool_calling import (
has_tool_calling,
parse_tool_calling,
)
from langchain_dev_utils.chat_models import load_chat_model
@tool
def get_current_time() -> str:
"""Get the current timestamp"""
return str(datetime.datetime.now().timestamp())
# Register and load model
model = load_chat_model("vllm:qwen3-4b")
bound_model = model.bind_tools([get_current_time])
# Invoke with a tool-requiring query
response = bound_model.invoke("What time is it?")
# Check for tool calls
if has_tool_calling(response):
# Parse first tool call
tool_name, tool_args = parse_tool_calling(response, first_tool_call_only=True)
print(f"Tool called: {tool_name}")
print(f"Arguments: {tool_args}")
# Output: Tool called: get_current_time
# Arguments: {}
# Parse all tool calls (if multiple)
all_tool_calls = parse_tool_calling(response)
for name, args in all_tool_calls:
print(f"Tool: {name}, Args: {args}")
```
--------------------------------
### Check and Parse Tool Calls in AIMessage
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Provides functions to determine if an AIMessage contains tool calls (`has_tool_calling`) and to extract the tool name and arguments (`parse_tool_calling`). Useful for agents and function calling.
```python
import datetime
from langchain_core.tools import tool
from langchain_core.messages import AIMessage
from langchain_dev_utils.tool_calling import has_tool_calling, parse_tool_calling
# Assume 'model' is an initialized Langchain model
# @tool
# def get_current_time() -> str:
# """Get the current timestamp"""
# return str(datetime.datetime.now().timestamp())
# response = model.bind_tools([get_current_time]).invoke("What time is it?")
# if isinstance(response, AIMessage) and has_tool_calling(response):
# name, args = parse_tool_calling(
# response, first_tool_call_only=True
# )
# print(f"Tool: {name}, Args: {args}")
# else:
# print("No tool call found or response is not an AIMessage.")
```
--------------------------------
### Merge Streamed AI Message Chunks
Source: https://github.com/tbice123123/langchain-dev-utils/blob/master/README.md
Merges a list of AIMessageChunk objects into a single AIMessage, typically used for processing streamed responses from a model. Requires the `merge_ai_message_chunk` function.
```python
from langchain_core.messages import AIMessageChunk
from langchain_dev_utils.message_conversion import merge_ai_message_chunk
# Assume 'model' is an initialized Langchain model with a stream method
# chunks = list(model.stream("Hello"))
# merged = merge_ai_message_chunk(chunks)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.