[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-defog-ai--sql-eval":3,"tool-defog-ai--sql-eval":65},[4,17,27,35,48,57],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",149489,2,"2026-04-10T11:32:46",[13,14,15],"开发框架","Agent","语言模型","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,3,"2026-04-06T11:19:32",[15,26,14,13],"图像",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":10,"last_commit_at":33,"category_tags":34,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":10,"last_commit_at":41,"category_tags":42,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",85092,"2026-04-10T11:13:16",[26,43,44,45,14,46,15,13,47],"数据工具","视频","插件","其他","音频",{"id":49,"name":50,"github_repo":51,"description_zh":52,"stars":53,"difficulty_score":54,"last_commit_at":55,"category_tags":56,"status":16},5784,"funNLP","fighting41love\u002FfunNLP","funNLP 是一个专为中文自然语言处理（NLP）打造的超级资源库，被誉为\"NLP 民工的乐园”。它并非单一的软件工具，而是一个汇集了海量开源项目、数据集、预训练模型和实用代码的综合性平台。\n\n面对中文 NLP 领域资源分散、入门门槛高以及特定场景数据匮乏的痛点，funNLP 提供了“一站式”解决方案。这里不仅涵盖了分词、命名实体识别、情感分析、文本摘要等基础任务的标准工具，还独特地收录了丰富的垂直领域资源，如法律、医疗、金融行业的专用词库与数据集，甚至包含古诗词生成、歌词创作等趣味应用。其核心亮点在于极高的全面性与实用性，从基础的字典词典到前沿的 BERT、GPT-2 模型代码，再到高质量的标注数据和竞赛方案，应有尽有。\n\n无论是刚刚踏入 NLP 领域的学生、需要快速验证想法的算法工程师，还是从事人工智能研究的学者，都能在这里找到急需的“武器弹药”。对于开发者而言，它能大幅减少寻找数据和复现模型的时间；对于研究者，它提供了丰富的基准测试资源和前沿技术参考。funNLP 以开放共享的精神，极大地降低了中文自然语言处理的开发与研究成本，是中文 AI 社区不可或缺的宝藏仓库。",79857,1,"2026-04-08T20:11:31",[15,43,46],{"id":58,"name":59,"github_repo":60,"description_zh":61,"stars":62,"difficulty_score":54,"last_commit_at":63,"category_tags":64,"status":16},5773,"cs-video-courses","Developer-Y\u002Fcs-video-courses","cs-video-courses 是一个精心整理的计算机科学视频课程清单，旨在为自学者提供系统化的学习路径。它汇集了全球知名高校（如加州大学伯克利分校、新南威尔士大学等）的完整课程录像，涵盖从编程基础、数据结构与算法，到操作系统、分布式系统、数据库等核心领域，并深入延伸至人工智能、机器学习、量子计算及区块链等前沿方向。\n\n面对网络上零散且质量参差不齐的教学资源，cs-video-courses 解决了学习者难以找到成体系、高难度大学级别课程的痛点。该项目严格筛选内容，仅收录真正的大学层级课程，排除了碎片化的简短教程或商业广告，确保用户能接触到严谨的学术内容。\n\n这份清单特别适合希望夯实计算机基础的开发者、需要补充特定领域知识的研究人员，以及渴望像在校生一样系统学习计算机科学的自学者。其独特的技术亮点在于分类极其详尽，不仅包含传统的软件工程与网络安全，还细分了生成式 AI、大语言模型、计算生物学等新兴学科，并直接链接至官方视频播放列表，让用户能一站式获取高质量的教育资源，免费享受世界顶尖大学的课堂体验。",79792,"2026-04-08T22:03:59",[46,26,43,13],{"id":66,"github_repo":67,"name":68,"description_en":69,"description_zh":70,"ai_summary_zh":71,"readme_en":72,"readme_zh":73,"quickstart_zh":74,"use_case_zh":75,"hero_image_url":76,"owner_login":77,"owner_name":78,"owner_avatar_url":79,"owner_bio":80,"owner_company":81,"owner_location":81,"owner_email":82,"owner_twitter":83,"owner_website":84,"owner_url":85,"languages":86,"stars":99,"forks":100,"last_commit_at":101,"license":102,"difficulty_score":103,"env_os":104,"env_gpu":105,"env_ram":106,"env_deps":107,"category_tags":119,"github_topics":81,"view_count":10,"oss_zip_url":81,"oss_zip_packed_at":81,"status":16,"created_at":120,"updated_at":121,"faqs":122,"releases":152},6238,"defog-ai\u002Fsql-eval","sql-eval","Evaluate the accuracy of LLM generated outputs","sql-eval 是 Defog 开源的一款专门用于评估大语言模型（LLM）生成 SQL 语句准确性的工具。在 AI 辅助数据分析日益普及的今天，如何客观判断模型写出的查询代码是否正确一直是个难题，sql-eval 正是为了解决这一痛点而生。\n\n该工具的核心工作流程严谨而高效：它基于经典的 Spider 数据集架构，但采用了全新手工筛选的问题与查询对，并按类别进行了细致分组。评估时，sql-eval 会同时执行“标准答案”查询和\"AI 生成”的查询，将两者的运行结果转化为数据表进行比对。它不仅支持严格的“完全匹配”验证，还引入了灵活的“子集匹配”机制，能更智能地判定结果的有效性，同时还能记录令牌消耗、延迟等关键性能指标。\n\nsql-eval 特别适合 AI 研究人员、数据库开发者以及致力于优化 Text-to-SQL 模型的工程师使用。其技术亮点在于提供了基于 Docker 的一站式 Postgres 测试环境，极大降低了配置复杂多数据库场景的门槛；此外，它还集成了元数据剪枝等高级启发式方法，帮助开发者更深入地分析和提升模型表现。如果你正在构建或微调自己的 SQL 生成模型，sql-e","sql-eval 是 Defog 开源的一款专门用于评估大语言模型（LLM）生成 SQL 语句准确性的工具。在 AI 辅助数据分析日益普及的今天，如何客观判断模型写出的查询代码是否正确一直是个难题，sql-eval 正是为了解决这一痛点而生。\n\n该工具的核心工作流程严谨而高效：它基于经典的 Spider 数据集架构，但采用了全新手工筛选的问题与查询对，并按类别进行了细致分组。评估时，sql-eval 会同时执行“标准答案”查询和\"AI 生成”的查询，将两者的运行结果转化为数据表进行比对。它不仅支持严格的“完全匹配”验证，还引入了灵活的“子集匹配”机制，能更智能地判定结果的有效性，同时还能记录令牌消耗、延迟等关键性能指标。\n\nsql-eval 特别适合 AI 研究人员、数据库开发者以及致力于优化 Text-to-SQL 模型的工程师使用。其技术亮点在于提供了基于 Docker 的一站式 Postgres 测试环境，极大降低了配置复杂多数据库场景的门槛；此外，它还集成了元数据剪枝等高级启发式方法，帮助开发者更深入地分析和提升模型表现。如果你正在构建或微调自己的 SQL 生成模型，sql-eval 将是一个专业且得力的评估助手。","# SQL Generation Evaluation\n\nThis repository contains the code that Defog uses for the evaluation of generated SQL. It's based off the schema from the [Spider](https:\u002F\u002Fgithub.com\u002Ftaoyds\u002Fspider), but with a new set of hand-selected questions and queries grouped by query category. For an in-depth look into our process of creating this evaluation approach, see [this](https:\u002F\u002Fdefog.ai\u002Fblog\u002Fopen-sourcing-sqleval\u002F).\n\n## Introduction\n\nOur testing procedure comprises the following steps. For each question\u002Fquery pair:\n\n1. We generate a SQL query (possibly from an LLM).\n2. We run both the \"gold\" query and the generated query on their respective database to obtain 2 dataframes with the results.\n3. We compare the 2 dataframes using an \"exact\" and a \"subset\" match. TODO add link to blogpost.\n4. We log these alongside other metrics of interest (e.g. tokens used, latency) and aggregate the results for reporting.\n\n## Getting Started\n\nThis is a comprehensive set of instructions that assumes basic familiarity with the command line, Docker, running SQL queries on a database, and common Python data manipulation libraries (e.g. pandas).\n\n### Install Dependencies\n\nFirstly, clone the repository where we store our database data and schema. Install all Python libraries listed in the `requirements.txt` file. You would also need to download a spacy model if you're using the NER heuristic for our [metadata-pruning method](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fblob\u002Fmain\u002Futils\u002Fpruning.py) (set by any values of the `c` parameter that is  more than 0, more below). Finally, install the library.\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data.git\ncd defog-data\npip install -r requirements.txt\npip install -e .\n```\n\n### Start Postgres Instance\n\nNext, you would need to set up the databases that the queries are executed on. We use Postgres here, since it is the most common OSS database with the widest distribution and usage in production. In addition, we would recommend using Docker to do this, as it is the easiest way to get started. You can install Docker [here](https:\u002F\u002Fdocs.docker.com\u002Fget-docker\u002F).\n\nOnce you have Docker installed, you can create the Docker container and start the Postgres database using the following commands. We recommend mounting a volume on `data\u002Fpostgres` to persist the data, as well as `data\u002Fexport` to make it easier to import the data. To create the container, run:\n\n```bash\nmkdir data\u002Fpostgres data\u002Fexport\ndocker create --name postgres-sql-eval -e POSTGRES_PASSWORD=postgres -p 5432:5432 -v $(pwd)\u002Fdata\u002Fpostgres:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata -v $(pwd)\u002Fdata\u002Fexport:\u002Fexport postgres:16-alpine\n```\n\nTo start the container, run:\n\n```bash\ndocker start postgres-sql-eval\n```\n\nIf you want to reset the Postgres server instance's state (e.g. memory leaks from transient connections), you can turn it off (and start it back up after):\n\n```bash\ndocker stop postgres-sql-eval\n# see that the container is still there:\ndocker container list -a\n```\n\nSome notes:\n\n- You would need to stop other Postgres instances listening on port 5432 before running the above command.\n- You only need to run the `docker create ...` once to create the image, and then subsequently only `docker start\u002Fstop postgres-sql-eval`.\n- The data is persisted in `data\u002Fpostgres`, so turning it off isn't critical. On the other hand, if you delete the `data\u002Fpostgres` folder, then all is lost T.T\n- While we will use Docker for deploying Postgres and the initialization, you are free to modify the scripts\u002Finstructions to work with your local installation.\n\n### Import Data into Postgres\n\nThe data for importing is in the `defog-data` repository which we cloned earlier. Each folder contains the metadata and data corresponding to a single database (e.g. `academic` contains all the data required to reload the 'academic' database). We assume that you have a `psql` client installed locally. We will create a new database in our postgres instance for each of the 7 SQL databases with the following commands:\n\n```bash\n# set the following environment variables\ncd defog-data # if you're not already in the defog-data directory\nexport DBPASSWORD=\"postgres\"\nexport DBUSER=\"postgres\"\nexport DBHOST=\"localhost\"\nexport DBPORT=5432\n.\u002Fsetup.sh\n```\n\n### Import Data into Snowflake\n\nShould you wish to import the data into Snowflake, the setup instructions are also in the `defog-data` repository. After installing the [Snowflake CLI](https:\u002F\u002Fdocs.snowflake.com\u002Fen\u002Fuser-guide\u002Fsnowsql-install-config), configure your credentials as per the [docs](https:\u002F\u002Fdocs.snowflake.com\u002Fen\u002Fuser-guide\u002Fsnowsql-config) and set them as environment variables like below, then run the setup command.\n\n```sh\nexport SFDBPASSWORD=\"your_password\"\nexport SFDBUSER=\"your_username\"\nexport SFDBACCOUNT=\"your_account\"\nexport SFDBWAREHOUSE=\"your_warehouse\"\n.\u002Fsetup_snowflake.sh\n```\n\nNote that during evaluation you'll have to use the `_snowflake` question files in `\u002Fdata`. The queries been modified to be valid on Snowflake databases.\n\n### Import Data into BigQuery, MySQL, SQLite, SQL Server\n\nThe setup instructions for these database management systems are found in the `defog-data` repository. Configure your credentials accordingly, set up your environment variables, then translate and import the eval databases with the command:\n\n```python\npython translate_ddl_dialect.py\n```\n\nDuring evaluation, you'll have to set the right `--db_type` flag and use the corresponding `_{dialect}` question files in `\u002Fdata`.\n\n### Using Private Data (Optional)\n\nIf you have a private dataset that you do not want to make publicly available but would still like to repurpose the code here for evaluations, you can do so by following the steps below.\n\n- Begin by creating a separate git repository for your private data, that has a `setup.py` file, similar to [defog-data](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data).\n- Create the metadata and data files, and import them into your database. This is to allow our evaluation framework to run the generated queries with some actual data. You can refer to `defog-data`'s [metadata objects](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fmain\u002Fdefog_data\u002Fmetadata.py) for the schema, and [setup.sh](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fmain\u002Fsetup.sh) as an example on how import the data into your database. We do not prescribe any specific folder structure, and leave it to you to decide how you want to organize your data, so long as you can import it into your database easily.\n- To use our metadata pruning utilities, you would need to have the following defined:\n  - A way to define joinable columns between tables. In our case, we call a dictionary [columns_join](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fdb8c3d4c4004144d2b3ff5a2701529f5545f520f\u002Fdefog_data\u002Fsupplementary.py#L233) of database name to a nested dictionary of table tuples to column name tuples. You can refer to the raw data for an example of how we generate this dictionary.\n\nOnce all of the 3 above steps have completed, you would need to\n\n- Install your data library as a dependency, by running `pip install -e .` (-e to automatically incorporate edits without reinstalling)\n- Replace the associated function calls and variables in [prune_metadata_str](utils\u002Fpruning.py#L165) with your own imported functions and variables. Note that you might not name your package\u002Fmodule `defog_data_private.supplementary`, so do modify accordingly.\n\nSome things to take note of:\n\n- If you do not populate your database with data (ie only create the tables without inserting data), you would return empty dataframes most of the time (regardless of whether the query generated was what you want), and it would result in results matching all the time and generate a lot of false positives. Hence, you might want to consider populating your database with some meaningful data that would return different results if the queries should be different from what you want.\n- If testing out on your private data, you would also need to change the questions file to point to your own questions file (tailored to your database schema).\n\n### Runner\n\nThe runner calls is responsible for handling the configuration of work (e.g. parallelization \u002F batching \u002F model selected etc.) for each question\u002Fquery pair.\n\nWe have provided a few common runners: `runners\u002Fopenai_runner.py` for calling OpenAI's API (with parallelization support), `runners\u002Fanthropic_runner` for calling Anthropic's API, `runners\u002Fhf_runner.py` for calling a local Hugging Face model and finally, `runners\u002Fapi_runner.py` makes it possible to use a custom API for evaluation.\n\n## Running the Test\n\n### OpenAI\n\nRemember to have your API key (`OPENAI_API_KEY` or `ANTHROPIC_API_KEY`) set as an environment variable before running the test if you plan to call the OpenAI or Anthropic\u002Fother LLM API's accordingly.\n\nTo test it out with just 10 questions (instead of all 200), parallelized across 5 :\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fopenai_classic.csv results\u002Fopenai_basic.csv results\u002Fopenai_advanced.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m o3-mini \\\n  -p 5 \\\n  -c 0\n```\n\nIf testing with the latest `o1-*` models (which do not support system prompts), you should use a different prompt file, reduce parallel requests and increase the timeout:\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fopenai_o1mini_classic.csv results\u002Fopenai_o1mini_basic.csv results\u002Fopenai_o1mini_advanced.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai_o1.json \\\n  -m o1-mini \\\n  -p 1 \\\n  -t 120 \\\n  -c 0\n```\n\n### Anthropic\n\nTo test out the full suite of questions for claude-3:\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fclaude3_classic.csv results\u002Fclaude3_basic.csv results\u002Fclaude3_advanced.csv \\\n  -g anthropic \\\n  -f prompts\u002Fprompt_anthropic.md \\\n  -m claude-3-opus-20240229 \\\n  -p 5 \\\n  -c 0\n```\n\n### Hugging Face\n\nTo test it out with our fine-tuned sql model with just 10 questions (instead of all 200):\n\n```bash\n# use the -W option to ignore warnings about sequential use of transformers pipeline\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fhf_classic.csv results\u002Fhf_basic.csv results\u002Fhf_advanced.csv \\\n  -g hf \\\n  -f prompts\u002Fprompt.md \\\n  -m defog\u002Fllama-3-sqlcoder-8b \\\n  -c 0\n```\n\nWe also support loading a peft adapter here as well via the `-a` flag. Note that the loading of the adapter with the model will take slightly longer than usual.\n\n### vLLM\n\nWe also have a [vllm](https:\u002F\u002Fblog.vllm.ai\u002F) runner which uses the vLLM engine to run the inference altogether as a single batch. It is much faster to do so especially when `num_beams` > 1. You would have to pass in a single set of merged model weights, path to LoRA adapters if applicable, and the model architecture needs to be supported by vLLM. Here's a sample command:\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fvllm_classic.csv results\u002Fvllm_basic.csv results\u002Fvllm_advanced.csv \\\n  -g vllm \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m defog\u002Fllama-3-sqlcoder-8b \\\n  -a path\u002Fto_adapter \\\n  -c 0\n```\n\nOptionally, if you're running evals on a model that is quantized with AWQ, add the `-qz` or `--quantized` parameter. Only applicable for the vllm runner.\n\n### Running with an API Server\n\nIf running with different settings, you can setup an api server to avoid reloading for each test setting and then run the tests subsequently. We enable setting up 2 types of api servers, namely the vllm api server, as well as the TGI server.\n\nWe also provide our custom modification of the vllm api server, which only returns the generated output.\n\n#### VLLM API Server\n\n```bash\n# to set up a vllm server\npython -m vllm.entrypoints.api_server \\\n    --model defog\u002Fdefog-llama-3-sqlcoder-8b \\\n    --tensor-parallel-size 4 \\\n    --dtype float16\n\n# to set up a vllm server that supports LoRA adapters\npython -m vllm.entrypoints.api_server \\\n    --model defog\u002Fllama-3-sqlcoder-8b \\\n    --tensor-parallel-size 1 \\\n    --dtype float16 \\\n    --max-model-len 4096 \\\n    --enable-lora \\\n    --max-lora-rank 64\n\n# to use our modified api server\npython utils\u002Fapi_server.py \\\n    --model defog\u002Fllama-3-sqlcoder-8b \\\n    --tensor-parallel-size 4 \\\n    --dtype float16 \\\n    --max-model-len 4096 \\\n    --enable-lora \\\n    --max-lora-rank 64\n\n# to use vllm's openai-compatible api server\nexport MODEL_NAME=\"Qwen\u002FQwen3-4B\"\nvllm serve \"$MODEL_NAME\" --port 8000\n\n# to run sql-eval using the api runner - depending on how much your GPUs can take, can increase p and b to higher values\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fapi.csv \\\n  -g api \\\n  -b 1 \\\n  -f prompts\u002Fprompt.md \\\n  --api_url \"http:\u002F\u002Flocalhost:8000\u002Fgenerate\" \\\n  --api_type \"vllm\" \\\n  -a path\u002Fto_adapter_if_applicable \\\n  -p 8\n```\n\n#### TGI API Server\n\nYou may consult the [TGI documentation](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftext-generation-inference\u002Fquicktour) for more information on how to set up a TGI server. Here's a sample command to set up a TGI server using a preset docker image and run the evaluation using the API runner. Note that you would want to change the number of shards and the model id accordingly, depending on how many gpu's you have available and your model of choice.\n\n```bash\n# to set up a tgi server\nmodel=\"defog\u002Fllama-3-sqlcoder-8b\"\ndocker run --gpus all \\\n  --shm-size 1g \\\n  -p 8000:80 \\\n  -v \u002Fmodels:\u002Fmodels ghcr.io\u002Fhuggingface\u002Ftext-generation-inference:2.0 \\\n  --model-id \"${model}\" \\\n  --max-best-of 4 \\\n  --max-input-tokens 3072 \\\n  --sharded true \\\n  --num-shard 4 \\\n  --hostname 0.0.0.0 \\\n  --port 80\n\n# to run sql-eval using the api runner - depending on how much your GPUs can take, can increase p and b to higher values. Note that cuda graphs in tgi is optimized for batch sizes that are powers of 2 by default.\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fapi.csv \\\n  -g api \\\n  -b 1 \\\n  -f prompts\u002Fprompt.md \\\n  --api_url \"http:\u002F\u002Flocalhost:8000\u002Fgenerate\" \\\n  --api_type \"vllm\" \\\n  -p 8\n```\n\n#### Multiple Prompts\n\nIf you'd like to test out a few prompts in a single run (to save the few minutes spent loading the model into GPU at the start of each run), you can specify a list of prompt files in `--prompt_file` (e.g. `-f prompts\u002Fprompt-1.md prompts\u002Fprompt-2.md prompts\u002Fprompt-3.md`), as well as a corresponding list of output files in `--output_file` (e.g. `-o results\u002Fresults-1.csv results\u002Fresults-2.csv results\u002Fresults-3.csv`). The number of prompts and output files must be the same. Here's a sample command:\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fresults_1.csv results\u002Fresults_2.csv \\\n  -g vllm \\\n  -f prompts\u002Fprompt_1.md prompts\u002Fprompt_2.md \\\n  -m defog\u002Fsqlcoder2\n```\n\nWhile you can do the same for the other runners, the time savings are most significant when loading a large model locally, vs calling an always-on API.\n\n#### Thinking Models\n\nIf you'd like to use a model that outputs thinking tokens, you can pass in the flag `--enable_thinking` to the runner so that we will remove the thinking tokens from the LLM output before running the generated query.\n\nYou can check out `run_qwen.sh` for an example of how to run a thinking model.\n\n```bash\n.\u002Frun_qwen.sh --thinking # add --thinking to generate thinking tokens\n```\n\n### Bedrock\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fllama3_70b.csv \\\n  -g bedrock \\\n  -f prompts\u002Fprompt.md \\\n  -m meta.llama3-70b-instruct-v1:0\n```\n\n### Llama CPP\n\nTo run the eval using Llama CPP, you can use the following code. Before running this, you must install `llama-cpp-python` with the following (on Apple Silicon)\n\n`CMAKE_ARGS=\"-DLLAMA_METAL=on\" pip install llama-cpp-python`\n\nNote that llama-cpp-python library does not currently have beam search, and hence will have lower quality results.\n\n```bash\npython -W ignore main.py \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -db postgres \\\n  -o \"results\u002Fllama_cpp.csv\" \\\n  -g llama_cpp \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m path\u002Fto\u002Fmodel.gguf\n```\n\n### MLX\n\nTo run the eval using MLX, you can use the following code. Before running this, you must install `mlx-lm` package with `pip install mlx-lm`\n\nNote that MLX does not currently have beam search, and hence will have lower quality results.\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o \"results\u002Fmlx_llama-3-sqlcoder-8b.csv\" \\\n  -g mlx \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m mlx-community\u002Fdefog-llama-3-sqlcoder-8b\n```\n\n### Gemini\n\nBefore running this, you need to set your credentials with `export GEMINI_API_KEY=\u003Cyour_api_key>`. Then, install these packages with `pip install google-generative-ai`.\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o \"results\u002Fgemini_flash_basic.csv\" \"results\u002Fgemini_flash_basic.csv\" \"results\u002Fgemini_flash_advanced.csv\" \\\n  -g gemini \\\n  -f \"prompts\u002Fprompt_gemini.md\" \"prompts\u002Fprompt_gemini.md\" \"prompts\u002Fprompt_gemini.md\" \\\n  -m gemini-2.0-flash-exp \\\n  -p 10\n```\n\n### Mistral\n\nBefore running this, you must create an account with [Mistral](https:\u002F\u002Fmistral.ai\u002F) and obtain an API key and store it with `export MISTRAL_API_KEY=\u003Cyour_api_key>`. Then, install `mistralai` with `pip install mistralai`.\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o \"results\u002Fresults.csv\" \\\n  -g mistral \\\n  -f \"prompts\u002Fprompt_mistral.md\" \\\n  -m mistral-medium \\\n  -p 5 \\\n  -n 10\n```\n\n### Bedrock\n\nBefore running this, you would need to export the following environment variables for the boto3 client to work:\n- `AWS_ACCESS_KEY_ID`\n- `AWS_SECRET_ACCESS_KEY`\n- `AWS_DEFAULT_REGION`\n\n```bash\npython3 main.py \\\n  -db postgres \\\n  -q data\u002Finstruct_basic_postgres.csv data\u002Finstruct_advanced_postgres.csv data\u002Fquestions_gen_postgres.csv \\\n  -o results\u002Fbedrock_llama_70b_basic.csv results\u002Fbedrock_llama_70b_advanced.csv results\u002Fbedrock_llama_70b_v1.csv \\\n  -g bedrock \\\n  -f prompts\u002Fprompt_cot_postgres.md \\\n  -m meta.llama3-70b-instruct-v1:0 \\\n  -c 0 \\\n  -p 10\n```\n\n### Deepseek\n\nBefore running this, you must create an account with [Deepseek](https:\u002F\u002Fdeepseek.com\u002F) and obtain an API key and store it with `export DEEPSEEK_API_KEY=\u003Cyour_api_key>`. Then, install `openai` with `pip install openai`. You can then run the following command:\n\n#### Deepseek Chat\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fdeepseek_classic.csv results\u002Fdeepseek_basic.csv results\u002Fdeepseek_advanced.csv \\\n  -g deepseek \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m deepseek-chat \\\n  -p 5 \\\n  -c 0\n\n#### Deepseek Reasoner\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fdeepseek_classic.csv results\u002Fdeepseek_basic.csv results\u002Fdeepseek_advanced.csv \\\n  -g deepseek \\\n  -f prompts\u002Fprompt_openai_o1.json \\\n  -m deepseek-reasoner \\\n  -p 5 \\\n  -c 0\n\n\n### Together\n\nBefore running this, you must create an account with [Together.ai](https:\u002F\u002Ftogether.ai\u002F) and obtain an API key and store it with `export TOGETHER_API_KEY=\u003Cyour_api_key>`. Then, install `together` with `pip install together`. You can then run the following command:\n\n```bash\npython3 main.py \\\n  -db postgres \\\n  -q data\u002Finstruct_basic_postgres.csv data\u002Finstruct_advanced_postgres.csv data\u002Fquestions_gen_postgres.csv \\\n  -o results\u002Ftogether_llama_70b_basic.csv results\u002Ftogether_llama_70b_advanced.csv results\u002Ftogether_llama_70b_v1.csv \\\n  -g together \\\n  -f prompts\u002Fprompt_together.json \\\n  -m \"meta-llama\u002FMeta-Llama-3.1-70B-Instruct-Turbo\" \\\n  -c 0 \\\n  -p 10\n```\n\n## CLI Flags\n\nYou can use the following flags in the command line to change the configurations of your evaluation runs.\n\n### Data-related parameters\n\n| CLI Flags              | Description                                                                                                                                                                                                                                                                                          |\n| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -q, --questions_file   | CSV file that contains the test questions and true queries. If this is not set, it will default to the relevant `questions_gen_\u003Cdb_type>.csv` file. It may be helpful to always end your questions*file name with `*\u003Cdb_type>.csv` to ensure compatibility between the queries and selected db_type. |\n| -n, --num_questions    | Use this to limit the total number of questions you want to test.                                                                                                                                                                                                                                    |\n| -db, --db_type         | Database type to run your queries on. Currently supported types are `postgres` and `snowflake`.                                                                                                                                                                                                      |\n| -d, --use_private_data | Use this to read from your own private data library.                                                                                                                                                                                                                                                 |\n| -dp, --decimal_points  | Use this to specify the number of decimal points a result should be rounded to. This is `None` by default                                                                                                                                                                                            |\n\n### Model-related parameters\n\n| CLI Flags        | Description                                                                                                                                                                                                                                                                                                                                                                                       |\n| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -g, --model_type | Model type used. Make sure this matches the model used. Currently defined options in `main.py` are `oa` for OpenAI models, `anthropic` for Anthropic models, `hf` for Hugging Face models, `vllm` for a vllm runner, `api` for API endpoints, `llama_cpp` for llama cpp, `mlx` for mlx, `bedrock` for AWS bedrock API, `together` for together.ai's API           |\n| -m, --model      | Model that will be tested and used to generate the queries. Some options for OpenAI models are chat models `gpt-4o` and `o3-mini`. Options for Anthropic include the latest claude-3 family of models (e.g. `claude-3-opus-20240229`). For Hugging Face, and VLLM models, simply use the path of your chosen model (e.g. `defog\u002Fsqlcoder`). |\n| -a, --adapter    | Path to the relevant adapter model you're using. Only available for the `hf_runner`.                                                                                                                                                                                                                                                                                                              |\n| --api_url        | The URL of the custom API you want to send the prompt to. Only used when model_type is `api`.                                                                                                                                                                                                                                                                                                     |\n| -qz, --quantized | Indicate whether the model is an AWQ quantized model. Only available for `vllm_runner`.                                                                                                                                                                                                                                                                                                           |\n\n### Inference-technique-related parameters\n\n| CLI Flags              | Description  |     |\n| ---------------------- |------------- | --- |\n| -f, --prompt_file      | Markdown file with the prompt used for query generation. You can pass in a list of prompts to test sequentially without reloading the script. |\n| -b, --num_beams        | Indicates the number of beams you want to use for beam search at inference. Only available for `hf_runner`, `vllm_runner`, and `api_runner`. |\n| -c, --num_columns      | Number of columns, default 20. To not prune the columns, set it to 0. |\n| -s, --shuffle_metadata | Shuffle metadata, default False. This shuffles the order of the tables within the schema and the order of the columns within each table but does not shift columns between tables (to preserve the structure of the database). |\n| -k, --k_shot           | Used when you want to include k-shot examples in your prompt. Make sure that the column 'k_shot_prompt' exists in your questions_file. |\n| --cot_table_alias      | (Experimental) Used when you want to include chain-of-thought instructions before the actual sql generation. Allowed values are `instruct`. If using `instruct`, make sure that the placeholder '{cot_instructions}' exists in your prompt file. `instruct` will get your model generate the chain-of-thought table aliases. |\n\n### Execution-related parameters\n\n| CLI Flags              | Description                                                                                                                                                                      |\n| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -o, --output_file      | Output CSV file that will store your results. You need to pass the same number of output file paths as the number of prompt files.                                               |\n| -p, --parallel_threads | No. of parallel workers available for generating and processing queries                                                                                                          |\n| -t, --timeout_gen      | No. of seconds before timeout occurs for query generation. The default is 30.0s.                                                                                                 |\n| -u, --timeout_exec     | No. of seconds before timeout occurs for query execution on the database. The default is 10.0s.                                                                                  |\n| -v, --verbose          | Prints details in command line.                                                                                                                                                  |\n| --upload_url           | (optional) the URL that you want to report the results to. The server that serves this URL must have functionality that is similar to the sample server in `utils\u002Fwebserver.py`. |\n| --run_name             | (optional) the name of this run for logging purposes                                                                                                                             |\n\n## Checking the Results\n\n### Upload URL\n\nIf you would like to start a google cloud function to receive the results, you can use the `--upload_url` flag to specify the URL that you want to report the results to. Before running the evaluation code with this flag, you would need to create a server that serves at the provided URL. We have provided 2 sample cloud function endpoints for writing either to bigquery or postgres, in the `results_fn_bigquery` and `results_fn_postgres` folders. You may also implement your own server to take in similar arguments. Before deploying either cloud functions, you would need to set up the environment variables by making a copy of .env.yaml.template and renaming it to .env.yaml, and then filling in the relevant fields. For the bigquery cloud function, you would also need to put your service account's key.json file in the same folder, and put the file name in the `CREDENTIALS_PATH` field in the .env.yaml file.\n\nAfter doing so, you can deploy the google cloud function:\n\n```bash\n# for uploading to bigquery\ngcloud functions deploy results_bigquery \\\n  --source results_fn_bigquery \\\n  --entry-point bigquery \\\n  --env-vars-file results_fn_bigquery\u002F.env.yaml \\\n  --runtime python311 \\\n  --memory 512MB \\\n  --trigger-http \\\n  --allow-unauthenticated \\\n  --gen2\n\n# for uploading to postgres\ngcloud functions deploy results_postgres \\\n  --source results_fn_postgres \\\n  --entry-point postgres \\\n  --env-vars-file results_fn_postgres\u002F.env.yaml \\\n  --runtime python311 \\\n  --memory 512MB \\\n  --trigger-http \\\n  --allow-unauthenticated \\\n  --gen2\n```\n\nThe cloud function's name is whatever comes after `gcloud functions deploy` (in this case, `results_bigquery`), and you can use it to check the logs of the function by running `gcloud functions logs read results_bigquery`.\n\nYou can then run the evaluation code with the `--upload_url` flag to report the results to the cloud function. The cloud function will then write the results to the relevant database.\n\n```bash\npython main.py \\\n  -db postgres \\\n  -o results\u002Ftest.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m gpt-4o-mini \\\n  -n 1 \\\n  --upload_url \u003Cyour cloud function url>\n```\n\nIf you would like to always report your results to an upload_url, even if it's not explicitly provided, you can set it in your environment variables as `SQL_EVAL_UPLOAD_URL`\n\n#### Testing the function locally\n\nIf you'd like to modify the functions and test it out locally, you can run these sample commands to deploy the function locally and then trigger the openai runner:\n\n```bash\nfunctions-framework --target bigquery --source results_fn_bigquery --debug\npython main.py \\\n  -db postgres \\\n  -o results\u002Ftest.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m gpt-4o-mini \\\n  -n 1 \\\n  --upload_url http:\u002F\u002F127.0.0.1:8080\u002F\n```\n\n## Misc\n\nWe welcome contributions to our project, specifically:\n\n- Dataset\n  - Adding new database schema\u002Fdata\n- Framework code\n  - Improving existing generators\u002Frunners (e.g. adding new metrics)\n\nPlease see [CONTRIBUTING.md](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-generation-evaluation\u002Fblob\u002Fmain\u002FCONTRIBUTING.md) for more information.\n","# SQL 生成评估\n\n此仓库包含 Defog 用于评估生成的 SQL 的代码。它基于 [Spider](https:\u002F\u002Fgithub.com\u002Ftaoyds\u002Fspider) 的模式，但使用了一组全新的人工精选问题和查询，并按查询类别分组。如需深入了解我们创建这一评估方法的过程，请参阅[这篇博文](https:\u002F\u002Fdefog.ai\u002Fblog\u002Fopen-sourcing-sqleval\u002F)。\n\n## 简介\n\n我们的测试流程包括以下步骤。对于每一对问题和查询：\n\n1. 我们生成一条 SQL 查询（可能来自大语言模型）。\n2. 我们在各自的数据库上分别运行“黄金”查询和生成的查询，以获得两个包含结果的数据框。\n3. 我们使用“精确匹配”和“子集匹配”来比较这两个数据框。TODO 添加博客文章链接。\n4. 我们将这些结果以及其他感兴趣的指标（例如使用的 token 数、延迟）记录下来，并汇总结果以生成报告。\n\n## 入门指南\n\n这是一份全面的说明文档，假定您对命令行、Docker、在数据库上执行 SQL 查询以及常用的 Python 数据处理库（例如 pandas）有一定的了解。\n\n### 安装依赖\n\n首先，克隆我们存储数据库数据和模式的仓库。安装 `requirements.txt` 文件中列出的所有 Python 库。如果您使用 NER 启发式方法来实现我们的[元数据剪枝方法](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fblob\u002Fmain\u002Futils\u002Fpruning.py)（即 `c` 参数设置为大于 0 的任意值，详见下文），则还需要下载一个 spaCy 模型。最后，安装该库。\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data.git\ncd defog-data\npip install -r requirements.txt\npip install -e .\n```\n\n### 启动 Postgres 实例\n\n接下来，您需要设置用于执行查询的数据库。我们在此使用 Postgres，因为它是在生产环境中分布最广、使用最广泛的开源数据库。此外，我们建议使用 Docker 来完成此操作，因为这是最简单的入门方式。您可以[在这里](https:\u002F\u002Fdocs.docker.com\u002Fget-docker\u002F)安装 Docker。\n\n安装 Docker 后，您可以使用以下命令创建 Docker 容器并启动 Postgres 数据库。我们建议将卷挂载到 `data\u002Fpostgres` 目录以持久化数据，同时将卷挂载到 `data\u002Fexport` 目录以便于导入数据。要创建容器，请运行：\n\n```bash\nmkdir data\u002Fpostgres data\u002Fexport\ndocker create --name postgres-sql-eval -e POSTGRES_PASSWORD=postgres -p 5432:5432 -v $(pwd)\u002Fdata\u002Fpostgres:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata -v $(pwd)\u002Fdata\u002Fexport:\u002Fexport postgres:16-alpine\n```\n\n要启动容器，请运行：\n\n```bash\ndocker start postgres-sql-eval\n```\n\n如果您想重置 Postgres 服务器实例的状态（例如由于临时连接导致的内存泄漏），可以将其关闭（并在之后重新启动）：\n\n```bash\ndocker stop postgres-sql-eval\n# 查看容器是否仍在：\ndocker container list -a\n```\n\n注意事项：\n\n- 在运行上述命令之前，您需要先停止其他正在监听 5432 端口的 Postgres 实例。\n- 您只需运行一次 `docker create ...` 命令来创建镜像，之后只需运行 `docker start\u002Fstop postgres-sql-eval`。\n- 数据会持久化在 `data\u002Fpostgres` 目录中，因此关闭容器并不关键。然而，如果删除 `data\u002Fpostgres` 文件夹，所有数据都将丢失 T.T。\n- 虽然我们将使用 Docker 来部署 Postgres 并进行初始化，但您也可以根据自己的本地安装情况修改脚本或说明。\n\n### 将数据导入 Postgres\n\n待导入的数据位于我们先前克隆的 `defog-data` 仓库中。每个文件夹包含对应单个数据库的元数据和数据（例如 `academic` 文件夹包含重新加载 “academic” 数据库所需的所有数据）。我们假设您已在本地安装了 `psql` 客户端。我们将使用以下命令在我们的 Postgres 实例中为 7 个 SQL 数据库中的每一个创建一个新的数据库：\n\n```bash\n# 设置以下环境变量\ncd defog-data # 如果您尚未进入 defog-data 目录\nexport DBPASSWORD=\"postgres\"\nexport DBUSER=\"postgres\"\nexport DBHOST=\"localhost\"\nexport DBPORT=5432\n.\u002Fsetup.sh\n```\n\n### 将数据导入 Snowflake\n\n如果您希望将数据导入 Snowflake，相关设置说明也位于 `defog-data` 仓库中。在安装 [Snowflake CLI](https:\u002F\u002Fdocs.snowflake.com\u002Fen\u002Fuser-guide\u002Fsnowsql-install-config) 后，按照[文档](https:\u002F\u002Fdocs.snowflake.com\u002Fen\u002Fuser-guide\u002Fsnowsql-config)配置您的凭据，并将其设置为如下所示的环境变量，然后运行设置命令。\n\n```sh\nexport SFDBPASSWORD=\"your_password\"\nexport SFDBUSER=\"your_username\"\nexport SFDBACCOUNT=\"your_account\"\nexport SFDBWAREHOUSE=\"your_warehouse\"\n.\u002Fsetup_snowflake.sh\n```\n\n请注意，在评估过程中，您需要使用 `\u002Fdata` 目录下的 `_snowflake` 问题文件。这些查询已修改为适用于 Snowflake 数据库。\n\n### 将数据导入 BigQuery、MySQL、SQLite、SQL Server\n\n这些数据库管理系统的设置说明位于 `defog-data` 仓库中。请相应地配置您的凭据，设置好环境变量，然后使用以下命令转换并导入评估数据库：\n\n```python\npython translate_ddl_dialect.py\n```\n\n在评估过程中，您需要设置正确的 `--db_type` 标志，并使用 `\u002Fdata` 目录下对应的 `{dialect}` 问题文件。\n\n### 使用私有数据（可选）\n\n如果您拥有不想公开的私有数据集，但仍希望复用此处的代码进行评估，可以按照以下步骤操作。\n\n- 首先为您的私有数据创建一个独立的 Git 仓库，并在其中包含 `setup.py` 文件，类似于 [defog-data](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data)。\n- 创建元数据和数据文件，并将它们导入到您的数据库中。这样做是为了让我们的评估框架能够使用实际数据运行生成的查询。您可以参考 `defog-data` 的 [元数据对象](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fmain\u002Fdefog_data\u002Fmetadata.py) 来了解表结构，以及 [setup.sh](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fmain\u002Fsetup.sh) 作为如何将数据导入数据库的示例。我们不规定具体的文件夹结构，您可以根据自己的需求自由组织数据，只要能够方便地将其导入数据库即可。\n- 要使用我们的元数据剪枝工具，您需要定义以下内容：\n  - 一种用于定义表之间可连接列的方法。在我们的案例中，我们使用一个字典 [columns_join](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data\u002Fblob\u002Fdb8c3d4c4004144d2b3ff5a2701529f5545f520f\u002Fdefog_data\u002Fsupplementary.py#L233)，其键为数据库名称，值则是嵌套字典，表示表元组与列名元组之间的对应关系。您可以参考原始数据来了解我们是如何生成这个字典的。\n\n完成上述三个步骤后，您需要：\n\n- 将您的数据库作为依赖项安装，运行 `pip install -e .`（`-e` 参数可使代码更改自动生效，无需重新安装）。\n- 将 [prune_metadata_str](utils\u002Fpruning.py#L165) 中的相关函数调用和变量替换为您自己导入的函数和变量。请注意，您可能不会将包\u002F模块命名为 `defog_data_private.supplementary`，因此请根据实际情况进行修改。\n\n需要注意的几点：\n\n- 如果您没有向数据库中填充数据（即仅创建表而未插入数据），大多数情况下会返回空的数据框（无论生成的查询是否符合预期），这会导致所有结果都匹配，并产生大量假阳性。因此，建议您向数据库中填充一些有意义的数据，以便在查询不符合预期时能够返回不同的结果。\n- 如果您使用私有数据进行测试，还需要将问题文件指向您自己的问题文件（根据您的数据库模式定制）。\n\n### 运行器\n\n运行器负责处理每个问题\u002F查询对的工作配置（例如并行化、批处理、所选模型等）。\n\n我们提供了几种常见的运行器：`runners\u002Fopenai_runner.py` 用于调用 OpenAI 的 API（支持并行化）、`runners\u002Fanthropic_runner` 用于调用 Anthropic 的 API、`runners\u002Fhf_runner.py` 用于调用本地 Hugging Face 模型，最后，`runners\u002Fapi_runner.py` 允许您使用自定义 API 进行评估。\n\n## 运行测试\n\n### OpenAI\n\n如果您计划调用 OpenAI 或 Anthropic 等 LLM API，请务必在运行测试前将您的 API 密钥（`OPENAI_API_KEY` 或 `ANTHROPIC_API_KEY`）设置为环境变量。\n\n要仅使用 10 个问题（而不是全部 200 个）进行测试，并以 5 个任务并行执行：\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fopenai_classic.csv results\u002Fopenai_basic.csv results\u002Fopenai_advanced.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m o3-mini \\\n  -p 5 \\\n  -c 0\n```\n\n如果使用最新的 `o1-*` 模型进行测试（这些模型不支持系统提示词），则应使用不同的提示词文件，减少并行请求数量并增加超时时间：\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fopenai_o1mini_classic.csv results\u002Fopenai_o1mini_basic.csv results\u002Fopenai_o1mini_advanced.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai_o1.json \\\n  -m o1-mini \\\n  -p 1 \\\n  -t 120 \\\n  -c 0\n```\n\n### Anthropic\n\n要对 Claude-3 的完整问题集进行测试：\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fclaude3_classic.csv results\u002Fclaude3_basic.csv results\u002Fclaude3_advanced.csv \\\n  -g anthropic \\\n  -f prompts\u002Fprompt_anthropic.md \\\n  -m claude-3-opus-20240229 \\\n  -p 5 \\\n  -c 0\n```\n\n### Hugging Face\n\n要使用我们微调的 SQL 模型仅测试 10 个问题（而不是全部 200 个）：\n\n```bash\n# 使用 -W 选项忽略关于连续使用 transformers pipeline 的警告\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fhf_classic.csv results\u002Fhf_basic.csv results\u002Fhf_advanced.csv \\\n  -g hf \\\n  -f prompts\u002Fprompt.md \\\n  -m defog\u002Fllama-3-sqlcoder-8b \\\n  -c 0\n```\n\n我们还支持通过 `-a` 标志加载 PEFT 适配器。请注意，加载适配器会使模型的加载时间比平时稍长。\n\n### vLLM\n\n我们还有一个 [vllm](https:\u002F\u002Fblog.vllm.ai\u002F) 运行器，它使用 vLLM 引擎将推理过程作为一个批次整体运行。这种方式速度更快，尤其是在 `num_beams` 大于 1 时。您需要传入合并后的模型权重、LoRA 适配器路径（如果适用），并且模型架构必须受 vLLM 支持。以下是一个示例命令：\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fvllm_classic.csv results\u002Fvllm_basic.csv results\u002Fvllm_advanced.csv \\\n  -g vllm \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m defog\u002Fllama-3-sqlcoder-8b \\\n  -a path\u002Fto_adapter \\\n  -c 0\n```\n\n可选地，如果您正在评估使用 AWQ 量化的模型，可以添加 `-qz` 或 `--quantized` 参数。此选项仅适用于 vLLM 运行器。\n\n### 使用 API 服务器运行\n\n如果需要以不同设置运行测试，可以搭建一个 API 服务器，避免每次测试时都重新加载配置，然后依次运行测试。我们支持搭建两种类型的 API 服务器，即 vLLM API 服务器和 TGI 服务器。\n\n我们还提供对 vLLM API 服务器的自定义修改版本，该版本仅返回生成的输出。\n\n#### VLLM API 服务器\n\n```bash\n# 设置 vLLM 服务器\npython -m vllm.entrypoints.api_server \\\n    --model defog\u002Fdefog-llama-3-sqlcoder-8b \\\n    --tensor-parallel-size 4 \\\n    --dtype float16\n\n# 用于设置支持 LoRA 适配器的 vLLM 服务器\npython -m vllm.entrypoints.api_server \\\n    --model defog\u002Fllama-3-sqlcoder-8b \\\n    --tensor-parallel-size 1 \\\n    --dtype float16 \\\n    --max-model-len 4096 \\\n    --enable-lora \\\n    --max-lora-rank 64\n\n# 使用我们修改后的 API 服务器\npython utils\u002Fapi_server.py \\\n    --model defog\u002Fllama-3-sqlcoder-8b \\\n    --tensor-parallel-size 4 \\\n    --dtype float16 \\\n    --max-model-len 4096 \\\n    --enable-lora \\\n    --max-lora-rank 64\n\n# 使用 vLLM 的 OpenAI 兼容 API 服务器\nexport MODEL_NAME=\"Qwen\u002FQwen3-4B\"\nvllm serve \"$MODEL_NAME\" --port 8000\n\n# 使用 API 运行器执行 SQL 评估——根据 GPU 的性能，可以将 p 和 b 的值调高\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fapi.csv \\\n  -g api \\\n  -b 1 \\\n  -f prompts\u002Fprompt.md \\\n  --api_url \"http:\u002F\u002Flocalhost:8000\u002Fgenerate\" \\\n  --api_type \"vllm\" \\\n  -a path\u002Fto_adapter_if_applicable \\\n  -p 8\n```\n\n#### TGI API 服务器\n\n您可以查阅 [TGI 文档](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftext-generation-inference\u002Fquicktour) 以获取有关如何设置 TGI 服务器的更多信息。以下是一个使用预设 Docker 镜像设置 TGI 服务器并使用 API 运行器运行评估的示例命令。请注意，您需要根据可用的 GPU 数量和所选模型相应地调整分片数和模型 ID。\n\n```bash\n# 设置 TGI 服务器\nmodel=\"defog\u002Fllama-3-sqlcoder-8b\"\ndocker run --gpus all \\\n  --shm-size 1g \\\n  -p 8000:80 \\\n  -v \u002Fmodels:\u002Fmodels ghcr.io\u002Fhuggingface\u002Ftext-generation-inference:2.0 \\\n  --model-id \"${model}\" \\\n  --max-best-of 4 \\\n  --max-input-tokens 3072 \\\n  --sharded true \\\n  --num-shard 4 \\\n  --hostname 0.0.0.0 \\\n  --port 80\n\n# 使用 API 运行器执行 SQL 评估——根据 GPU 的性能，可以将 p 和 b 的值调高。请注意，TGI 中的 CUDA 图默认针对 2 的幂次方批量大小进行了优化。\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fapi.csv \\\n  -g api \\\n  -b 1 \\\n  -f prompts\u002Fprompt.md \\\n  --api_url \"http:\u002F\u002Flocalhost:8000\u002Fgenerate\" \\\n  --api_type \"vllm\" \\\n  -p 8\n```\n\n#### 多个提示\n\n如果您希望在一次运行中测试多个提示（以节省每次运行开始时将模型加载到 GPU 上所需的几分钟时间），可以在 `--prompt_file` 中指定提示文件列表（例如 `-f prompts\u002Fprompt-1.md prompts\u002Fprompt-2.md prompts\u002Fprompt-3.md`），并在 `--output_file` 中指定相应的输出文件列表（例如 `-o results\u002Fresults-1.csv results\u002Fresults-2.csv results\u002Fresults-3.csv`）。提示和输出文件的数量必须相同。以下是一个示例命令：\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fresults_1.csv results\u002Fresults_2.csv \\\n  -g vllm \\\n  -f prompts\u002Fprompt_1.md prompts\u002Fprompt_2.md \\\n  -m defog\u002Fsqlcoder2\n```\n\n虽然其他运行器也可以这样做，但在本地加载大型模型与调用始终在线的 API 相比，节省的时间最为显著。\n\n#### 思考型模型\n\n如果您想使用会输出思考标记的模型，可以在运行器中传递 `--enable_thinking` 标志，这样我们在运行生成的查询之前会从 LLM 输出中移除思考标记。\n\n您可以查看 `run_qwen.sh` 以了解如何运行思考型模型的示例。\n\n```bash\n.\u002Frun_qwen.sh --thinking # 添加 --thinking 以生成思考标记\n```\n\n### Bedrock\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o results\u002Fllama3_70b.csv \\\n  -g bedrock \\\n  -f prompts\u002Fprompt.md \\\n  -m meta.llama3-70b-instruct-v1:0\n```\n\n### Llama CPP\n\n要使用 Llama CPP 运行评估，可以使用以下代码。在运行之前，您必须按照以下方式安装 `llama-cpp-python`（适用于 Apple Silicon）：\n\n`CMAKE_ARGS=\"-DLLAMA_METAL=on\" pip install llama-cpp-python`\n\n请注意，`llama-cpp-python` 库目前不支持束搜索，因此结果质量会较低。\n\n```bash\npython -W ignore main.py \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -db postgres \\\n  -o \"results\u002Fllama_cpp.csv\" \\\n  -g llama_cpp \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m path\u002Fto\u002Fmodel.gguf\n```\n\n### MLX\n\n要使用 MLX 运行评估，可以使用以下代码。在运行之前，您必须使用 `pip install mlx-lm` 安装 `mlx-lm` 包。\n\n请注意，MLX 目前也不支持束搜索，因此结果质量会较低。\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o \"results\u002Fmlx_llama-3-sqlcoder-8b.csv\" \\\n  -g mlx \\\n  -f \"prompts\u002Fprompt.md\" \\\n  -m mlx-community\u002Fdefog-llama-3-sqlcoder-8b\n```\n\n### Gemini\n\n在运行之前，您需要通过 `export GEMINI_API_KEY=\u003Cyour_api_key>` 设置您的凭据。然后，使用 `pip install google-generative-ai` 安装相关包。\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o \"results\u002Fgemini_flash_basic.csv\" \"results\u002Fgemini_flash_basic.csv\" \"results\u002Fgemini_flash_advanced.csv\" \\\n  -g gemini \\\n  -f \"prompts\u002Fprompt_gemini.md\" \"prompts\u002Fprompt_gemini.md\" \"prompts\u002Fprompt_gemini.md\" \\\n  -m gemini-2.0-flash-exp \\\n  -p 10\n```\n\n### Mistral\n\n在运行之前，您必须先在 [Mistral](https:\u002F\u002Fmistral.ai\u002F) 上注册账户并获取 API 密钥，然后将其存储为 `export MISTRAL_API_KEY=\u003Cyour_api_key>`。之后，使用 `pip install mistralai` 安装 `mistralai`。\n\n```bash\npython -W ignore main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \\\n  -o \"results\u002Fresults.csv\" \\\n  -g mistral \\\n  -f \"prompts\u002Fprompt_mistral.md\" \\\n  -m mistral-medium \\\n  -p 5 \\\n  -n 10\n```\n\n### Bedrock\n\n在运行之前，您需要导出以下环境变量，以便 boto3 客户端能够正常工作：\n- `AWS_ACCESS_KEY_ID`\n- `AWS_SECRET_ACCESS_KEY`\n- `AWS_DEFAULT_REGION`\n\n```bash\npython3 main.py \\\n  -db postgres \\\n  -q data\u002Finstruct_basic_postgres.csv data\u002Finstruct_advanced_postgres.csv data\u002Fquestions_gen_postgres.csv \\\n  -o results\u002Fbedrock_llama_70b_basic.csv results\u002Fbedrock_llama_70b_advanced.csv results\u002Fbedrock_llama_70b_v1.csv \\\n  -g bedrock \\\n  -f prompts\u002Fprompt_cot_postgres.md \\\n  -m meta.llama3-70b-instruct-v1:0 \\\n  -c 0 \\\n  -p 10\n```\n\n### Deepseek\n\n在运行此命令之前，您必须先在 [Deepseek](https:\u002F\u002Fdeepseek.com\u002F) 上注册一个账户，并获取 API 密钥，然后使用 `export DEEPSEEK_API_KEY=\u003Cyour_api_key>` 将其存储起来。接着，通过 `pip install openai` 安装 `openai` 库。之后即可运行以下命令：\n\n#### Deepseek Chat\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fdeepseek_classic.csv results\u002Fdeepseek_basic.csv results\u002Fdeepseek_advanced.csv \\\n  -g deepseek \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m deepseek-chat \\\n  -p 5 \\\n  -c 0\n\n#### Deepseek Reasoner\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fdeepseek_classic.csv results\u002Fdeepseek_basic.csv results\u002Fdeepseek_advanced.csv \\\n  -g deepseek \\\n  -f prompts\u002Fprompt_openai_o1.json \\\n  -m deepseek-reasoner \\\n  -p 5 \\\n  -c 0\n\n\n### Together\n\n在运行此命令之前，您必须先在 [Together.ai](https:\u002F\u002Ftogether.ai\u002F) 上注册一个账户，并获取 API 密钥，然后使用 `export TOGETHER_API_KEY=\u003Cyour_api_key>` 将其存储起来。接着，通过 `pip install together` 安装 `together` 库。之后即可运行以下命令：\n\n```bash\npython3 main.py \\\n  -db postgres \\\n  -q data\u002Finstruct_basic_postgres.csv data\u002Finstruct_advanced_postgres.csv data\u002Fquestions_gen_postgres.csv \\\n  -o results\u002Ftogether_llama_70b_basic.csv results\u002Ftogether_llama_70b_advanced.csv results\u002Ftogether_llama_70b_v1.csv \\\n  -g together \\\n  -f prompts\u002Fprompt_together.json \\\n  -m \"meta-llama\u002FMeta-Llama-3.1-70B-Instruct-Turbo\" \\\n  -c 0 \\\n  -p 10\n```\n\n## CLI 标志\n\n您可以在命令行中使用以下标志来更改评估运行的配置。\n\n### 数据相关参数\n\n| CLI 标志              | 描述                                                                                                                                                                                                                                                                                          |\n| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -q, --questions_file   | 包含测试问题和正确查询的 CSV 文件。如果未设置，则默认使用相应的 `questions_gen_\u003Cdb_type>.csv` 文件。建议始终将您的问题文件名以 `*\u003Cdb_type>.csv` 结尾，以确保查询与所选数据库类型兼容。 |\n| -n, --num_questions    | 使用此选项可限制要测试的问题总数。                                                                                                                                                                                                                                    |\n| -db, --db_type         | 要在其上运行查询的数据库类型。目前支持的类型包括 `postgres` 和 `snowflake`。                                                                                                                                                                                                      |\n| -d, --use_private_data | 使用此选项从您自己的私有数据集读取数据。                                                                                                                                                                                                                                                 |\n| -dp, --decimal_points  | 使用此选项指定结果应四舍五入的小数位数。默认值为 `None`。                                                                                                                                                                                            |\n\n### 模型相关参数\n\n| CLI 标志        | 描述                                                                                                                                                                                                                                                                                                                                                                                       |\n| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -g, --model_type | 所使用的模型类型。请确保此选项与实际使用的模型匹配。当前在 `main.py` 中定义的选项包括：`oa` 表示 OpenAI 模型，`anthropic` 表示 Anthropic 模型，`hf` 表示 Hugging Face 模型，`vllm` 表示 vllm 运行器，`api` 表示 API 端点，`llama_cpp` 表示 llama cpp，`mlx` 表示 mlx，`bedrock` 表示 AWS Bedrock API，`together` 表示 together.ai 的 API           |\n| -m, --model      | 将被测试并用于生成查询的模型。OpenAI 模型的一些选项包括聊天模型 `gpt-4o` 和 `o3-mini`。Anthropic 的选项则包括最新的 Claude-3 系列模型（例如 `claude-3-opus-20240229`）。对于 Hugging Face 和 VLLM 模型，只需使用您所选模型的路径即可（例如 `defog\u002Fsqlcoder`）。 |\n| -a, --adapter    | 您正在使用的相关适配器模型的路径。仅适用于 `hf_runner`。                                                                                                                                                                                                                                                                                                              |\n| --api_url        | 您希望将提示发送到的自定义 API 的 URL。仅当 `model_type` 为 `api` 时使用。                                                                                                                                                                                                                                                                                                     |\n| -qz, --quantized | 表示该模型是否为 AWQ 量化模型。仅适用于 `vllm_runner`。                                                                                                                                                                                                                                                                                                           |\n\n### 推理技术相关参数\n\n| CLI 标志              | 描述  |     |\n| ---------------------- |------------- | --- |\n| -f, --prompt_file      | 包含用于生成查询的提示的 Markdown 文件。您可以传入一个提示列表，按顺序进行测试，而无需重新加载脚本。 |\n| -b, --num_beams        | 指定推理时要使用的束搜索束数。仅适用于 `hf_runner`、`vllm_runner` 和 `api_runner`。 |\n| -c, --num_columns      | 列数，默认为 20。若不希望剪枝列，请将其设置为 0。 |\n| -s, --shuffle_metadata | 打乱元数据，默认为 False。此选项会打乱模式中表的顺序以及每张表内列的顺序，但不会在表之间移动列（以保持数据库结构）。 |\n| -k, --k_shot           | 当您希望在提示中包含 k-shot 示例时使用。请确保您的 `questions_file` 中存在 `k_shot_prompt` 列。 |\n| --cot_table_alias      | （实验性）当您希望在实际 SQL 生成之前包含思维链指令时使用。允许值为 `instruct`。如果使用 `instruct`，请确保您的提示文件中存在占位符 `{cot_instructions}`。`instruct` 将使模型生成思维链表别名。 |\n\n### 执行相关参数\n\n| CLI 标志              | 描述                                                                                                                                                                      |\n| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| -o, --output_file      | 用于存储结果的输出 CSV 文件。您需要传递与提示文件数量相同的输出文件路径。                                               |\n| -p, --parallel_threads | 用于生成和处理查询的并行工作线程数                                                                                                          |\n| -t, --timeout_gen      | 查询生成超时前的秒数。默认值为 30.0 秒。                                                                                                 |\n| -u, --timeout_exec     | 数据库上查询执行超时前的秒数。默认值为 10.0 秒。                                                                                  |\n| -v, --verbose          | 在命令行中打印详细信息。                                                                                                                                                  |\n| --upload_url           | （可选）您希望报告结果的 URL。提供此 URL 的服务器必须具备与 `utils\u002Fwebserver.py` 中示例服务器类似的功能。 |\n| --run_name             | （可选）本次运行的名称，用于日志记录                                                                                                                             |\n\n## 检查结果\n\n### 上传 URL\n\n如果您希望启动 Google Cloud Function 来接收结果，可以使用 `--upload_url` 标志指定您希望报告结果的 URL。在使用该标志运行评估代码之前，您需要创建一个在提供的 URL 上提供服务的服务器。我们已在 `results_fn_bigquery` 和 `results_fn_postgres` 文件夹中提供了两个示例 Cloud Function 端点，分别用于写入 BigQuery 或 PostgreSQL。您也可以实现自己的服务器来接收类似的参数。在部署任何 Cloud Function 之前，您需要通过复制 `.env.yaml.template` 并将其重命名为 `.env.yaml`，然后填写相关字段来设置环境变量。对于 BigQuery Cloud Function，您还需要将服务账户的 `key.json` 文件放在同一文件夹中，并将文件名填入 `.env.yaml` 文件中的 `CREDENTIALS_PATH` 字段。\n\n完成上述步骤后，您可以部署 Google Cloud Function：\n\n```bash\n# 用于上传到 BigQuery\ngcloud functions deploy results_bigquery \\\n  --source results_fn_bigquery \\\n  --entry-point bigquery \\\n  --env-vars-file results_fn_bigquery\u002F.env.yaml \\\n  --runtime python311 \\\n  --memory 512MB \\\n  --trigger-http \\\n  --allow-unauthenticated \\\n  --gen2\n\n# 用于上传到 PostgreSQL\ngcloud functions deploy results_postgres \\\n  --source results_fn_postgres \\\n  --entry-point postgres \\\n  --env-vars-file results_fn_postgres\u002F.env.yaml \\\n  --runtime python311 \\\n  --memory 512MB \\\n  --trigger-http \\\n  --allow-unauthenticated \\\n  --gen2\n```\n\nCloud Function 的名称是 `gcloud functions deploy` 后面的部分（本例中为 `results_bigquery`），您可以通过运行 `gcloud functions logs read results_bigquery` 来查看该函数的日志。\n\n随后，您可以使用 `--upload_url` 标志运行评估代码，将结果报告给 Cloud Function。Cloud Function 那么会将结果写入相应的数据库。\n\n```bash\npython main.py \\\n  -db postgres \\\n  -o results\u002Ftest.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m gpt-4o-mini \\\n  -n 1 \\\n  --upload_url \u003C您的 Cloud Function URL>\n```\n\n如果您希望始终将结果报告到 `upload_url`，即使未显式提供，也可以在环境变量中将其设置为 `SQL_EVAL_UPLOAD_URL`。\n\n#### 在本地测试函数\n\n如果您想修改这些函数并在本地进行测试，可以运行以下示例命令，在本地部署函数并触发 OpenAI 运行器：\n\n```bash\nfunctions-framework --target bigquery --source results_fn_bigquery --debug\npython main.py \\\n  -db postgres \\\n  -o results\u002Ftest.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m gpt-4o-mini \\\n  -n 1 \\\n  --upload_url http:\u002F\u002F127.0.0.1:8080\u002F\n```\n\n## 其他\n\n我们欢迎对本项目做出贡献，特别是：\n\n- 数据集\n  - 添加新的数据库模式\u002F数据\n- 框架代码\n  - 改进现有生成器\u002F运行器（例如添加新指标）\n\n更多信息请参阅 [CONTRIBUTING.md](https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-generation-evaluation\u002Fblob\u002Fmain\u002FCONTRIBUTING.md)。","# sql-eval 快速上手指南\n\n`sql-eval` 是 Defog 开源的 SQL 生成评估工具，用于测试大语言模型（LLM）生成 SQL 查询的准确性。它基于 Spider 数据集模式，但使用了新的手工筛选问题集，支持多种数据库后端（Postgres, Snowflake, BigQuery 等）和多种模型接口（OpenAI, Anthropic, Hugging Face, vLLM 等）。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**：Linux 或 macOS（Windows 用户建议使用 WSL2 或 Docker Desktop）。\n*   **基础工具**：\n    *   Git\n    *   Python 3.8+\n    *   Docker（推荐用于快速部署数据库）\n    *   `psql` 客户端（用于 Postgres 数据导入）\n*   **前置知识**：熟悉命令行操作、Docker 基本用法及 Python 数据库（如 pandas）。\n*   **API Key**：如果测试商业模型，需准备好 `OPENAI_API_KEY` 或 `ANTHROPIC_API_KEY` 环境变量。\n\n> **提示**：国内用户在安装 Python 依赖时，建议指定清华或阿里镜像源以加速下载：\n> `pip install -r requirements.txt -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n\n## 安装步骤\n\n### 1. 克隆数据仓库并安装依赖\n\n首先克隆存放数据库模式和数据的 `defog-data` 仓库，并安装相关 Python 库。\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fdefog-data.git\ncd defog-data\npip install -r requirements.txt\npip install -e .\n```\n\n*(可选)* 如果使用元数据剪枝功能（`-c` 参数大于 0），还需安装 spacy 模型：\n```bash\npython -m spacy download en_core_web_sm\n```\n\n### 2. 启动 Postgres 数据库实例\n\n使用 Docker 快速启动一个持久化的 Postgres 实例。\n\n**创建容器**（只需执行一次）：\n```bash\nmkdir data\u002Fpostgres data\u002Fexport\ndocker create --name postgres-sql-eval -e POSTGRES_PASSWORD=postgres -p 5432:5432 -v $(pwd)\u002Fdata\u002Fpostgres:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata -v $(pwd)\u002Fdata\u002Fexport:\u002Fexport postgres:16-alpine\n```\n\n**启动容器**：\n```bash\ndocker start postgres-sql-eval\n```\n\n> **注意**：请确保本地没有其他进程占用 5432 端口。数据将持久化存储在 `data\u002Fpostgres` 目录中。\n\n### 3. 导入评估数据\n\n将测试所需的元数据和样本数据导入到刚启动的 Postgres 实例中。\n\n```bash\n# 确保在 defog-data 目录下\nexport DBPASSWORD=\"postgres\"\nexport DBUSER=\"postgres\"\nexport DBHOST=\"localhost\"\nexport DBPORT=5432\n.\u002Fsetup.sh\n```\n\n## 基本使用\n\n以下示例展示如何使用 OpenAI 模型对 10 个问题进行并行评估。\n\n**前提**：设置环境变量\n```bash\nexport OPENAI_API_KEY=\"your_api_key_here\"\n```\n\n**运行测试命令**：\n该命令将针对 Postgres 数据库，使用 `o3-mini` 模型，并行度为 5，测试部分问题集。\n\n```bash\npython main.py \\\n  -db postgres \\\n  -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n  -o results\u002Fopenai_classic.csv results\u002Fopenai_basic.csv results\u002Fopenai_advanced.csv \\\n  -g oa \\\n  -f prompts\u002Fprompt_openai.json \\\n  -m o3-mini \\\n  -p 5 \\\n  -c 0\n```\n\n**参数说明：**\n*   `-db`: 数据库类型 (postgres, snowflake 等)。\n*   `-q`: 输入的问题文件路径（支持多个）。\n*   `-o`: 输出结果文件路径。\n*   `-g`: 运行器类型 (`oa` 代表 OpenAI, `anthropic`, `hf`, `vllm` 等)。\n*   `-f`: Prompt 模板文件。\n*   `-m`: 模型名称。\n*   `-p`: 并行请求数量。\n*   `-c`: 元数据剪枝阈值（0 表示禁用）。\n\n**其他模型示例：**\n\n*   **Anthropic (Claude 3)**:\n    ```bash\n    export ANTHROPIC_API_KEY=\"your_key\"\n    python main.py -db postgres -q \"data\u002Fquestions_gen_postgres.csv\" ... -g anthropic -m claude-3-opus-20240229 -p 5 -c 0\n    # 注意：实际使用时请补全 -o 和 -f 参数，参考上文完整命令\n    ```\n\n*   **本地 Hugging Face 模型**:\n    ```bash\n    python -W ignore main.py \\\n      -db postgres \\\n      -q \"data\u002Fquestions_gen_postgres.csv\" \"data\u002Finstruct_basic_postgres.csv\" \"data\u002Finstruct_advanced_postgres.csv\" \\\n      -o results\u002Fhf_classic.csv results\u002Fhf_basic.csv results\u002Fhf_advanced.csv \\\n      -g hf \\\n      -f prompts\u002Fprompt.md \\\n      -m defog\u002Fllama-3-sqlcoder-8b \\\n      -c 0\n    ```\n\n运行结束后，评估结果（包括精确匹配率、子集匹配率、Token 消耗等）将保存至指定的 `-o` CSV 文件中。","某数据团队正在为内部财务系统开发基于大模型的 Text-to-SQL 助手，旨在让非技术人员通过自然语言查询复杂的销售数据库。\n\n### 没有 sql-eval 时\n- **评估标准模糊**：团队仅靠人工肉眼对比生成的 SQL 与标准答案，难以量化模型在复杂嵌套查询上的准确率，导致优化方向不明。\n- **结果验证低效**：每次微调模型后，需手动将“黄金查询”和“生成查询”分别在数据库中运行并导出结果进行比对，耗时且容易出错。\n- **缺乏细粒度洞察**：无法自动识别模型在特定类别（如多表连接或时间聚合）上的短板，只能凭感觉调整提示词，迭代周期长达数天。\n- **指标记录缺失**：缺少对 Token 消耗、推理延迟等关键性能指标的自动化记录，难以在准确率与成本之间找到最佳平衡点。\n\n### 使用 sql-eval 后\n- **量化评估精准**：利用 sql-eval 内置的 Spider 架构变体及手工精选问答集，自动执行“精确匹配”和“子集匹配”，瞬间输出可信赖的准确率评分。\n- **自动化闭环验证**：工具自动在 Docker 隔离的 Postgres 环境中并发运行双份查询并对比返回的 DataFrame，将单次评估时间从小时级缩短至分钟级。\n- **分类弱点定位**：自动生成按查询类别分组的详细报告，清晰指出模型在“多表关联”场景表现不佳，指导团队针对性地增强 Few-shot 示例。\n- **多维数据沉淀**：自动记录并聚合 Token 用量与延迟数据，帮助团队在保持高准确率的同时，成功将单次查询成本降低了 30%。\n\nsql-eval 将原本依赖人工经验的模糊评估过程，转化为可量化、自动化且具备深度洞察的工程化闭环，显著加速了 Text-to-SQL 模型的落地迭代。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdefog-ai_sql-eval_cc49049f.png","defog-ai","Defog.ai","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fdefog-ai_3d75b05f.png","LLMs for data analysis",null,"founders@defog.ai","defogdata","https:\u002F\u002Fdefog.ai","https:\u002F\u002Fgithub.com\u002Fdefog-ai",[87,91,95],{"name":88,"color":89,"percentage":90},"Jupyter Notebook","#DA5B0B",52.6,{"name":92,"color":93,"percentage":94},"Python","#3572A5",45.1,{"name":96,"color":97,"percentage":98},"Shell","#89e051",2.3,740,73,"2026-04-04T11:33:43","Apache-2.0",4,"Linux, macOS, Windows","非必需。仅在本地运行 Hugging Face 或 vLLM 模型时推荐\u002F需要 NVIDIA GPU；具体型号和显存取决于所选模型（如运行 8B 参数模型通常需 16GB+ 显存）。若使用 API (OpenAI\u002FAnthropic) 或数据库评估则无需 GPU。","未说明（建议至少 8GB，运行大型本地模型时推荐 16GB+）",{"notes":108,"python":109,"dependencies":110},"1. 必须安装 Docker 以启动 Postgres 数据库容器（默认使用 postgres:16-alpine 镜像）。\n2. 需克隆独立的 defog-data 仓库以获取测试数据和 schema。\n3. 本地需安装 psql 客户端用于数据导入。\n4. 若使用特定启发式方法（metadata-pruning），需下载 spacy 模型。\n5. 支持多种数据库后端（Postgres, Snowflake, BigQuery, MySQL, SQLite, SQL Server），需相应配置凭据。\n6. 运行本地模型时需注意模型权重和适配器（LoRA）的加载时间。","未明确指定版本（需支持 pandas 及主流深度学习库，通常建议 Python 3.8+）",[111,112,113,114,115,116,117,118],"pandas","docker","psycopg2 (或 psql 客户端)","spacy (可选，用于 NER)","transformers (用于 HF runner)","vllm (用于 vLLM runner)","torch","accelerate",[15,46],"2026-03-27T02:49:30.150509","2026-04-10T20:32:39.712631",[123,128,133,138,143,147],{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},28220,"如何生成评估过程中需要的 embeddings.pkl 文件？","embeddings.pkl 文件是由另一个依赖库 defog-data 生成的。你可以查看该库中的 generate_embeddings 函数来了解具体生成逻辑。该文件用于元数据剪枝（pruning），需通过安装并运行 defog-data 库的相关脚本来创建。","https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fissues\u002F22",{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},28221,"运行基准测试时，显示的查询类别（query_categories）与官方博客列出的不一致，这是为什么？","博客中列出的类别（如 where, join）是逻辑分类，而实际运行时显示的类别（如 instruct, table_join）是代码内部的具体实现标签。例如，'instruct' 通常对应逻辑上的 'where' 条件过滤。这种命名差异源于内部实现细节，不影响评估结果的有效性。","https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fissues\u002F94",{"id":134,"question_zh":135,"answer_zh":136,"source_url":137},28222,"在使用 OpenAI 模型进行评估时，Prompt 中的 assistant_prompt 部分似乎没有正确格式化用户问题，这会影响结果吗？","这是一个有效的观察，但在实践中，OpenAI 的 ChatCompletion 端点通常会忽略 assistant prompt 中的静态文本，主要关注 user prompt。维护者测试发现，即使修复代码将 user_question 填入 assistant_prompt，GPT-4-turbo 的准确率仍保持在 83% 不变。虽然不影响结果，但代码库已提交 PR 进行了修复以保持一致性。","https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fissues\u002F54",{"id":139,"question_zh":140,"answer_zh":141,"source_url":142},28223,"部分测试用例的预期 SQL 似乎不正确或不一致，如何处理这种情况？","社区已发现部分测试用例的预期 SQL 存在逻辑错误（例如未正确计算平均值或引用计数）。维护者已确认这些问题，并通过 PR 更新了数据集和预期查询。例如，对于计算平均评分的问题，已将预期 SQL 修正为使用 JOIN 连接 review 表并使用 AVG() 聚合函数，而非直接读取 business 表中的字段。建议在使用前拉取最新代码以获取修正后的测试集。","https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fissues\u002F65",{"id":144,"question_zh":145,"answer_zh":146,"source_url":132},28224,"如何在不同机器上部署模型和数据库以运行大规模评估？","如果模型和数据库运行在不同机器上，可以使用 vLLM 服务器模式。你不需要专门创建一个独立的 server 进程，可以直接在 Python 进程中运行 vLLM 代码。对于多卡环境（如 4xA100），确保正确配置 vLLM 的启动参数以利用所有 GPU 资源。PostgreSQL 是推荐的数据库类型，但其他数据库类型通常也可以正常工作。",{"id":148,"question_zh":149,"answer_zh":150,"source_url":151},28225,"运行 PostgreSQL 评估时报错 'ValueError: not enough values to unpack'，该如何解决？","该错误通常发生在元数据剪枝阶段，原因是列信息字符串格式解析失败。这可能是因为本地部署的模型或数据版本不匹配。请确保使用的是最新的代码库，并检查是否正确安装了 defog-data 依赖。如果是使用 OpenAI 模型进行测试，请尝试使用标准的命令行参数运行（如指定 -db postgres 和正确的 prompt 文件），维护者在复现时并未遇到此问题，表明可能是环境配置差异导致。","https:\u002F\u002Fgithub.com\u002Fdefog-ai\u002Fsql-eval\u002Fissues\u002F165",[]]