跳至主要内容

LangManus:含演示项目的指南

学习如何使用 LangManus 构建多智能体系统,分析一个 GitHub 热门仓库、抓取其提交历史、可视化活动趋势,并生成一份 Markdown 报告。
· 12分钟 阅读

使用 AI 探索

LangManus 是一个开源、由社区驱动的 AI 自动化框架,旨在使用语言模型构建结构化的多智能体系统。借助 LangManus,您可以构建智能体,将规划、研究、编码、浏览器交互和报告整合为一个连贯的流水线。

在本教程中,我将指导您用 LangManus 搭建一个可运行的演示,它可以:

  • 在 GitHub 上找到一个热门开源仓库
  • 抓取最近的提交活动
  • 分析功能更新和贡献模式
  • 生成 Markdown 报告
  • 用多种图表可视化活动趋势

什么是 LangManus?

LangManus 的架构支持精细化控制、可审计性和可扩展性。它构建在以下强大工具之上:

借助 LangManus,您可以构建智能体,将规划、研究、编码、浏览器交互与报告整合到一个由以下要素驱动的统一流水线中:

  • YAML 或 .env 配置模型与密钥。
  • OpenAI 兼容的 LLM API(通过 LiteLLM)。
  • 与 Jina、Tavily 等工具的搜索集成。
  • 支持视觉模型、REPL、浏览器会话与 Markdown 格式化。

LangManus 项目概览:GitHub 仓库分析器 

我们将构建的应用是一个交互式助手,利用 LangManus 的多智能体能力来分析一个热门的 GitHub 仓库。要设置 LangManus 智能体,我们需要一个多文件结构,其中每个文件在多智能体系统中承担不同角色:

  • planner.py:定义任务序列。
  • agent.py:协调各个智能体并维护上下文。
  • agents/:包含用于研究、抓取、分析与报告的专用智能体。
  • streamlit_app.py:包含用于运行流水线并可视化结果的 UI 层。

让我们逐一实现这些组件。

步骤 1:前置条件

在开始之前,请确保已安装以下工具和库:

python3 --version  # Python 3.8+
pip install requests beautifulsoup4 matplotlib streamlit

检查 Python 版本,应至少为 3.8 或更高。然后安装上述其他依赖项。您还需要一个 GitHub API 令牌以避免速率限制,并通过终端将其设置为环境变量。

生成 GitHub 令牌的方法:

  • 访问 GitHub Tokens
  • 点击 Generate New Token 并选择经典版本。不要选择其他选项。
  • 点击 Generate 生成令牌。
  • 复制并安全存储该令牌,它将用于 API 请求的身份验证。

现在,运行以下命令:

export GITHUB_TOKEN=your_personal_token_here

步骤 2:创建规划器与智能体控制器 

依赖已安装完成,接下来为我们的应用构建规划器与智能体控制器。

1. 创建 planner.py 文件

planner.py 定义了一个简单的 4 步计划,覆盖研究、浏览、分析和报告等所需任务。

def plan_task(user_query):
    return [
        {'agent': 'researcher', 'task': 'Find trending repo'},
        {'agent': 'browser', 'task': 'Scrape GitHub activity'},
        {'agent': 'coder', 'task': 'Analyze recent commits and features'},
        {'agent': 'reporter', 'task': 'Generate Markdown report'}
    ]

上述函数为系统返回逐步的任务计划,其中每一步都:

  • 指定负责的智能体(agent);以及
  • 定义该智能体应执行的任务(task)。

2. 创建 agent.py 文件

该文件定义核心的 LangManusAgent 类,用于编排所有智能体,并在它们执行任务时维护共享上下文。

