[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-minimaxir--simpleaichat":3,"tool-minimaxir--simpleaichat":62},[4,18,28,37,45,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":24,"last_commit_at":25,"category_tags":26,"status":17},9989,"n8n","n8n-io\u002Fn8n","n8n 是一款面向技术团队的公平代码（fair-code）工作流自动化平台，旨在让用户在享受低代码快速构建便利的同时，保留编写自定义代码的灵活性。它主要解决了传统自动化工具要么过于封闭难以扩展、要么完全依赖手写代码效率低下的痛点，帮助用户轻松连接 400 多种应用与服务，实现复杂业务流程的自动化。\n\nn8n 特别适合开发者、工程师以及具备一定技术背景的业务人员使用。其核心亮点在于“按需编码”：既可以通过直观的可视化界面拖拽节点搭建流程，也能随时插入 JavaScript 或 Python 代码、调用 npm 包来处理复杂逻辑。此外，n8n 原生集成了基于 LangChain 的 AI 能力，支持用户利用自有数据和模型构建智能体工作流。在部署方面，n8n 提供极高的自由度，支持完全自托管以保障数据隐私和控制权，也提供云端服务选项。凭借活跃的社区生态和数百个现成模板，n8n 让构建强大且可控的自动化系统变得简单高效。",184740,2,"2026-04-19T23:22:26",[16,14,13,15,27],"插件",{"id":29,"name":30,"github_repo":31,"description_zh":32,"stars":33,"difficulty_score":10,"last_commit_at":34,"category_tags":35,"status":17},10095,"AutoGPT","Significant-Gravitas\u002FAutoGPT","AutoGPT 是一个旨在让每个人都能轻松使用和构建 AI 的强大平台，核心功能是帮助用户创建、部署和管理能够自动执行复杂任务的连续型 AI 智能体。它解决了传统 AI 应用中需要频繁人工干预、难以自动化长流程工作的痛点，让用户只需设定目标，AI 即可自主规划步骤、调用工具并持续运行直至完成任务。\n\n无论是开发者、研究人员，还是希望提升工作效率的普通用户，都能从 AutoGPT 中受益。开发者可利用其低代码界面快速定制专属智能体；研究人员能基于开源架构探索多智能体协作机制；而非技术背景用户也可直接选用预置的智能体模板，立即投入实际工作场景。\n\nAutoGPT 的技术亮点在于其模块化“积木式”工作流设计——用户通过连接功能块即可构建复杂逻辑，每个块负责单一动作，灵活且易于调试。同时，平台支持本地自托管与云端部署两种模式，兼顾数据隐私与使用便捷性。配合完善的文档和一键安装脚本，即使是初次接触的用户也能在几分钟内启动自己的第一个 AI 智能体。AutoGPT 正致力于降低 AI 应用门槛，让人人都能成为 AI 的创造者与受益者。",183572,"2026-04-20T04:47:55",[13,36,27,14,15],"语言模型",{"id":38,"name":39,"github_repo":40,"description_zh":41,"stars":42,"difficulty_score":10,"last_commit_at":43,"category_tags":44,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":46,"name":47,"github_repo":48,"description_zh":49,"stars":50,"difficulty_score":24,"last_commit_at":51,"category_tags":52,"status":17},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 真正成长为懂上",161147,"2026-04-19T23:31:47",[14,13,36],{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":59,"last_commit_at":60,"category_tags":61,"status":17},8272,"opencode","anomalyco\u002Fopencode","OpenCode 是一款开源的 AI 编程助手（Coding Agent），旨在像一位智能搭档一样融入您的开发流程。它不仅仅是一个代码补全插件，而是一个能够理解项目上下文、自主规划任务并执行复杂编码操作的智能体。无论是生成全新功能、重构现有代码，还是排查难以定位的 Bug，OpenCode 都能通过自然语言交互高效完成，显著减少开发者在重复性劳动和上下文切换上的时间消耗。\n\n这款工具专为软件开发者、工程师及技术研究人员设计，特别适合希望利用大模型能力来提升编码效率、加速原型开发或处理遗留代码维护的专业人群。其核心亮点在于完全开源的架构，这意味着用户可以审查代码逻辑、自定义行为策略，甚至私有化部署以保障数据安全，彻底打破了传统闭源 AI 助手的“黑盒”限制。\n\n在技术体验上，OpenCode 提供了灵活的终端界面（Terminal UI）和正在测试中的桌面应用程序，支持 macOS、Windows 及 Linux 全平台。它兼容多种包管理工具，安装便捷，并能无缝集成到现有的开发环境中。无论您是追求极致控制权的资深极客，还是渴望提升产出的独立开发者，OpenCode 都提供了一个透明、可信",144296,1,"2026-04-16T14:50:03",[13,27],{"id":63,"github_repo":64,"name":65,"description_en":66,"description_zh":67,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":78,"owner_email":79,"owner_twitter":80,"owner_website":81,"owner_url":82,"languages":83,"stars":88,"forks":89,"last_commit_at":90,"license":91,"difficulty_score":24,"env_os":92,"env_gpu":93,"env_ram":94,"env_deps":95,"category_tags":101,"github_topics":102,"view_count":24,"oss_zip_url":80,"oss_zip_packed_at":80,"status":17,"created_at":105,"updated_at":106,"faqs":107,"releases":138},10026,"minimaxir\u002Fsimpleaichat","simpleaichat","Python package for easily interfacing with chat apps, with robust features and minimal code complexity.","simpleaichat 是一个专为 Python 开发者设计的轻量级库，旨在以极简的代码轻松对接 ChatGPT、GPT-4 等主流聊天模型。它主要解决了传统 AI 集成方案代码繁琐、Token 消耗高导致成本与延迟增加的问题，让开发者无需深入底层细节即可快速构建应用。\n\n无论是希望快速原型验证的工程师，还是需要高效处理多任务的研究人员，simpleaichat 都能提供极大便利。其核心亮点在于极致的优化工作流：仅需几行代码即可创建并运行对话，支持异步处理和流式响应，能显著减少 Token 用量从而降低费用并提升速度。此外，它还具备同时运行多个独立会话的能力，并允许通过结构化数据模型构建复杂的智能体（Agent）工作流。\n\n除了作为开发库，simpleaichat 还贴心地提供了命令行交互模式，用户可直接在终端启动自定义角色的对话，甚至模拟特定风格（如用表情符号说话或模仿影视角色），为测试和娱乐增添了趣味。如果你追求在保持代码简洁的同时，充分挖掘现代大模型的潜力，simpleaichat 是一个值得尝试的高效工具。","# simpleaichat\n\n```py3\nfrom simpleaichat import AIChat\n\nai = AIChat(system=\"Write a fancy GitHub README based on the user-provided project name.\")\nai(\"simpleaichat\")\n```\n\nsimpleaichat is a Python package for easily interfacing with chat apps like ChatGPT and GPT-4 with robust features and minimal code complexity. This tool has many features optimized for working with ChatGPT as fast and as cheap as possible, but still much more capable of modern AI tricks than most implementations:\n\n- Create and run chats with only a few lines of code!\n- Optimized workflows which minimize the amount of tokens used, reducing costs and latency.\n- Run multiple independent chats at once.\n- Minimal codebase: no code dives to figure out what's going on under the hood needed!\n- Chat streaming responses and the ability to use tools.\n- Async support, including for streaming and tools.\n- Ability to create more complex yet clear workflows if needed, such as Agents. (Demo soon!)\n- Coming soon: more chat model support (PaLM, Claude)!\n\nHere's some fun, hackable examples on how simpleaichat works:\n\n- Creating a [Python coding assistant](examples\u002Fnotebooks\u002Fsimpleaichat_coding.ipynb) without any unnecessary accompanying output, allowing 5x faster generation at 1\u002F3rd the cost. ([Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fsimpleaichat_coding.ipynb))\n- Allowing simpleaichat to [provide inline tips](examples\u002Fnotebooks\u002Fchatgpt_inline_tips.ipynb) following ChatGPT usage guidelines. ([Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fchatgpt_inline_tips.ipynb))\n- Async interface for [conducting many chats](examples\u002Fnotebooks\u002Fsimpleaichat_async.ipynb) in the time it takes to receive one AI message. ([Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fsimpleaichat_async.ipynb))\n- Create your own Tabletop RPG (TTRPG) setting and campaign by using [advanced structured data models](examples\u002Fnotebooks\u002Fschema_ttrpg.ipynb). ([Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fschema_ttrpg.ipynb))\n\n## Installation\n\nsimpleaichat can be installed [from PyPI](https:\u002F\u002Fpypi.org\u002Fproject\u002Fsimpleaichat\u002F):\n\n```sh\npip3 install simpleaichat\n```\n\n## Quick, Fun Demo\n\nYou can demo chat-apps very quickly with simpleaichat! First, you will need to get an OpenAI API key, and then with one line of code:\n\n```py3\nfrom simpleaichat import AIChat\n\nAIChat(api_key=\"sk-...\")\n```\n\nAnd with that, you'll be thrust directly into an interactive chat!\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_627cc7a137af.png)\n\nThis AI chat will mimic the behavior of OpenAI's webapp, but on your local computer!\n\nYou can also pass the API key by storing it in an `.env` file with a `OPENAI_API_KEY` field in the working directory (recommended), or by setting the environment variable of `OPENAI_API_KEY` directly to the API key.\n\nBut what about creating your own custom conversations? That's where things get fun. Just input whatever person, place or thing, fictional or nonfictional, that you want to chat with!\n\n```py3\nAIChat(\"GLaDOS\")  # assuming API key loaded via methods above\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_d9074fe90a5b.png)\n\nBut that's not all! You can customize exactly how they behave too with additional commands!\n\n```py3\nAIChat(\"GLaDOS\", \"Speak in the style of a Seinfeld monologue\")\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_18d15ba10b94.png)\n\n```py3\nAIChat(\"Ronald McDonald\", \"Speak using only emoji\")\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_83f3081bafe5.png)\n\nNeed some socialization immediately? Once simpleaichat is installed, you can also start these chats directly from the command line!\n\n```sh\nsimpleaichat\nsimpleaichat \"GlaDOS\"\nsimpleaichat \"GLaDOS\" \"Speak in the style of a Seinfeld monologue\"\n```\n\n## Building AI-based Apps\n\nThe trick with working with new chat-based apps that wasn't readily available with earlier iterations of GPT-3 is the addition of the system prompt: a different class of prompt that guides the AI behavior throughout the entire conversation. In fact, the chat demos above are actually using [system prompt tricks](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002FPROMPTS.md#interactive-chat) behind the scenes! OpenAI has also released an official guide for [system prompt best practices](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fgpt-best-practices) to building AI apps.\n\nFor developers, you can instantiate a programmatic instance of `AIChat` by explicitly specifying a system prompt, or by disabling the console.\n\n```py3\nai = AIChat(system=\"You are a helpful assistant.\")\nai = AIChat(console=False)  # same as above\n```\n\nYou can also pass in a `model` parameter, such as `model=\"gpt-4\"` if you have access to GPT-4, or `model=\"gpt-3.5-turbo-16k\"` for a larger-context-window ChatGPT.\n\nYou can then feed the new `ai` class with user input, and it will return and save the response from ChatGPT:\n\n```py3\nresponse = ai(\"What is the capital of California?\")\nprint(response)\n```\n\n```\nThe capital of California is Sacramento.\n```\n\nAlternatively, you can stream responses by token with a generator if the text generation itself is too slow:\n\n```py3\nfor chunk in ai.stream(\"What is the capital of California?\", params={\"max_tokens\": 5}):\n    response_td = chunk[\"response\"]  # dict contains \"delta\" for the new token and \"response\"\n    print(response_td)\n```\n\n```\nThe\nThe capital\nThe capital of\nThe capital of California\nThe capital of California is\n```\n\nFurther calls to the `ai` object will continue the chat, automatically incorporating previous information from the conversation.\n\n```py3\nresponse = ai(\"When was it founded?\")\nprint(response)\n```\n\n```\nSacramento was founded on February 27, 1850.\n```\n\nYou can also save chat sessions (as CSV or JSON) and load them later. The API key is not saved so you will have to provide that when loading.\n\n```py3\nai.save_session()  # CSV, will only save messages\nai.save_session(format=\"json\", minify=True)  # JSON\n\nai.load_session(\"my.csv\")\nai.load_session(\"my.json\")\n```\n\n### Functions\n\nA large number of popular venture-capital-funded ChatGPT apps don't actually use the \"chat\" part of the model. Instead, they just use the system prompt\u002Ffirst user prompt as a form of natural language programming. You can emulate this behavior by passing a new system prompt when generating text, and not saving the resulting messages.\n\nThe `AIChat` class is a manager of chat _sessions_, which means you can have multiple independent chats or functions happening! The examples above use a default session, but you can create new ones by specifying a `id` when calling `ai`.\n\n```py3\njson = '{\"title\": \"An array of integers.\", \"array\": [-1, 0, 1]}'\nfunctions = [\n             \"Format the user-provided JSON as YAML.\",\n             \"Write a limerick based on the user-provided JSON.\",\n             \"Translate the user-provided JSON from English to French.\"\n            ]\nparams = {\"temperature\": 0.0, \"max_tokens\": 100}  # a temperature of 0.0 is deterministic\n\n# We namespace the function by `id` so it doesn't affect other chats.\n# Settings set during session creation will apply to all generations from the session,\n# but you can change them per-generation, as is the case with the `system` prompt here.\nai = AIChat(id=\"function\", params=params, save_messages=False)\nfor function in functions:\n    output = ai(json, id=\"function\", system=function)\n    print(output)\n```\n\n```txt\ntitle: \"An array of integers.\"\narray:\n  - -1\n  - 0\n  - 1\n```\n\n```txt\nAn array of integers so neat,\nWith values that can't be beat,\nFrom negative to positive one,\nIt's a range that's quite fun,\nThis JSON is really quite sweet!\n```\n\n```txt\n{\"titre\": \"Un tableau d'entiers.\", \"tableau\": [-1, 0, 1]}\n```\n\nNewer versions of ChatGPT also support \"[function calling](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fgpt\u002Ffunction-calling)\", but the real benefit of that feature is the ability for ChatGPT to support structured input and\u002For output, which now opens up a wide variety of applications! simpleaichat streamlines the workflow to allow you to just pass an `input_schema` and\u002For an `output_schema`.\n\nYou can construct a schema using a [pydantic](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002F) BaseModel.\n\n```py3\nfrom pydantic import BaseModel, Field\n\nai = AIChat(\n    console=False,\n    save_messages=False,  # with schema I\u002FO, messages are never saved\n    model=\"gpt-3.5-turbo-0613\",\n    params={\"temperature\": 0.0},\n)\n\nclass get_event_metadata(BaseModel):\n    \"\"\"Event information\"\"\"\n\n    description: str = Field(description=\"Description of event\")\n    city: str = Field(description=\"City where event occured\")\n    year: int = Field(description=\"Year when event occured\")\n    month: str = Field(description=\"Month when event occured\")\n\n# returns a dict, with keys ordered as in the schema\nai(\"First iPhone announcement\", output_schema=get_event_metadata)\n```\n\n```txt\n{'description': 'The first iPhone was announced by Apple Inc.',\n 'city': 'San Francisco',\n 'year': 2007,\n 'month': 'January'}\n```\n\nSee the [TTRPG Generator Notebook](examples\u002Fnotebooks\u002Fschema_ttrpg.ipynb) for a more elaborate demonstration of schema capabilities.\n\n### Tools\n\nOne of the most recent aspects of interacting with ChatGPT is the ability for the model to use \"tools.\" As popularized by [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain), tools allow the model to decide when to use custom functions, which can extend beyond just the chat AI itself, for example retrieving recent information from the internet not present in the chat AI's training data. This workflow is analogous to ChatGPT Plugins.\n\nParsing the model output to invoke tools typically requires a number of shennanigans, but simpleaichat uses [a neat trick](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002FPROMPTS.md#tools) to make it fast and reliable! Additionally, the specified tools return a `context` for ChatGPT to draw from for its final response, and tools you specify can return a dictionary which you can also populate with arbitrary metadata for debugging and postprocessing. Each generation returns a dictionary with the `response` and the `tool` function used, which can be used to set up workflows akin to [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain)-style Agents, e.g. recursively feed input to the model until it determines it does not need to use any more tools.\n\nYou will need to specify functions with docstrings which provide hints for the AI to select them:\n\n```py3\nfrom simpleaichat.utils import wikipedia_search, wikipedia_search_lookup\n\n# This uses the Wikipedia Search API.\n# Results from it are nondeterministic, your mileage will vary.\ndef search(query):\n    \"\"\"Search the internet.\"\"\"\n    wiki_matches = wikipedia_search(query, n=3)\n    return {\"context\": \", \".join(wiki_matches), \"titles\": wiki_matches}\n\ndef lookup(query):\n    \"\"\"Lookup more information about a topic.\"\"\"\n    page = wikipedia_search_lookup(query, sentences=3)\n    return page\n\nparams = {\"temperature\": 0.0, \"max_tokens\": 100}\nai = AIChat(params=params, console=False)\n\nai(\"San Francisco tourist attractions\", tools=[search, lookup])\n```\n\n```txt\n{'context': \"Fisherman's Wharf, San Francisco, Tourist attractions in the United States, Lombard Street (San Francisco)\",\n 'titles': [\"Fisherman's Wharf, San Francisco\",\n  'Tourist attractions in the United States',\n  'Lombard Street (San Francisco)'],\n 'tool': 'search',\n 'response': \"There are many popular tourist attractions in San Francisco, including Fisherman's Wharf and Lombard Street. Fisherman's Wharf is a bustling waterfront area known for its seafood restaurants, souvenir shops, and sea lion sightings. Lombard Street, on the other hand, is a famous winding street with eight hairpin turns that attract visitors from all over the world. Both of these attractions are must-sees for anyone visiting San Francisco.\"}\n```\n\n```py3\nai(\"Lombard Street?\", tools=[search, lookup])\n```\n\n```\n{'context': 'Lombard Street is an east–west street in San Francisco, California that is famous for a steep, one-block section with eight hairpin turns. Stretching from The Presidio east to The Embarcadero (with a gap on Telegraph Hill), most of the street\\'s western segment is a major thoroughfare designated as part of U.S. Route 101. The famous one-block section, claimed to be \"the crookedest street in the world\", is located along the eastern segment in the Russian Hill neighborhood.',\n 'tool': 'lookup',\n 'response': 'Lombard Street is a famous street in San Francisco, California known for its steep, one-block section with eight hairpin turns. It stretches from The Presidio to The Embarcadero, with a gap on Telegraph Hill. The western segment of the street is a major thoroughfare designated as part of U.S. Route 101, while the famous one-block section, claimed to be \"the crookedest street in the world\", is located along the eastern segment in the Russian Hill'}\n```\n\n```py3\nai(\"Thanks for your help!\", tools=[search, lookup])\n```\n\n```txt\n{'response': \"You're welcome! If you have any more questions or need further assistance, feel free to ask.\",\n 'tool': None}\n```\n\n## Miscellaneous Notes\n\n- Like [gpt-2-simple](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fgpt-2-simple) before it, the primary motivation behind releasing simpleaichat is to both democratize access to ChatGPT even more and also offer more transparency for non-engineers into how Chat AI-based apps work under the hood given the disproportionate amount of media misinformation about their capabilities. This is inspired by real-world experience from [my work with BuzzFeed](https:\u002F\u002Ftech.buzzfeed.com\u002Fthe-right-tools-for-the-job-c05de96e949e) in the domain, where after spending a long time working with the popular [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain), a more-simple implementation was both much easier to maintain and resulted in much better generations. I began focusing development on simpleaichat after reading a [Hacker News thread](https:\u002F\u002Fnews.ycombinator.com\u002Fitem?id=35820931) filled with many similar complaints, indicating value for an easier-to-use interface for modern AI tricks.\n  - simpleaichat very intentionally avoids coupling features with common use cases where possible (e.g. Tools) in order to avoid software lock-in due to the difficulty implementing anything not explicitly mentioned in the project's documentation. The philosophy behind simpleaichat is to provide good demos, and let the user's creativity and business needs take priority instead of having to fit a round peg into a square hole like with LangChain.\n  - simpleaichat makes it easier to interface with Chat AIs, but it does not attempt to solve common technical and ethical problems inherent to large language models trained on the internet, including prompt injection and unintended plagiarism. The user should exercise good judgment when implementing simpleaichat. Use cases of simpleaichat which go against OpenAI's [usage policies](https:\u002F\u002Fopenai.com\u002Fpolicies\u002Fusage-policies) (including jailbreaking) will not be endorsed.\n  - simpleaichat intentionally does not use the \"Agent\" logical metaphor for tool workflows because it's become an AI hype buzzword heavily divorced from its origins. If needed be, you can emulate the Agent workflow with a `while` loop without much additional code, plus with the additional benefit of much more flexibility such as debugging.\n- The session manager implements some sensible security defaults, such as using UUIDs as session ids by default, storing authentication information in a way to minimize unintentional leakage, and type enforcement via Pydantic. Your end-user application should still be aware of potential security issues, however.\n- Although OpenAI's documentation says that system prompts are less effective than a user prompt constructed in a similar manner, in my experience it still does perform better for maintaining rules\u002Fa persona.\n- Many examples of popular prompts use more conversational prompts, while the example prompts here use more consise and imperative prompts. This aspect of prompt engineering is still evolving, but in my experience commands do better with ChatGPT and with greater token efficieny. That's also why simpleaichat allows users to specify system prompts (and explicitly highlights what the default use) instead of relying on historical best practices.\n- Token counts for async is not supported as OpenAI doesn't return token counts when streaming responses. In general, there may be some desync in token counts and usage for various use cases; I'm working on categorizing them.\n- Outside of the explicit examples, none of this README uses AI-generated text. The introduction code example is just a joke, but it was too good of a real-world use case!\n\n## Roadmap\n\n- PaLM Chat (Bard) and Anthropic Claude support\n- More fun\u002Ffeature-filled CLI chat app based on Textual\n- Simple example of using simpleaichat in a webapp\n- Simple of example of using simpleaichat in a stateless manner (e.g. AWS Lambda functions)\n\n## Maintainer\u002FCreator\n\nMax Woolf ([@minimaxir](https:\u002F\u002Fminimaxir.com))\n\n_Max's open-source projects are supported by his [Patreon](https:\u002F\u002Fwww.patreon.com\u002Fminimaxir) and [GitHub Sponsors](https:\u002F\u002Fgithub.com\u002Fsponsors\u002Fminimaxir). If you found this project helpful, any monetary contributions to the Patreon are appreciated and will be put to good creative use._\n\n## License\n\nMIT\n","# simpleaichat\n\n```py3\nfrom simpleaichat import AIChat\n\nai = AIChat(system=\"根据用户提供的项目名称，撰写一份精美的 GitHub README。\")\nai(\"simpleaichat\")\n```\n\nsimpleaichat 是一个 Python 包，旨在以最少的代码复杂度和强大的功能，轻松地与 ChatGPT、GPT-4 等聊天应用进行交互。该工具专为高效、低成本地使用 ChatGPT 而设计，同时在现代 AI 技巧方面远超大多数实现方式：\n\n- 仅需几行代码即可创建并运行对话！\n- 优化的工作流程可最大限度减少使用的 token 数量，从而降低费用并缩短响应时间。\n- 可同时运行多个独立的对话。\n- 代码库极简：无需深入理解底层细节！\n- 支持流式回复以及工具调用。\n- 提供异步支持，包括流式传输和工具调用。\n- 如有需要，还可构建更复杂但清晰的工作流，例如智能体。（演示即将推出！）\n- 即将支持更多聊天模型（如 PaLM、Claude）！\n\n以下是几个有趣且可玩的示例，展示 simpleaichat 的强大功能：\n\n- 创建一个 [Python 编程助手](examples\u002Fnotebooks\u002Fsimpleaichat_coding.ipynb)，完全避免不必要的输出，使生成速度提升 5 倍，成本仅为原来的三分之一。（[Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fsimpleaichat_coding.ipynb)）\n- 让 simpleaichat 按照 ChatGPT 使用指南，提供 [内联提示](examples\u002Fnotebooks\u002Fchatgpt_inline_tips.ipynb)。（[Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fchatgpt_inline_tips.ipynb)）\n- 使用异步接口，在接收一条 AI 消息的时间内，同时进行 [多轮对话](examples\u002Fnotebooks\u002Fsimpleaichat_async.ipynb)。（[Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fsimpleaichat_async.ipynb)）\n- 利用 [高级结构化数据模型](examples\u002Fnotebooks\u002Fschema_ttrpg.ipynb)，创建属于你自己的桌面角色扮演游戏（TTRPG）设定与战役。（[Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002Fexamples\u002Fnotebooks\u002Fschema_ttrpg.ipynb)）\n\n## 安装\n\n您可以通过 [PyPI](https:\u002F\u002Fpypi.org\u002Fproject\u002Fsimpleaichat\u002F) 安装 simpleaichat：\n\n```sh\npip3 install simpleaichat\n```\n\n## 快速趣味演示\n\n使用 simpleaichat，您可以非常迅速地体验聊天应用！首先，您需要获取 OpenAI API 密钥，然后只需一行代码：\n\n```py3\nfrom simpleaichat import AIChat\n\nAIChat(api_key=\"sk-...\")\n```\n\n如此一来，您便可以直接进入一个交互式聊天界面！\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_627cc7a137af.png)\n\n这个 AI 聊天模拟了 OpenAI 官网应用的行为，只不过是在您的本地计算机上运行！\n\n您也可以通过在工作目录下创建一个包含 `OPENAI_API_KEY` 字段的 `.env` 文件来存储 API 密钥（推荐），或者直接将环境变量 `OPENAI_API_KEY` 设置为您的 API 密钥。\n\n那么，如何创建自定义对话呢？这就更有趣了！只需输入您想与之交谈的任何人物、地点或事物——无论是虚构的还是真实的——即可！\n\n```py3\nAIChat(\"GLaDOS\")  # 假设已通过上述方法加载 API 密钥\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_d9074fe90a5b.png)\n\n但这还不是全部！您还可以通过额外的指令精确控制他们的行为！\n\n```py3\nAIChat(\"GLaDOS\", \"以《宋飞正传》独白的风格说话\")\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_18d15ba10b94.png)\n\n```py3\nAIChat(\"麦当劳叔叔\", \"只用表情符号交流\")\n```\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_readme_83f3081bafe5.png)\n\n想要立即来一场社交互动吗？安装 simpleaichat 后，您甚至可以直接从命令行启动这些对话！\n\n```sh\nsimpleaichat\nsimpleaichat \"GlaDOS\"\nsimpleaichat \"GLaDOS\" \"以《宋飞正传》独白的风格说话\"\n```\n\n## 构建基于 AI 的应用\n\n与早期 GPT-3 不同的是，新一代聊天型应用引入了系统提示这一新特性：这是一种能够引导整个对话中 AI 行为的特殊类型提示。事实上，上面的聊天演示实际上都暗含了 [系统提示技巧](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002FPROMPTS.md#interactive-chat)！OpenAI 还发布了官方指南 [系统提示最佳实践](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fgpt-best-practices)，帮助开发者构建 AI 应用。\n\n对于开发者而言，您可以通过显式指定系统提示，或关闭控制台模式，来实例化 `AIChat` 类的程序化对象。\n\n```py3\nai = AIChat(system=\"您是一位乐于助人的助手。\")\nai = AIChat(console=False)  # 与上相同\n```\n\n您还可以传递 `model` 参数，例如如果您有权访问 GPT-4，则可以设置为 `model=\"gpt-4\"`；如果使用具有更大上下文窗口的 ChatGPT，则可以设置为 `model=\"gpt-3.5-turbo-16k\"`。\n\n随后，您可以向新的 `ai` 对象输入用户问题，它会返回并保存来自 ChatGPT 的回复：\n\n```py3\nresponse = ai(\"加州的首都是哪里？\")\nprint(response)\n```\n\n```\n加州的首都是萨克拉门托。\n```\n\n此外，如果文本生成速度较慢，您还可以通过生成器按 token 流式获取回复：\n\n```py3\nfor chunk in ai.stream(\"加州的首都是哪里？\", params={\"max_tokens\": 5}):\n    response_td = chunk[\"response\"]  # 字典包含新增 token 的“delta”及完整回复\n    print(response_td)\n```\n\n```\n加\n加利\n加利福\n加利福尼亚\n加利福尼亚州\n加利福尼亚州是\n```\n\n再次调用 `ai` 对象将继续对话，并自动整合之前的对话内容。\n\n```py3\nresponse = ai(\"它是什么时候建立的？\")\nprint(response)\n```\n\n```\n萨克拉门托成立于 1850 年 2 月 27 日。\n```\n\n您还可以将聊天会话保存为 CSV 或 JSON 格式，并在以后加载。不过，API 密钥不会被保存，因此在加载时仍需提供。\n\n```py3\nai.save_session()  # 保存为 CSV，仅保存消息\nai.save_session(format=\"json\", minify=True)  # 保存为 JSON\n\nai.load_session(\"my.csv\")\nai.load_session(\"my.json\")\n```\n\n### 函数\n\n许多由风投支持的热门 ChatGPT 应用其实并未真正利用模型的“聊天”功能。相反，它们只是将系统提示或首次用户提示当作一种自然语言编程的方式。您可以通过在生成文本时传递新的系统提示，并不保存生成的消息，来模仿这种行为。\n\n`AIChat` 类管理的是聊天 _会话_，这意味着您可以同时进行多个独立的对话或函数调用！上述示例使用的是默认会话，但您可以通过在调用 `ai` 时指定 `id` 来创建新的会话。\n\n```py3\njson = '{\"title\": \"一个整数数组\", \"array\": [-1, 0, 1]}'\nfunctions = [\n             \"将用户提供的 JSON 格式化为 YAML。\",\n             \"根据用户提供的 JSON 写一首打油诗。\",\n             \"将用户提供的 JSON 从英语翻译成法语。\"\n            ]\nparams = {\"temperature\": 0.0, \"max_tokens\": 100}  # 温度为 0.0 时，结果是确定性的\n\n# 我们通过 `id` 对函数进行命名空间划分，这样就不会影响其他对话。\n# 在会话创建时设置的参数将应用于该会话中的所有生成内容，\n# 但你也可以为每次生成单独更改这些参数，就像这里的 `system` 提示一样。\nai = AIChat(id=\"function\", params=params, save_messages=False)\nfor function in functions:\n    output = ai(json, id=\"function\", system=function)\n    print(output)\n```\n\n```txt\n标题: \"一个整数数组。\"\n数组:\n  - -1\n  - 0\n  - 1\n```\n\n```txt\n一个整数数组多么整齐，\n数值之妙无人能及，\n从负一到正一，\n范围真是有趣极，\n这份 JSON 真是美妙无比！\n```\n\n```txt\n{\"titre\": \"Un tableau d'entiers.\", \"tableau\": [-1, 0, 1]}\n```\n\nChatGPT 的新版本还支持“[函数调用](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fgpt\u002Ffunction-calling)”，但该功能真正的优势在于它能够支持结构化输入和\u002F或输出，这为各种应用场景打开了大门！simpleaichat 简化了工作流程，让你只需传递 `input_schema` 和\u002F或 `output_schema` 即可。\n\n你可以使用 [pydantic](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002F) 的 BaseModel 来构建模式。\n\n```py3\nfrom pydantic import BaseModel, Field\n\nai = AIChat(\n    console=False,\n    save_messages=False,  # 使用模式 I\u002FO 时，消息永远不会被保存\n    model=\"gpt-3.5-turbo-0613\",\n    params={\"temperature\": 0.0},\n)\n\nclass get_event_metadata(BaseModel):\n    \"\"\"活动信息\"\"\"\n\n    description: str = Field(description=\"活动描述\")\n    city: str = Field(description=\"活动举办城市\")\n    year: int = Field(description=\"活动举办年份\")\n    month: str = Field(description=\"活动举办月份\")\n\n# 返回一个字典，键的顺序与模式中定义的一致\nai(\"首款 iPhone 发布会\", output_schema=get_event_metadata)\n```\n\n```txt\n{'description': '首款 iPhone 是由苹果公司发布的。',\n 'city': '旧金山',\n 'year': 2007,\n 'month': '一月'}\n```\n\n更多关于模式功能的详细演示，请参阅 [TTRPG 生成器笔记本](examples\u002Fnotebooks\u002Fschema_ttrpg.ipynb)。\n\n### 工具\n\n与 ChatGPT 交互的最新方式之一是让模型使用“工具”。正如 [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain) 所推广的那样，工具使模型能够决定何时调用自定义函数，这些函数不仅可以扩展聊天 AI 本身的功能，还可以用于从互联网上检索聊天 AI 训练数据中未包含的最新信息。这种工作流程类似于 ChatGPT 插件。\n\n解析模型输出以调用工具通常需要一些复杂的操作，但 simpleaichat 使用了一个巧妙的技巧 ([a neat trick](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fblob\u002Fmain\u002FPROMPTS.md#tools))，使其快速且可靠！此外，指定的工具会返回一个 `context`，供 ChatGPT 在最终响应中参考；你指定的工具还可以返回一个字典，其中可以填充任意元数据，用于调试和后处理。每次生成都会返回一个包含 `response` 和所用 `tool` 函数的字典，这可用于构建类似 [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain) 风格代理的工作流，例如递归地向模型提供输入，直到模型判断不再需要使用任何工具为止。\n\n你需要指定带有文档字符串的函数，以便为 AI 提供选择工具的提示：\n\n```py3\nfrom simpleaichat.utils import wikipedia_search, wikipedia_search_lookup\n\n# 这里使用维基百科搜索 API。\n# 搜索结果具有不确定性，效果可能因人而异。\ndef search(query):\n    \"\"\"搜索互联网。\"\"\"\n    wiki_matches = wikipedia_search(query, n=3)\n    return {\"context\": \", \".join(wiki_matches), \"titles\": wiki_matches}\n\ndef lookup(query):\n    \"\"\"查找有关某个主题的更多信息。\"\"\"\n    page = wikipedia_search_lookup(query, sentences=3)\n    return page\n\nparams = {\"temperature\": 0.0, \"max_tokens\": 100}\nai = AIChat(params=params, console=False)\n\nai(\"旧金山旅游景点\", tools=[search, lookup])\n```\n\n```txt\n{'context': \"渔人码头、旧金山、美国的旅游景点、伦巴底街（旧金山）\",\n 'titles': [\"渔人码头、旧金山\",\n  '美国的旅游景点',\n  '伦巴底街（旧金山）'],\n 'tool': 'search',\n 'response': '旧金山有许多热门的旅游景点，包括渔人码头和伦巴底街。渔人码头是一个热闹的海滨地区，以其海鲜餐厅、纪念品商店和海狮观赏而闻名。另一方面，伦巴底街是一条著名的蜿蜒街道，拥有八个急转弯，吸引了来自世界各地的游客。对于任何访问旧金山的人来说，这两个景点都是必去之地。'}\n```\n\n```py3\nai(\"伦巴底街？\", tools=[search, lookup])\n```\n\n```\n{'context': '伦巴底街是加利福尼亚州旧金山的一条东西向街道，因其一段陡峭的单行路段上有八个急转弯而闻名。这条街道从要塞区向东延伸至滨水区（在电报山处有一段中断），其西部大部分路段是一条重要的交通干道，被指定为美国101号公路的一部分。而那条著名的单行路段，号称“世界上最曲折的街道”，位于俄罗斯山社区的东部路段。',\n 'tool': 'lookup',\n 'response': '伦巴底街是加利福尼亚州旧金山一条著名的街道，以其陡峭的单行路段上的八个急转弯而闻名。它从要塞区一直延伸到滨水区，在电报山处有一段中断。该街道的西部路段是一条重要的交通干道，被指定为美国101号公路的一部分；而那条著名的单行路段，号称“世界上最曲折的街道”，则位于俄罗斯山社区的东部路段。'}\n```\n\n```py3\nai(\"谢谢你的帮助！\", tools=[search, lookup])\n```\n\n```txt\n{'response': '不客气！如果您还有任何问题或需要进一步的帮助，请随时提问。',\n 'tool': None}\n```\n\n## 其他说明\n\n- 与之前的 [gpt-2-simple](https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fgpt-2-simple) 一样，发布 simpleaichat 的主要动机在于进一步 democratize ChatGPT 的访问权限，并为非技术人员提供更多透明度，了解基于聊天 AI 的应用在底层是如何工作的，尤其是在关于其能力的媒体 misinformation 极其普遍的情况下。这一想法源于我在 [BuzzFeed](https:\u002F\u002Ftech.buzzfeed.com\u002Fthe-right-tools-for-the-job-c05de96e949e) 工作时的实际经验：在长期使用流行的 [LangChain](https:\u002F\u002Fgithub.com\u002Fhwchase17\u002Flangchain) 后，我发现一个更简单的实现不仅更容易维护，而且生成效果也更好。在阅读了一个充满类似抱怨的 [Hacker News 帖子](https:\u002F\u002Fnews.ycombinator.com\u002Fitem?id=35820931) 后，我开始将开发重点转向 simpleaichat，这表明对于现代 AI 技巧来说，一个更易用的界面确实具有价值。\n  - simpleaichat 在可能的情况下非常有意识地避免将功能与常见用例（例如 Tools）耦合在一起，以防止因难以实现项目文档中未明确提及的功能而导致的软件 lock-in。simpleaichat 的理念是提供良好的演示示例，然后让用户的创造力和业务需求占据主导地位，而不是像 LangChain 那样被迫将圆柱塞进方孔。\n  - simpleaichat 确实简化了与聊天 AI 的交互，但它并未试图解决大型语言模型在互联网上训练所固有的常见技术和伦理问题，包括 prompt injection 和无意的 plagiarism。用户在使用 simpleaichat 时应保持良好的判断力。任何违反 OpenAI [使用政策](https:\u002F\u002Fopenai.com\u002Fpolicies\u002Fusage-policies) 的 simpleaichat 使用场景（包括 jailbreaking）均不被支持。\n  - simpleaichat 故意没有采用“Agent”这一用于工具工作流的逻辑隐喻，因为它已经成为一个与本源严重脱节的 AI 虚热词汇。如果需要，你可以通过一个 `while` 循环来模拟 Agent 工作流，而无需太多额外代码，同时还具备更高的灵活性，比如调试能力。\n- 会话管理器实现了一些合理的安全默认设置，例如默认使用 UUID 作为会话 ID、以尽量减少意外泄露的方式存储认证信息，以及通过 Pydantic 进行类型强制。不过，您的最终用户应用程序仍需注意潜在的安全问题。\n- 尽管 OpenAI 的文档指出，系统提示的效果不如以类似方式构建的用户提示，但根据我的经验，它在维持规则或 persona 方面仍然表现得更好。\n- 许多流行的提示示例都采用了更具对话性的风格，而这里的示例提示则更加简洁和命令式。提示工程的这一方面仍在不断发展，但根据我的经验，命令形式的提示在 ChatGPT 上表现更好，且 token 效率更高。这也是 simpleaichat 允许用户指定系统提示（并明确指出默认用法）而非依赖于历史最佳实践的原因。\n- 异步操作的 token 计数目前不受支持，因为 OpenAI 在流式响应时不会返回 token 计数。总体而言，不同用例下的 token 计数和实际用量之间可能存在一些不同步；我正在努力对这些情况进行分类。\n- 除明确标注的示例外，本 README 中没有任何内容是由 AI 生成的。开头的代码示例只是一个玩笑，但它确实是一个太好的真实应用场景！\n\n## 路线图\n\n- 支持 PaLM Chat（Bard）和 Anthropic Claude\n- 基于 Textual 构建一个更具趣味性和功能性的 CLI 聊天应用\n- 提供一个在 Web 应用中使用 simpleaichat 的简单示例\n- 提供一个以无状态方式使用 simpleaichat 的简单示例（例如 AWS Lambda 函数）\n\n## 维护者\u002F创建者\n\nMax Woolf ([@minimaxir](https:\u002F\u002Fminimaxir.com))\n\n*Max 的开源项目由他的 [Patreon](https:\u002F\u002Fwww.patreon.com\u002Fminimaxir) 和 [GitHub Sponsors](https:\u002F\u002Fgithub.com\u002Fsponsors\u002Fminimaxir) 支持。如果您觉得这个项目有所帮助，欢迎向 Patreon 捐款，您的每一份支持都将得到妥善利用。*\n\n## 许可证\n\nMIT","# simpleaichat 快速上手指南\n\n`simpleaichat` 是一个轻量级 Python 库，旨在以极简的代码与 ChatGPT、GPT-4 等聊天模型进行交互。它专注于优化 Token 使用以降低成本和延迟，同时支持流式输出、异步调用、工具调用（Tools）及结构化数据输出等高级功能。\n\n## 环境准备\n\n- **操作系统**：Windows、macOS 或 Linux\n- **Python 版本**：Python 3.8 及以上\n- **前置依赖**：\n  - OpenAI API Key（需提前在 [OpenAI 平台](https:\u002F\u002Fplatform.openai.com\u002F) 获取）\n  - 可选依赖：若使用工具调用中的维基百科搜索等功能，需确保网络可访问相关 API。\n\n> **提示**：建议将 API Key 配置为环境变量 `OPENAI_API_KEY` 或存入当前目录的 `.env` 文件中（字段名为 `OPENAI_API_KEY`），以避免在代码中硬编码密钥。\n\n## 安装步骤\n\n通过 PyPI 直接安装：\n\n```sh\npip3 install simpleaichat\n```\n\n> **国内加速建议**：如遇下载缓慢，可使用清华或阿里镜像源安装：\n> ```sh\n> pip3 install simpleaichat -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n> ```\n\n## 基本使用\n\n### 1. 启动交互式聊天\n\n最简单的用法是直接在终端启动一个类似官方网页版的交互式聊天窗口：\n\n```sh\nsimpleaichat\n```\n\n你也可以指定角色和行为规范（例如扮演 GLaDOS 并用《宋飞正传》风格说话）：\n\n```sh\nsimpleaichat \"GLaDOS\" \"Speak in the style of a Seinfeld monologue\"\n```\n\n### 2. 在 Python 脚本中使用\n\n导入库并初始化 `AIChat` 对象，即可开始对话。以下示例展示如何设置系统提示并获取回复：\n\n```py3\nfrom simpleaichat import AIChat\n\nai = AIChat(system=\"You are a helpful assistant.\")\nresponse = ai(\"What is the capital of California?\")\nprint(response)\n```\n\n**输出：**\n```\nThe capital of California is Sacramento.\n```\n\n### 3. 流式输出（Streaming）\n\n如果需要实时看到生成过程（降低等待感知延迟），可以使用流式模式：\n\n```py3\nfor chunk in ai.stream(\"What is the capital of California?\", params={\"max_tokens\": 5}):\n    response_td = chunk[\"response\"]\n    print(response_td, end=\"\", flush=True)\n```\n\n### 4. 多轮对话上下文\n\n`AIChat` 实例会自动维护对话历史，后续调用会包含之前的上下文：\n\n```py3\nresponse = ai(\"When was it founded?\")\nprint(response)\n```\n\n**输出：**\n```\nSacramento was founded on February 27, 1850.\n```\n\n### 5. 保存与加载会话\n\n你可以将会话保存为 CSV 或 JSON 文件，以便稍后恢复（注意：API Key 不会被保存）：\n\n```py3\nai.save_session(format=\"json\", minify=True)\nai.load_session(\"my.json\")\n```\n\n---\n\n通过以上步骤，你即可快速利用 `simpleaichat` 构建高效的 AI 聊天应用。更多高级功能（如 Function Calling、Schema 结构化输出、Agent 工作流等）请参考官方示例笔记。","某初创团队的技术负责人需要快速构建一个能同时为多位开发者提供定制化代码建议的异步助手集群，以加速内部工具的原型开发。\n\n### 没有 simpleaichat 时\n- **代码冗余严重**：原生调用需编写大量样板代码来处理会话状态、历史消息管理及 API 鉴权，导致核心逻辑被淹没。\n- **并发实现困难**：若要同时服务多个开发者或运行多个独立对话线程，手动管理异步任务和上下文切换极易出错且耗时。\n- **成本与延迟失控**：缺乏内置的 Token 优化机制，每次交互都携带冗余信息，导致 API 调用成本高昂且响应速度慢。\n- **调试门槛高**：底层封装复杂，出现异常时难以快速定位是网络问题、参数错误还是逻辑漏洞，排查效率低下。\n\n### 使用 simpleaichat 后\n- **极简代码集成**：仅需几行代码即可初始化具备完整会话记忆的 AI 聊天实例，让开发者专注于业务逻辑而非底层对接。\n- **原生异步支持**：内置强大的 Async 功能，可轻松在同一时间内并行运行多个独立对话，完美适配多用户或批量处理场景。\n- **智能成本优化**：自动采用优化的工作流最小化 Token 消耗，在保持高质量输出的同时，显著降低费用并提升响应速度。\n- **透明易维护**：精简的代码库结构让内部机制一目了然，无需深入“黑盒”即可轻松调试和扩展功能。\n\nsimpleaichat 通过极致的简化与性能优化，让开发者能以最低的成本和代码量，快速构建出高效、可扩展的 AI 聊天应用。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fminimaxir_simpleaichat_d9074fe9.png","minimaxir","Max Woolf","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fminimaxir_3ab20437.jpg","Senior Data Scientist @buzzfeed. Plotter of pretty charts.","@buzzfeed ","San Francisco","max@minimaxir.com",null,"https:\u002F\u002Fminimaxir.com","https:\u002F\u002Fgithub.com\u002Fminimaxir",[84],{"name":85,"color":86,"percentage":87},"Python","#3572A5",100,3506,223,"2026-04-20T00:14:55","MIT","未说明 (适用于所有支持 Python 和 pip 的操作系统)","不需要 (该工具为 OpenAI API 的客户端封装，计算在云端进行)","未说明",{"notes":96,"python":97,"dependencies":98},"该工具本身不运行本地大模型，因此无需 GPU 或大量内存。主要依赖是有效的 OpenAI API Key。支持异步操作、流式输出、工具调用（Function Calling）以及基于 Pydantic 的结构化数据输入输出。可通过命令行直接启动交互式聊天。","3.8+",[99,100],"pydantic","python-dotenv",[14,15,36,13],[103,104],"ai","chatgpt","2026-03-27T02:49:30.150509","2026-04-20T16:46:41.245777",[108,113,118,123,128,133],{"id":109,"question_zh":110,"answer_zh":111,"source_url":112},45043,"生成的 Schema 中包含 OpenAI 示例中没有的 \"title\" 字段，这是否正常？","这是正常的。虽然 Pydantic 生成的 Schema 默认包含 \"title\" 字段，但在实际发送给 ChatGPT 模型时，库会自动递归地移除这些 \"title\" 字段以符合 OpenAI 的要求。维护者已验证 `write_ttrpg_story` 等复杂示例能正确工作。此外，\"name\" 字段仅用于顶层的 `function_call` 参数，不属于 JSON Schema 规范的一部分。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F40",{"id":114,"question_zh":115,"answer_zh":116,"source_url":117},45044,"如何查看库实际发送给 API 的请求内容（包括角色和 Prompt）？","可以使用 `prepare_request()` 方法来调试。该方法会构建发送给 ChatGPT API 的数据。例如，调用 `ai.default_session.prepare_request(prompt)[1]` 将返回用作模型参数的完整 `data` 集合，其中包含了封装为 `ChatMessage` 的 prompt 以及之前的消息历史。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F13",{"id":119,"question_zh":120,"answer_zh":121,"source_url":122},45045,"这个项目还在维护吗？是否接受社区贡献？","项目仍在维护中，但范围严格限定以保持轻量级。维护者会合并修复错误或重要问题的 PR（如 Pydantic 2.0 迁移），但会拒绝增加复杂性或非核心功能（如 Azure OpenAI 支持）的请求。并非所有 Issue 都会立即处理，项目遵循优先级分类，不追求零 Issue 状态。欢迎提交高质量的 PR，但需符合项目精简的设计理念。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F92",{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},45046,"是否支持不符合 JSON Schema 规范的自定义函数 Schema？","不支持。该库的结构化输入\u002F输出实现是专门针对 ChatGPT 优化的。除非有证据表明违反 JSON Schema 格式能切实提高生成质量，否则为了保持库的简单性，不会添加允许自由格式 Schema 的功能。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F38",{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},45047,"库内置支持 API 调用缓存（如 GPTCache 或 SQLite）吗？","库本身不包含缓存功能。维护者认为如果需要缓存输入，可以通过扩展实现，或者作为单独的演示案例提供，而不必将其集成到核心库中，以保持库的轻量化。用户可以自行结合 LangChain 或 GPTCache 等外部工具实现缓存。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F2",{"id":134,"question_zh":135,"answer_zh":136,"source_url":137},45048,"最近项目没有更新，是不是已经废弃了？","项目没有被废弃。之前的停滞是因为维护者个人原因暂时离开，目前工作已恢复。由于该项目刻意保持范围狭窄（tightly scoped），其活跃度可能不如其他大型 AI 项目，因此短期的不活跃并不代表项目死亡。","https:\u002F\u002Fgithub.com\u002Fminimaxir\u002Fsimpleaichat\u002Fissues\u002F91",[139,144,149,154,159,163],{"id":140,"version":141,"summary_zh":142,"released_at":143},359940,"v0.2.2","* 允许 `fd` 接收可用于 `Field` 的任意参数（我有一个很酷的项目正打算用这个功能！）\n* 在 CLI 应用中使用 `argparse` #50  （待办：移除 `fire` 依赖）\n* 传递 `str` 类型的 URL 来构建 `api_url` #52 \n* 如果在输入或输出 Schema 中使用了 `title`，添加了一个断言，因为它是保留关键字，我们已经在进行移除处理。请注意，目前这仅影响顶级 Schema。","2023-07-24T01:43:32",{"id":145,"version":146,"summary_zh":147,"released_at":148},359941,"v0.2.1","本次发布将 simpleaichat 更新至 Pydantic 2.0，并替换了其中所有已弃用的函数。simpleaichat 现在需要 `pydantic>=2.0`。此次迁移不应带来任何破坏性变更，但客户端性能预计将有显著提升！\n\n## 其他更改\n\n- 内部重构 #19\n- 为保持一致性，`AIChat` 构造函数中的 API 密钥优先于 `env` 变量 #22\n- `ChatMessage` 的字符串表示现在返回一个序列化的字典，而非仅返回文本内容。#29\n- 可通过 `https_proxy` 环境变量指定 HTTP 代理。**此行为可能会在未来的版本中发生变化** #34\n","2023-07-03T18:16:01",{"id":150,"version":151,"summary_zh":152,"released_at":153},359942,"v0.2.0","本次发布支持基于模式的输入输出，这得益于 OpenAI 的新函数调用功能！\n\n## 模式\n\n```py3\nfrom pydantic import BaseModel, Field\n\nai = AIChat(\n    console=False,\n    save_messages=False,  # 使用模式 I\u002FO 时，消息永远不会被保存\n    model=\"gpt-3.5-turbo-0613\",\n    params={\"temperature\": 0.0},\n)\n\nclass get_event_metadata(BaseModel):\n    \"\"\"事件信息\"\"\"\n\n    description: str = Field(description=\"事件描述\")\n    city: str = Field(description=\"事件发生城市\")\n    year: int = Field(description=\"事件发生年份\")\n    month: str = Field(description=\"事件发生月份\")\n\n# 返回一个字典，键的顺序与模式中定义的一致\nai(\"首款 iPhone 发布会\", output_schema=get_event_metadata)\n```\n\n```txt\n{'description': '首款 iPhone 由苹果公司发布。',\n 'city': '旧金山',\n 'year': 2007,\n 'month': '一月'}\n```\n\n利用这一功能，你可以实现许多用途，而当前的实现仅仅是一个开始。\n\n注意事项：\n- 在所有情况下，使用模式时都不会保存消息，以避免意外行为。如果你希望将多个输入串联起来，目前仍需自行管理中间输出。\n- 输入和输出模式适用于常规生成任务，无论是同步还是异步方式。\n- 对于流式响应，仅支持输入模式；因为流式输出结构化数据可能会导致兼容性问题。\n- 目前尚不支持与工具结合使用；这方面还需要进一步测试。\n\n## 其他变更：\n\n- 添加了会话上下文管理器 (#7)，适用于需要编写临时对话脚本的场景，同时支持同步和异步两种模式。\n- 从 ChatGPT 的输出中保存了 `finish_reason` 字段 (#14)。\n- 现在可以向 `save_session()` 方法传递 `output_path` 参数。","2023-06-19T02:58:01",{"id":155,"version":156,"summary_zh":157,"released_at":158},359943,"v0.1.1","修复缺失的依赖项 #1","2023-06-09T04:07:11",{"id":160,"version":161,"summary_zh":80,"released_at":162},359944,"v0.1.0","2023-06-08T04:37:37",{"id":164,"version":165,"summary_zh":166,"released_at":167},359945,"v0.0.1","初始测试发布（用于在 PyPI 上预留名称并在 Colab 上进行测试）","2023-06-07T03:10:47"]