How AI Agents and Tools Transform Operations: A Hands‑On LangChain Guide

This article explores how large AI models can act as autonomous agents equipped with tools, demonstrates practical LangChain examples for remote server queries and RSS parsing, explains the ReAct reasoning‑acting loop, and shows how decorators and object‑oriented patterns enable seamless AI‑driven programming.

Alibaba Cloud Big Data AI Platform
Alibaba Cloud Big Data AI Platform
Alibaba Cloud Big Data AI Platform
How AI Agents and Tools Transform Operations: A Hands‑On LangChain Guide

Introduction

The rise of large AI models is reshaping daily life and work, offering smarter, more efficient ways to solve problems. This series investigates whether such models can be integrated into operations and development to bring greater convenience and value.

True "Tool Person"

In programming slang, a "tool person" refers to an AI model that not only receives commands but can actively use external tools. The common structure is Agent + Tool , where the agent decides what to do and the tool executes the action.

LangChain Agent + Tool Practice

A minimal example shows how to query a remote machine’s uptime using an SSH tool wrapped as a LangChain StructuredTool and an Agent:

import os
from subprocess import Popen, PIPE
from langchain.llms import OpenAI
from langchain.tools import StructuredTool
from langchain.agents import initialize_agent, AgentType

def ssh(command: str, host: str, username: str = "root") -> str:
    """Execute a command on a remote server via SSH and return the output."""
    return os.popen(f"ssh {host} -l{username} '{command}'").read()

agent = initialize_agent(
    [StructuredTool.from_function(ssh)],
    OpenAI(temperature=0),
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)
agent.run("帮我看一下 8.130.35.2 这台机器运行多久了")

The agent first decides it needs the ssh tool, sends a JSON action, receives the uptime output, and finally returns a concise answer.

The agent formulates a thought and selects the ssh tool.

It supplies the uptime command and target host.

The tool returns the raw uptime string.

The agent extracts the relevant part and formats the final answer.

ReAct Process

ReAct (Reasoning and Acting) interleaves Thought , Action , and Observation steps, allowing the model to reason, invoke tools, and incorporate feedback. This loop gives the model explainability and improves reliability.

Complex Thought‑Chain Example: RSS Parsing

A more elaborate scenario uses a Python tool to fetch and parse an RSS feed. The model first writes a script, encounters a SyntaxError, corrects the print statement, re‑executes, and finally returns a list of recent blog titles, links, and dates.

from typing import Dict
import sys, traceback
from io import StringIO
from langchain.llms import OpenAI
from langchain.tools import StructuredTool
from langchain.agents import initialize_agent, AgentType

def python(code_str: str, return_context: bool=False) -> Dict:
    """Execute Python code and return stdout, stderr, and optionally the execution context."""
    stdout = StringIO(); stderr = StringIO(); return_head = 1000
    context = {}
    try:
        with redirect_stdout(stdout), redirect_stderr(stderr):
            exec(code_str, context)
    except Exception:
        stderr.write(traceback.format_exc())
    stdout_value = stdout.getvalue()[:return_head]
    stderr_value = stderr.getvalue()[:return_head]
    if return_context:
        return {"stdout": stdout_value, "stderr": stderr_value, "context": context}
    return {"stdout": stdout_value, "stderr": stderr_value, "context": {}}

agent = initialize_agent([StructuredTool.from_function(python)], OpenAI(temperature=0.3), agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
resp = agent.run("帮我利用工具总结一下 https://elastic.aiops.work/blog/feed 这个xml的博客订最近有什么更新")
print(resp)

The model iteratively refines the script until it successfully extracts the feed items.

Decorator Pattern for Agent + Tool

LangChain also provides @tool and @agent decorators. The example below defines two Kubernetes tools ( k8sLabel and k8sServiceSelectorList) and an agent k8sPodServiceFinder that composes them to locate services related to a pod.

import os, sys
from subprocess import Popen, PIPE
sys.path.insert(0, os.path.split(os.path.realpath(__file__))[0] + "/../../")
from aibond import AI
from langchain import OpenAI
ai = AI()

def popen(command):
    child = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = child.communicate()
    ret = child.wait()
    return ret, out.strip(), err.strip()

@ai.tool()
def k8sLabel(name: str, kind: str, namespace: str) -> str:
    """Fetch labels of a Kubernetes object."""
    cmd = f"kubectl get {kind} {name} -n {namespace} -o jsonpath='{{.metadata.labels}}'"
    ret, out, err = popen(cmd)
    return out

@ai.tool()
def k8sServiceSelectorList(namespace: str) -> str:
    """List all services in a namespace with their label selectors."""
    cmd = f"kubectl get svc -n {namespace} -o jsonpath=\"{{range .items[*]}}{{@.metadata.name}}:{{@.spec.selector}}\
{{end}}\""
    ret, out, err = popen(cmd)
    return out

@ai.agent(tools=["k8sLabel", "k8sServiceSelectorList"], llm=OpenAI(temperature=0.2), verbose=True)
def k8sPodServiceFinder(name: str, namespace: str) -> str:
    """Find services associated with a given pod."""
    return f"帮我列出 {namespace} 这个ns下所有的service,在这个service list中找出与 pod {name} 的label相关的service,返回的结果只有service的名称即可"

a = ai.run("使用所有的工具去查找sreworks这个ns下 prod-health-health-6cbc46567-s6dqp 这个pod的关联的k8s资源", llm=OpenAI(temperature=0.2), agents=["k8sPodServiceFinder"], verbose=True)
print(a)

The decorator approach cleanly separates tool definitions from the agent logic.

Object‑Oriented AI Programming

Beyond functions, class instances can also be turned into tools. The following example wraps an SSH client class as a tool, allowing the agent to first instantiate the client and then execute commands:

import os, sys, paramiko
sys.path.insert(0, os.path.split(os.path.realpath(__file__))[0] + "/../../")
from aibond import AI
from langchain import OpenAI
ai = AI()

class SshClient:
    """Tool that connects to a remote server via SSH and runs commands."""
    def __init__(self, host: str, username: str = "root", password: str = None):
        self._client = paramiko.SSHClient()
        self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self._client.connect(host, username=username, password=password)
    def exec_command(self, command: str) -> dict:
        stdin, stdout, stderr = self._client.exec_command(command)
        return {"stdout": stdout.read().decode('utf-8'), "stderr": stderr.read().decode('utf-8'), "exitStatus": stdout.channel.recv_exit_status()}

resp = ai.run("帮我看看 8.130.35.2 这台机器启动了多久了", llm=OpenAI(temperature=0.2), tools=[SshClient], verbose=True)
print(resp)

The agent first calls the class constructor (action SshClient with __init__), receives an instance_id, then invokes exec_command on that instance to obtain the uptime.

Conclusion

These examples illustrate how large language models can be combined with external tools through the ReAct loop, decorators, and object‑oriented wrappers, enabling powerful, flexible AI‑driven programming workflows. References include the original ReAct paper and the aibond case repository.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAIReactLangChainagentstool
Alibaba Cloud Big Data AI Platform
Written by

Alibaba Cloud Big Data AI Platform

The Alibaba Cloud Big Data AI Platform builds on Alibaba’s leading cloud infrastructure, big‑data and AI engineering capabilities, scenario algorithms, and extensive industry experience to offer enterprises and developers a one‑stop, cloud‑native big‑data and AI capability suite. It boosts AI development efficiency, enables large‑scale AI deployment across industries, and drives business value.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.