java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Python与Java实现AI Agent

使用Python与Java双语言实现AI Agent智能体

作者:蜡台

本文基于Python和Java分别实现轻量级AIAgent,完成热点信息抓取、多类别(新闻/技术/股票)自动分类、结构化存储及大模型驱动的博客内容生成,需要的朋友可以参考下

摘要:本文分别使用Python、Java两套代码实现AI Agent智能体。
Agent自动抓取每日热点(新闻、技术、股票),完成内容分类存储,调用大模型自动生成各分类博客草稿。
文章对比两种语言在Agent开发中的差异,包含完整可运行Demo,适合后端/AI应用开发者参考。

一、需求与整体架构

业务需求

AI Agent需要完成一套完整闭环任务:

  1. 抓取多源每日热点:综合新闻、IT技术资讯、股票行情热点;
  2. 对抓取的原始内容做分类:news / tech / stock;
  3. 将原始热点结构化保存(本地JSON文件,生产可替换MySQL);
  4. 调用大模型,按分类自动生成对应主题博客markdown内容;
  5. 输出博客文件,完成自动化内容生产。

Agent工作流程

图1:AI Agent完整任务链路。Agent内部包含工具调用、数据处理、LLM生成、文件持久化模块。

模块划分

重要提示:Demo为教学示例。正式爬虫请遵守目标网站robots协议,未经许可禁止大规模爬取,避免法律风险。

二、方案设计

  1. 数据源:Demo内置模拟热点数据,可直接替换为真实爬虫接口;
  2. LLM:使用OpenAI兼容接口,可替换通义千问、DeepSeek等国产大模型;
  3. 存储:本地JSON文件存储原始热点;博客输出为独立.md文件;
  4. 分类:news综合新闻、tech技术资讯、stock股票热点;
  5. Agent范式:轻量ReAct,顺序执行任务,适合定时每日热点采集任务。

三、Python版本 AI Agent 实现

Python生态在AI Agent开发中更简洁,爬虫、大模型SDK、文件处理代码量更少。
依赖安装:

pip install openai
import json
import os
from openai import OpenAI
from datetime import datetime
# -------------------------- 工具层:热点抓取工具 --------------------------
class HotSpiderTool:
    """热点抓取工具,Demo模拟数据源,生产替换为requests爬虫"""
    def fetch_hot_data(self):
        mock_hot_list = [
            {
                "title": "国内人工智能产业扶持政策更新",
                "raw_content": "近期多部门发布AI产业扶持政策,推动大模型落地企业场景,算力基础设施持续扩容。",
                "source": "综合新闻门户"
            },
            {
                "title": "LangGraph新版本发布,增强多Agent状态管理能力",
                "raw_content": "LangGraph新版本优化了分支循环,原生支持多智能体协作,降低复杂Agent开发门槛。",
                "source": "技术资讯站"
            },
            {
                "title": "A股算力板块今日走强,多家上市公司业绩预告上调",
                "raw_content": "今日算力相关板块上涨,市场资金持续关注AI基础设施相关标的,机构发布行业研报。",
                "source": "财经股票网站"
            }
        ]
        return mock_hot_list
# -------------------------- LLM工具:内容分类 + 博客生成 --------------------------
class LLMService:
    def __init__(self):
        # 替换为你的api key与base_url
        self.client = OpenAI(
            api_key="sk-xxx",
            base_url="[https://api.deepseek.com/v1](https://api.deepseek.com/v1)"
        )
    def classify_content(self, title, content):
        """热点内容分类:news / tech / stock"""
        prompt = f"""
请对下面内容分类,仅返回标签,可选标签:news、tech、stock
标题:{title}
内容:{content}
输出要求:只输出标签,不要多余文字
"""
        resp = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=[{"role": "user", "content": prompt}],
            temperature=0
        )
        return resp.choices[0].message.content.strip()
    def generate_blog(self, category, title, raw_content):
        """根据分类,生成对应主题博客Markdown"""
        prompt = f"""
你是技术内容作者,根据素材写一篇CSDN风格博客。
分类:{category}
标题素材:{title}
原文素材:{raw_content}
输出markdown博客,包含标题、导读、正文、总结。
"""
        resp = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7
        )
        return resp.choices[0].message.content.strip()
