从ai产品推荐到利用cursor快速掌握一个开源项目再到langchain手搓一个Text2Sql agent

目录

[0. 经验分享:产品推荐](#0. 经验分享:产品推荐)

[1. 经验分享:提示词优化](#1. 经验分享:提示词优化)

[2. 经验分享:使用cursor 阅读一篇文章](#2. 经验分享:使用cursor 阅读一篇文章)

[3. 经验分享:使用cursor 阅读一个完全陌生的开源项目](#3. 经验分享:使用cursor 阅读一个完全陌生的开源项目)

[4. 经验分享:手搓一个text2sql agent (使用langchain langgraph)](#4. 经验分享:手搓一个text2sql agent (使用langchain langgraph))


0. 经验分享:产品推荐

ai 产品

360ai 浏览器

https://www.perplexity.ai/onboarding?redirect=https%3A%2F%2Fwww.perplexity.ai%2F%3Flogin-source%3DoneTapHome

秘塔AI搜索

ima.copilot-腾讯智能工作台

https://deepseek.com -→ 揭秘DeepSeek:一个更极致的中国技术理想主义故事

ai 导航站

极客时间 AI 指南

ai 学习材料

https://github.com/anthropics
大语言模型(LLM)学习路径和资料汇总 · Issue #97 · ninehills/blog · GitHub

Docs

动手实战人工智能 AI By Doing --- 动手实战人工智能 AI By Doing

agent平台

code

dify

fastgpt

发展趋势:

pc-agent

GLM-PC

mobile-agent

Mobile-Agent-E: Self-Evolving Mobile Assistant for Complex Tasks

检测论文是否由ai 生成: GitHub - Jiaqi-Chen-00/ImBD: [AAAI 2025] Official repository of Imitate Before Detect: Aligning Machine Stylistic Preference for Machine-Revised Text Detection

写小说 GitHub - nicekate/Al-StoryLab: AI-StoryLab 是一款基于 Next.js 的智能故事创作平台,集成音频制作与 AI 绘图提示词生成功能。

GitHub - Aria-Zhangjl/StoryWeaver: [AAAI 2025] StoryWeaver: A Unified World Model for Knowledge-Enhanced Story Character Customization

漫画生成: GitHub - jianzongwu/DiffSensei: Implementation of "DiffSensei: Bridging Multi-Modal LLMs and Diffusion Models for Customized Manga Generation"

社交: GitHub - langchain-ai/social-media-agent: 📲 An agent for sourcing, curating, and scheduling social media posts with human-in-the-loop.

https://github.com/whotto/Video_note_generator

电影视频: https://github.com/linyqh/NarratoAI

https://github.com/Huanshere/VideoLingo/blob/main/i18n/README.zh.md

数字人: https://github.com/modstart-lib/aigcpanel

教育方向: GitHub - taoofagi/easegen-front: Easegen is an open-source digital human course creation platform offering comprehensive solutions from course production and video management to intelligent quiz generation.Easegen 是一个开源的数字人课程制作平台,提供从课程制作、视频管理到智能出题的全方位解决方案。

1. 经验分享:提示词优化

a.search in english, reponse use chinese ;

b.思维链 )

李继刚:Prompt的道与术

总结:没什么用

2. 经验分享:使用cursor 阅读一篇文章

1.安装markmap插件

2.提示词: @http://xxx 阅读文章帮我,使用md 格式生产思维导图

效果如下:

3. 经验分享:使用cursor 阅读一个完全陌生的开源项目

1.安装plantUml 插件

  1. 提示词:

@codebase 使用plantUml格式,帮我生成这个项目的架构图

@codebase 帮我生成xxx 的流程图

@codebase 帮我写一篇关于roo Cline 系统提示词分析

以roo-code插件项目为例 为例: GitHub - RooVetGit/Roo-Code: Roo Code (prev. Roo Cline) is a VS Code plugin that enhances coding with AI-powered automation, multi-model support, and experimental features

4. 经验分享:手搓一个text2sql agent (使用langchain langgraph)

python 复制代码
import os
from typing import Dict, Any, List
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_community.utilities import SQLDatabase
from dotenv import load_dotenv
import pymysql
from sqlalchemy import create_engine, text

# 加载环境变量
load_dotenv()

class MySQLChainDemo:
    """MySQL Chain 演示类"""

    def __init__(self, database: str = None):
        """
        初始化 MySQL Chain 演示实例
        
        Args:
            database: 数据库名称,如果不指定则使用环境变量中的配置
        """
        self.llm = ChatOpenAI(
            model="deepseek-chat",
            openai_api_key=os.getenv("LLM_API_KEY"),
            base_url=os.getenv("LLM_BASE_URL")
        )
        
        # 使用传入的数据库名或环境变量中的配置
        self.database = database or os.getenv("MYSQL_DATABASE", "stock")
        
        # 创建数据库连接
        db_url = (f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}"
                 f"@{os.getenv('MYSQL_HOST')}:{os.getenv('MYSQL_PORT')}/{self.database}")
        
        self.engine = create_engine(db_url)
        self.db = SQLDatabase(engine=self.engine)

    def get_tables_info(self) -> str:
        """获取所有表的信息"""
        try:
            with self.engine.connect() as conn:
                # 获取所有表名
                tables = conn.execute(text("SHOW TABLES")).fetchall()
                tables = [table[0] for table in tables]
                
                tables_info = [f"当前数据库: {self.database}"]
                for table in tables:
                    # 获取表结构
                    columns = conn.execute(text(f"DESCRIBE `{table}`")).fetchall()
                    columns_info = [f"{col[0]} ({col[1]})" for col in columns]
                    
                    tables_info.append(f"\n表名: {table}")
                    tables_info.append("列: " + ", ".join(columns_info))
                
                return "\n".join(tables_info)
        except Exception as e:
            return f"获取表信息失败: {str(e)}"

    def execute_query(self, question: str) -> str:
        """执行自然语言查询"""
        try:
            # 创建提示模板
            prompt = ChatPromptTemplate.from_messages([
                ("system", """你是一个MySQL专家,请将用户的自然语言问题转换为可执行的MySQL查询语句。

当前数据库环境:
数据库名称: {database}

数据库表结构如下:
{tables_info}

规则:
1. 只返回一个MySQL查询语句
2. 不要包含任何注释或额外说明
3. 不要使用markdown格式
4. 使用反引号(`)包裹表名和列名
5. 确保SQL语法正确
6. 查询information_schema时使用当前数据库名称

示例:
问题:数据库中有哪些表?
返回:SELECT TABLE_NAME as table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{database}';

问题:查询用户表有多少条记录?
返回:SELECT COUNT(*) as total FROM `users`;
"""),
                ("human", "{question}")
            ])
            
            # 获取表信息
            tables_info = self.get_tables_info()
            
            # 生成SQL
            chain = prompt | self.llm | StrOutputParser()
            sql = chain.invoke({
                "question": question,
                "tables_info": tables_info,
                "database": self.database
            }).strip()
            
            # 执行SQL
            with self.engine.connect() as conn:
                result = conn.execute(text(sql))
                rows = result.fetchall()
                
                if not rows:
                    return f"SQL查询: {sql}\n\n查询结果: 无数据"
                
                # 格式化结果
                columns = result.keys()
                results = []
                for row in rows:
                    result_dict = dict(zip(columns, row))
                    results.append(str(result_dict))
                
                return f"SQL查询: {sql}\n\n查询结果:\n" + "\n".join(results)
                
        except Exception as e:
            return f"查询执行失败: {str(e)}\nSQL: {sql if 'sql' in locals() else '未生成'}"

def main():
    """主函数"""
    # 可以指定数据库名称,或使用默认值
    demo = MySQLChainDemo()  # 使用默认的 stock 数据库
    # demo = MySQLChainDemo(database="other_db")  # 使用指定的数据库
    
    # 测试查询
    test_queries = [
        "数据库中有哪些表?",
        "查询t_stock_min_trade表中最新的交易时间",
        "查询t_stock_min_trade表中股票代码为000001的最近3条记录",
        "统计t_stock_min_trade表中有多少个不同的股票代码"
    ]
    
    for query in test_queries:
        print(f"\n问题: {query}")
        result = demo.execute_query(query)
        print(result)
        print("-" * 50)

if __name__ == "__main__":
    main() 

涉及到到细节的代码和roo code 源码分析见github:
https://github.com/caicongyang/ai-agent-demo.git
https://github.com/caicongyang/mini-cline.git

相关推荐
mask哥1 天前
详解mcp以及agen架构设计与实现
java·微服务·flink·大模型·ai agent·springai·mcp
Sam_Deep_Thinking3 天前
在Windows 11上配置Cursor IDE进行Java开发
ai编程·cursor
SamDeepThinking4 天前
在Cursor里安装极其好用的Mysql Database Client 插件
ai编程·cursor
卡尔特斯4 天前
Cursor 自用习惯快速调整基础布局与配置
cursor
Sam_Deep_Thinking5 天前
在 Cursor IDE 中配置 SQLTools 连接 MySQL 数据库指南(Windows 11)
ai编程·cursor
SamDeepThinking5 天前
彻底让Cursor不要格式化Java代码
ai编程·cursor
SamDeepThinking5 天前
使用Cursor生成【财务对账系统】前后端代码
后端·ai编程·cursor
SamDeepThinking6 天前
在Windows 11上配置Cursor IDE进行Java开发
后端·ai编程·cursor
陈佬昔没带相机6 天前
告别Token焦虑!我是如何用最低消费玩转AI编程的
claude·cursor·trae
yaocheng的ai分身6 天前
Browser MCP扩展
cursor·mcp