from planner import plan_task
from agents.researcher import find_trending_repo
from agents.browser import scrape_github_activity
from agents.coder import analyze_code_activity
from agents.reporter import generate_report
class LangManusAgent:
    def __init__(self, task):
        self.task = task
        self.context = {}
    def run(self):
        steps = plan_task(self.task)
        for step in steps:
            agent = step['agent']
            task = step['task']
            if agent == 'researcher':
                self.context['repo'] = find_trending_repo()
            elif agent == 'browser':
                self.context['repo_data'] = scrape_github_activity(self.context['repo'])
            elif agent == 'coder':
                self.context['analysis'], self.context['chart_path'] = analyze_code_activity(self.context['repo_data'])
            elif agent == 'reporter':
                report = generate_report(
                    self.context['repo'],
                    self.context['repo_data'],
                    self.context['analysis'],
                    self.context['chart_path']
                )
                print(report)
    def run_and_return(self):
        self.run()
        report = generate_report(
            self.context['repo'],
            self.context['repo_data'],
            self.context['analysis'],
            self.context['chart_path']
        )
        return report, self.context['chart_path']

代码首先调用 plan_task()(在 planner.py 中定义)以获取步骤列表。随后按如下顺序调用相应的专用智能体来运行每个步骤:

  • 由 researcher 智能体获取一个热门 GitHub 仓库。
  • 由 browser 智能体使用 GitHub API 抓取该仓库的提交活动。
  • 由 coder 智能体分析提交数据并生成图表。
  • 由 reporter 智能体将所有内容整理为最终的 Markdown 报告。

每个智能体会将其结果存入 context 字典,便于下游智能体访问并在先前输出之上继续处理。

步骤 3:实现 LangManus 智能体

核心功能就绪后,让我们为应用构建各个智能体。

1. 创建 agents/researcher.py 文件

该智能体通过抓取 GitHub Trending 页面,识别一个热门的开源 Python 项目。

import requests
from bs4 import BeautifulSoup
def find_trending_repo():
    url = "https://github.com/trending/python"
    res = requests.get(url)
    soup = BeautifulSoup(res.text, 'html.parser')
    repo = soup.select_one('article h2 a')['href'].strip()
    return f"https://github.com{repo}"

其工作原理如下:

  • 智能体向 GitHub 仓库页面发送 GET 请求,并使用 BeautifulSoup 解析返回的 HTML 响应。
  • 随后通过 CSS 选择器定位“Trending”下列出的第一个项目,提取仓库 URL 路径(如 /user/repo)。
  • 最后构造并返回完整的 GitHub URL,例如 “https://github.com/user/repo”。

2. 创建 agents/browser.py 文件

浏览器智能体用于从所选 GitHub 仓库获取最近活动。它使用 GitHub REST API 收集提交历史和元数据。

import requests
import os
def scrape_github_activity(repo_url):
    token = os.getenv("GITHUB_TOKEN")  # Set via environment or .env
    headers = {"Authorization": f"Bearer {token}"} if token else {}
    user_repo = "/".join(repo_url.split('/')[-2:])
    api_url = f"https://api.github.com/repos/{user_repo}/commits"
    res = requests.get(api_url, headers=headers)
    res.raise_for_status()
    data = res.json()
    commits = []
    commit_dates = []
    for item in data[:20]:  # optional: increase window for better activity chart
        message = item['commit']['message']
        author = item['commit']['author']['name']
        date = item['commit']['author']['date']
        sha = item['sha'][:7]
        commits.append(f"[{sha}] {message} — {author} @ {date}")
        commit_dates.append(date)  # in ISO 8601 format (perfect for parsing)
    return {
        'repo_url': repo_url,
        'commits': commits,
        'commit_dates': commit_dates
    }

上述函数的作用如下:

  • 提取 GitHub URL 中的 user/repo 部分,并构造 GitHub API 请求。
  • 随后智能体解析返回的 JSON,以提取:
    • 提交 SHA
    • 提交消息
    • 作者姓名
    • 时间戳
  • 这些值分别存储在两个列表中:commits 与 commit_dates。
  • 最后,函数返回一个包含二者的字典,供下游智能体进一步分析与可视化使用。

3. 创建 agents/coder.py 文件

该智能体处理并分析从 GitHub 收集的提交历史,并使用 matplotlib 生成文本摘要与可视化洞察。