# -------------------------- Agent主控类 --------------------------
class HotInfoAgent:
    def __init__(self):
        self.spider = HotSpiderTool()
        self.llm = LLMService()
        self.save_dir = "./hot_data"
        self.blog_dir = "./blog_output"
        os.makedirs(self.save_dir, exist_ok=True)
        os.makedirs(self.blog_dir, exist_ok=True)
    def run(self):
        print("===== Python AI Agent 开始抓取热点 =====")
        hot_list = self.spider.fetch_hot_data()
        result_list = []
        today_str = datetime.now().strftime("%Y%m%d")
        for item in hot_list:
            title = item["title"]
            raw = item["raw_content"]
            source = item["source"]
            # LLM分类
            category = self.llm.classify_content(title, raw)
            print(f"【识别分类】{title} -> {category}")
            item["category"] = category
            result_list.append(item)
            # 生成博客
            blog_md = self.llm.generate_blog(category, title, raw)
            # 保存博客文件
            blog_filename = f"{self.blog_dir}/{today_str}_{category}_{title[:15]}.md"
            with open(blog_filename, "w", encoding="utf-8") as f:
                f.write(blog_md)
            print(f"✅ 博客已生成:{blog_filename}")
        # 保存原始热点JSON
        json_file = f"{self.save_dir}/hot_{today_str}.json"
        with open(json_file, "w", encoding="utf-8") as f:
            json.dump(result_list, f, ensure_ascii=False, indent=2)
        print(f"\n✅ 原始热点数据保存完成:{json_file}")
        print("===== Agent任务全部完成 =====")
if __name__ == "__main__":
    agent = HotInfoAgent()
    agent.run()

Python代码说明

  1. HotSpiderTool:抓取工具,Demo内置模拟热点,真实场景替换requests、BeautifulSoup;
  2. LLMService封装两个能力:内容分类(低temperature保证结果稳定)、博客生成;
  3. HotInfoAgent为主控Agent,顺序调度工具,完成抓取→分类→存储→生成博客全流程;
  4. 文件输出:原始热点保存JSON,博客按日期+分类生成独立md文件。

四、Java版本 AI Agent 实现

Java适合企业后端工程,稳定性强,适合部署为定时任务服务。

依赖:Maven引入OkHttp(http请求)、Jackson(json序列化)。

pom.xml

<dependencies>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Java完整Agent代码

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 热点实体
class HotItem {
    public String title;
    public String raw_content;
    public String source;
    public String category;
}
// 热点抓取工具
class HotSpiderTool {
    public List<HotItem> fetchHotData() {
        List<HotItem> list = new ArrayList<>();
        HotItem item1 = new HotItem();
        item1.title = "国内人工智能产业扶持政策更新";
        item1.raw_content = "近期多部门发布AI产业扶持政策,推动大模型落地企业场景,算力基础设施持续扩容。";
        item1.source = "综合新闻门户";
        list.add(item1);
        HotItem item2 = new HotItem();
        item2.title = "LangGraph新版本发布,增强多Agent状态管理能力";
        item2.raw_content = "LangGraph新版本优化了分支循环,原生支持多智能体协作,降低复杂Agent开发门槛。";
        item2.source = "技术资讯站";
        list.add(item2);
        HotItem item3 = new HotItem();
        item3.title = "A股算力板块今日走强,多家上市公司业绩预告上调";
        item3.raw_content = "今日算力相关板块上涨,市场资金持续关注AI基础设施相关标的,机构发布行业研报。";
        item3.source = "财经股票网站";
        list.add(item3);
        return list;
    }
}
// LLM服务:调用大模型API,分类、生成博客
class LLMService {
    private final OkHttpClient client = new OkHttpClient();
    private final String apiKey = "sk-xxx";
    private final String baseUrl = "[https://api.deepseek.com/v1/chat/completions](https://api.deepseek.com/v1/chat/completions)";
    private final ObjectMapper mapper = new ObjectMapper();
    public String classifyContent(String title, String content) throws IOException {
        String prompt = String.format("""
                请对下面内容分类,仅返回标签,可选标签:news、tech、stock
                标题:%s
                内容:%s
                输出要求:只输出标签,不要多余文字
                """, title, content);
        return callLlmApi(prompt, 0.0);
    }
    public String generateBlog(String category, String title, String rawContent) throws IOException {
        String prompt = String.format("""
                你是技术内容作者,根据素材写一篇CSDN风格博客。
                分类:%s
                标题素材:%s
                原文素材:%s
                输出markdown博客,包含标题、导读、正文、总结。
                """, category, title, rawContent);
        return callLlmApi(prompt, 0.7);
    }
    private String callLlmApi(String prompt, double temperature) throws IOException {
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put("model", "deepseek-chat");
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> msg = new HashMap<>();
        msg.put("role", "user");
        msg.put("content", prompt);
        messages.add(msg);
        reqBody.put("messages", messages);
        reqBody.put("temperature", temperature);
        String jsonBody = mapper.writeValueAsString(reqBody);
        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(baseUrl)
                .header("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();
        try (Response resp = client.newCall(request).execute()) {
            String respBody = resp.body().string();
            Map<String, Object> result = mapper.readValue(respBody, Map.class);
            List<Map<String, Object>> choices = (List<Map<String, Object>>) result.get("choices");
            Map<String, Object> choice = choices.get(0);
            Map<String, String> message = (Map<String, String>) choice.get("message");
            return message.get("content").trim();
        }
    }
}
// Java Agent主控
public class HotInfoAgentJava {
    private final HotSpiderTool spider = new HotSpiderTool();
    private final LLMService llm = new LLMService();
    private final String saveDir = "./hot_data";
    private final String blogDir = "./blog_output";
    private final String today;
    public HotInfoAgentJava() {
        today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        new File(saveDir).mkdirs();
        new File(blogDir).mkdirs();
    }
    public void run() throws IOException {
        System.out.println("===== Java AI Agent 开始抓取热点 =====");
        List<HotItem> hotList = spider.fetchHotData();
        for (HotItem item : hotList) {
            String category = llm.classifyContent(item.title, item.raw_content);
            item.category = category;
            System.out.printf("【识别分类】%s -> %s%n", item.title, category);
            String blogMd = llm.generateBlog(category, item.title, item.raw_content);
            // 保存博客md文件
            String fileName = blogDir + "/" + today + "_" + category + "_" + item.title.substring(0,15) + ".md";
            try (FileWriter fw = new FileWriter(fileName, StandardCharsets.UTF_8)) {
                fw.write(blogMd);
            }
            System.out.println("✅ 博客已生成:" + fileName);
        }
        // 保存原始JSON
        String jsonFile = saveDir + "/hot_" + today + ".json";
        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonFile), hotList);
        System.out.println("\n✅ 原始热点数据保存完成:" + jsonFile);
        System.out.println("===== Agent任务全部完成 =====");
    }
    public static void main(String[] args) throws IOException {
        HotInfoAgentJava agent = new HotInfoAgentJava();
        agent.run();
    }
}