# agents/coder.py
import matplotlib.pyplot as plt
from collections import defaultdict, Counter
from datetime import datetime
import matplotlib.dates as mdates
import re
import os
def categorize_commit(message):
    message = message.lower()
    if any(kw in message for kw in ["fix", "bug"]):
        return "🐛 Bug Fixes"
    elif any(kw in message for kw in ["add", "feature", "implement"]):
        return "✨ Features"
    elif any(kw in message for kw in ["doc", "readme"]):
        return "📄 Documentation"
    elif any(kw in message for kw in ["remove", "delete"]):
        return "🔥 Removals"
    elif any(kw in message for kw in ["update", "upgrade"]):
        return "🔧 Updates"
    elif any(kw in message for kw in ["merge", "pull"]):
        return "🔀 Merges"
    else:
        return "📦 Others"
def analyze_code_activity(repo_data):
    commit_messages = repo_data['commits']
    commit_dates = repo_data.get('commit_dates', [])
    # Chart 1: Commits per day (last 30 days)
    commit_day_counts = defaultdict(int)
    for date in commit_dates:
        day = datetime.fromisoformat(date).date()
        commit_day_counts[day] += 1
    recent_days = sorted(commit_day_counts.keys())
    counts = [commit_day_counts[day] for day in recent_days]
    plt.figure(figsize=(10, 4))
    plt.plot(recent_days, counts, marker='o', linestyle='-', color='tab:blue', label='Commits per day')
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
    plt.gcf().autofmt_xdate()
    plt.xlabel("Date")
    plt.ylabel("Commits")
    plt.title("📈 Commits in Last 30 Days")
    plt.legend()
    path1 = "commit_chart.png"
    plt.tight_layout()
    plt.savefig(path1)
    plt.close()
    # Chart 2: Commits per category
    commit_categories = defaultdict(list)
    category_counter = Counter()
    for msg in commit_messages:
        short_msg = re.split(r'—|@', msg)[0].strip()
        category = categorize_commit(short_msg)
        commit_categories[category].append(short_msg)
        category_counter[category] += 1
    plt.figure(figsize=(8, 4))
    cats, values = zip(*category_counter.items())
    plt.bar(cats, values, color='tab:green')
    plt.ylabel("Commits")
    plt.title("🧩 Commits by Category")
    path2 = "category_chart.png"
    plt.tight_layout()
    plt.savefig(path2)
    plt.close()
    # Chart 3: Word frequency in commit messages (basic proxy for hot areas)
    word_freq = Counter()
    for msg in commit_messages:
        words = re.findall(r'\b\w{4,}\b', msg.lower())  # only words with length >= 4
        word_freq.update(words)
    most_common = word_freq.most_common(10)
    labels, freqs = zip(*most_common)
    plt.figure(figsize=(8, 4))
    plt.bar(labels, freqs, color='tab:purple')
    plt.ylabel("Frequency")
    plt.title("🔥 Most Mentioned Topics in Commits")
    path3 = "topics_chart.png"
    plt.tight_layout()
    plt.savefig(path3)
    plt.close()
    # Build markdown report
    analysis = ["## 🔍 Commit Highlights by Category"]
    for cat, msgs in commit_categories.items():
        analysis.append(f"\n### {cat}")
        for m in msgs[:3]:
            clean_msg = m.replace("\n", " ").strip()
            analysis.append(f"- {clean_msg[:100]}{'...' if len(clean_msg) > 100 else ''}")
    charts = [path1, path2, path3]
    return analysis, charts

该智能体处理 GitHub 提交历史,并使用 matplotlib 生成 Markdown 摘要与可视化图表。它通过关键词匹配将提交划分为预定义分组,如修复缺陷、新功能、文档等。接着使用 matplotlib 生成三张信息量较高的图表,展示:

  • 过去 30 天的提交活动
  • 按类别统计的提交
  • 提交消息中最常出现的关键词

最后,智能体会创建一份按类别突出关键提交的 Markdown 摘要,并返回摘要与图表路径,以便在报告中渲染。