Java代码说明

  1. 实体HotItem承载热点数据;
  2. HotSpiderTool模拟热点抓取;
  3. LLMService使用OkHttp发起大模型http调用,Jackson做JSON序列化;
  4. HotInfoAgentJava为主控Agent,串联任务,写入本地文件;
  5. 适合打包为Jar,配合Spring Scheduled定时每日自动执行热点采集。

五、Python vs Java 实现AI Agent差异对比

对比项Python AgentJava Agent
开发效率极高,代码简洁,开箱即用,适合快速原型验证代码量大,模板代码多,开发周期更长
生态AI/LLM、爬虫库极其丰富,Agent框架(LangGraph)原生支持企业后端生态成熟,Agent相关库偏少,多手动封装HTTP调用
运行性能解释型,单线程性能弱;适合轻量任务编译型,高并发、稳定性强,适合线上定时任务服务
部署场景本地脚本、jupyter、轻量容器服务器后台、微服务、定时调度系统
异常管控需要手动捕获异常强类型,编译期提前发现类型错误,工程健壮性更好

六、运行演示

  1. 配置LLM api key,修改base_url;
  2. 执行主程序;
  3. Agent输出日志,自动创建hot_data、blog_output目录;
  4. hot_data存放当日抓取的热点原始json;blog_output存放按分类生成的博客Markdown。

输出目录结构

├── hot_data
│   └── hot_20261017.json
├── blog_output
│   ├── 20261017_news_国内人工智能产业扶持政策更新.md
│   ├── 20261017_tech_LangGraph新版本发布.md
│   └── 20261017_stock_A股算力板块今日走强.md

七、生产环境优化方向

  1. 爬虫合规改造:增加请求间隔、UA头,代理池,禁止高频爬取;
  2. 持久化替换:JSON文件替换MySQL,增加数据表:热点表、博客草稿表;
  3. 任务容错:增加重试、超时捕获,LLM调用失败降级,日志持久化;
  4. Agent增强:增加ReAct工具选择,失败自动重试抓取,过滤重复热点;
  5. 限流与成本:LLM接口增加token统计,防止大量调用产生高额费用;
  6. 定时调度:Python用APScheduler,Java使用Spring Schedule/Quartz每日定点执行。

八、总结

本文分别使用Python、Java实现同一套AI Agent,完成热点抓取、自动分类、博客生成完整链路。
Python版本优势在于快速验证Agent逻辑,适合AI开发者做原型;Java版本更适合企业级定时内容生产服务,强类型、稳定可靠。
这个Agent属于工具调用型轻量智能体,后续可继续扩展:RAG知识库、多Agent分工、人工审核环节,形成完整自动化内容生产平台。

以上就是使用Python与Java双语言实现AI Agent智能体的详细内容,更多关于Python与Java实现AI Agent的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文