4. 创建 agents/reporter.py 文件

报告智能体会生成最终的 Markdown 报告,内容包括:

  • GitHub 仓库链接
  • 近期提交的项目符号列表
  • 按类别整理的提交消息摘要(来自 coder 智能体)
def generate_report(repo_url, repo_data, analysis, chart_path):
    md = f"""# 🧠 GitHub Repo Analysis
## 🔗 Repo: [{repo_url}]({repo_url})
## 📝 Recent Commits:
"""
    for c in repo_data['commits']:
        md += f"- {c}\n"
    md += "\n## 🔍 Analysis:\n"
    for line in analysis:
        md += f"- {line}\n"
    return md

generate_report() 函数使用 GitHub URL、提交数据、分类分析与图表路径来组装最终的 Markdown 报告。它返回一段 Markdown 格式的字符串,可在终端显示或在诸如 Streamlit 之类的 UI 中渲染。它返回的这段 Markdown 也可以直接打印到控制台或在 Streamlit 中渲染。

步骤 4:使用 Streamlit 搭建 UI

该 Streamlit 应用允许用户一键运行完整流水线。创建 streamlit_app.py 文件并添加如下代码:

import streamlit as st
from agent import LangManusAgent
import os
from PIL import Image
st.set_page_config(page_title="LangManus GitHub Analyzer", layout="wide")
st.title("🧠 LangManus GitHub Repo Analyzer")
if st.button("🔍 Run Analysis on Trending Repo"):
    with st.spinner("Running LangManus agents..."):
        agent = LangManusAgent(task="Find a popular open-source project updated recently and summarize its new features with examples and charts.")
        report, chart_paths = agent.run_and_return()
        st.markdown(report)
        st.subheader("📊 Charts")
        for path in chart_paths:
            if os.path.exists(path):
                st.image(Image.open(path), caption=os.path.basename(path).replace('_', ' ').replace('.png', '').title(), use_container_width=True)
else:
    st.info("Click the button to run analysis on a trending GitHub Python repo.")

上述代码的作用如下:

  • 使用 streamlit 库创建一个精简的仪表板,点击分析按钮后触发 LangManusAgent.run_and_return() 函数。
  • 应用通过 st.markdown() 展示 Markdown 报告,并遍历每个图表路径,再用 st.image() 渲染图表。

我们基于 LangManus 的 GitHub 分析项目的最终结构如下:

LangManus-GitHub-Demo/
├── main.py
├── agent.py
├── planner.py
├── streamlit_app.py
├── agents/
│   ├── researcher.py
│   ├── browser.py
│   ├── coder.py
│   └── reporter.py
├── commit_chart.png
├── category_chart.png
├── topics_chart.png

步骤 5:测试 StreamLit 应用

组件已就位,现在运行我们的 Streamlit 应用。在终端执行以下命令:

streamlit run streamlit_app.py

Streamlit Application

在浏览器中点击 "Run Analysis on Trending Repo" 按钮,您的 LangManus 智能体将于数秒内抓取、分析并呈现该 GitHub 仓库的洞察。

Streamlit Application Repo Analysis

Streamlit Application Key feature analysis

Streamlit Application Charts - Commit chart

Streamlit Application Charts - Topics chart

Streamlit Application Charts - Category chart

结语

LangManus 让我们能够构建与真实世界数据交互的结构化多智能体系统。在本指南中,我们创建了一个全自动的 GitHub 仓库分析器,完成了以下工作:

  • 研究热门仓库
  • 抓取提交历史
  • 用图表可视化趋势
  • 用 Markdown 总结结果

LangManus 在构建研究型智能体、仪表盘和数据驱动助手方面潜力十足。

Aashi Dutt

作者

Aashi Dutt

我是一名 Google Developers 机器学习(生成式 AI)领域的专家、Kaggle 三项专家,以及 Women Techmakers 大使,拥有 3 年以上的技术从业经验。2020 年我共同创办了一家健康科技初创公司,目前在佐治亚理工学院攻读计算机科学硕士,专攻机器学习。

主题