今日已更新 386 条资讯 | 累计 20358 条内容
关于我们

标签:#Python

找到 615 篇相关文章

AI 资讯

I Built RAG From Scratch in Python to Understand It. Here's What I Learned.

I had used LangChain's RAG chain in production for six months. I could not have told you, off the top of my head, what chunk_overlap did, or why cosine similarity is the right distance metric, or how nomic-embed-text actually turns a sentence into a vector. The high-level library abstracted all of it away. So one weekend I deleted the LangChain dependency and wrote a RAG pipeline from scratch in ~500 lines of plain Python. No framework, no magic. pypdf for text extraction. A 60-line chunker. ChromaDB for the vector store. Ollama for embeddings and the LLM. The whole thing is on GitHub — every module is under 200 lines, every test is deterministic, and you can read the whole thing in one sitting. This is the build log. Not a tutorial — the build log, with the parts that surprised me and the parts I got wrong the first time. Why bother The honest reason: I was using LangChain's RetrievalQA chain and getting answers I didn't trust. Sometimes the model would say "according to the document" when the document didn't say that. Sometimes the citations were wrong. I had no way to know if the chunker was dropping important context, or if the cosine similarity was picking the wrong neighbors, or if the prompt was actually constraining the model. The library was a black box. When you build it yourself, every layer is inspectable. When the answer is wrong, you can add a print statement in pipeline.py line 102 and see exactly which chunks were sent to the LLM. When the chunker cuts a sentence in half, you see it in the test fixtures. When the embedding model gives garbage for some inputs, you can swap in a different model with one constructor parameter. None of that is possible when the whole thing is RetrievalQA.from_chain_type(llm=..., retriever=...) . The other reason: the code I wrote is 500 lines, and it covers the same ground as a 50-line LangChain script. The extra 450 lines are comments, type hints, tests, and explicit error handling. That's the actual complexity. LangCha

2026-06-22 原文 →
AI 资讯

KIMI + Agnes: A Real-World Test of Cross-Provider Agent Chain Correctover

A few days ago I had an idea: what if one LLM could orchestrate other LLMs as agents — not just calling them, but verifying that each agent's output was actually correct before passing it to the next? I work on NeuralBridge (an open-source self-healing SDK for LLM pipelines), so I decided to build it and test it with two real providers: KIMI (Moonshot) and Agnes AI . The Core Problem: Failover ≠ Correctover Most API gateways and LLM routers stop at "HTTP 200" — they retry or switch providers, but they never check if the output is actually correct . # What everyone else does: try : result = call_llm ( prompt ) return result # HTTP 200 = success? 🚩 except Exception : result = call_llm_fallback ( prompt ) return result # Still not verified! This is dangerous. A failover from gpt-4o to gpt-4o-mini might silently drop 3 critical fields. A KIMI response that returns "200 OK" might still be missing key entities. Correctover is the idea that switching providers isn't enough — you must verify semantic equivalence after every switch. The Architecture We built a simple DAG-based chain executor with three key capabilities: DAG orchestration — define multi-step workflows where nodes depend on each other Per-node semantic validation — every LLM output is checked against a Contract before passing to the next node Cross-provider Correctover — if validation fails, automatically retry with a different provider from neuralbridge import SelfHealingEngine , ProviderConfig , Contract from neuralbridge.chain import ChainBuilder engine = SelfHealingEngine ( providers = []) engine . add_provider ( ProviderConfig ( name = " moonshot " , base_url = " https://api.moonshot.cn/v1 " , api_key = " ... " , models = [ " moonshot-v1-8k " , " moonshot-v1-32k " ], )) engine . add_provider ( ProviderConfig ( name = " agnes " , base_url = " https://apihub.agnes-ai.com/v1 " , api_key = " ... " , models = [ " agnes-2.0-flash " ], )) chain = ( ChainBuilder ( engine ) . node ( name = " planner " , system = "

2026-06-22 原文 →
AI 资讯

PydanticAI vs LangChain - Choosing an Agent Framework for Production, Not Demos

In a recent audit, a team showed me an AI assistant they'd built on top of their company knowledge base. The demo had landed well: ask how to use a feature, and it walked through the exact pain point their support queue kept seeing. Leadership signed off. In production, the same agent told a user to open a menu option that didn't exist. Not a vague answer - a specific UI path, stated with confidence. Nobody caught it in testing. It surfaced when I audited the system, not when a user complained. The prototype passed testing because nobody was checking whether the answer matched the product. In production, that gap becomes a liability: the model invents UI paths, and your backend has no schema to reject them. When you're choosing an agent framework, popularity is the wrong scorecard. Pick the one that fails loudly in development and gracefully in production - or you'll find out in audit. What "Production-Ready" Actually Requires Tutorial agents are built to impress in a fifteen-minute demo. Production agents run unattended, handle bad inputs, and ship answers your backend has to trust. The gap between those two goals is where most teams stumble - and it's rarely visible until something reaches a user. When I audit agent codebases, I evaluate five things the tutorials skip: Structured, validated outputs: Can your system reject an invented menu path before it becomes user-facing advice? Dependency injection for testing: Can you swap the knowledge base for a mock in CI without rewiring the agent? Retry and error handling: When the model returns malformed output, does the framework retry - or do you ship a parser exception? Observability hooks: Can you trace which document grounded a bad answer when support escalates? Type-checker support: Will static analysis catch a breaking API change before deploy, or after the agent silently misbehaves? If you want to score your own system, the Production Readiness Audit covers the same five categories - deployment, observability, fa

2026-06-22 原文 →
AI 资讯

Pydantic AI 的 5 个隐藏用法:类型安全的 Agent 框架

你知道吗?最近一个 AI Agent 直接删除了生产数据库,然后在 Twitter 上轻松"自首"——这条消息在 Hacker News 上获得了 860 分和超过 1000 条评论。随着 AI Agent 从演示走向生产环境,"在我的机器上能跑"和"它能安全地运行我的业务"之间的鸿沟从未如此巨大。 Pydantic AI 正是为弥合这一鸿沟而来。这个拥有 17,895 Stars 的 Python Agent 框架,由 Pydantic Validation 的同一团队打造——而 Pydantic Validation 正是 OpenAI SDK、Anthropic SDK、Google ADK、LangChain、LlamaIndex、CrewAI 等数十个 GenAI 工具的数据验证层。如果你用过 FastAPI,你已经知道 Pydantic 的感觉:类型安全、优雅、生产就绪。Pydantic AI 将这种哲学完整地带入了 Agent 开发领域。 在 2026 年的今天,大多数 Agent 框架把 LLM 当成返回字符串的黑盒子。Pydantic AI 则将其视为类型化、可验证、可组合的系统——这改变了一切。 隐藏用法 #1:人工审批工具调用(阻止 Agent 乱来) 大多数人的做法: 给 Agent 完全自由去调用任何工具——数据库查询、API 调用、文件删除——然后祈祷一切顺利。当出了问题时,你从用户口中才知道。 隐藏技巧: Pydantic AI 的延迟工具(deferred tools)让你可以标记某些工具调用在执行前需要人工审批。Agent 会规划好动作,但在执行前暂停并等待人类批准或拒绝——完美适用于数据库写入、金融交易或生产部署等破坏性操作。 from pydantic_ai import Agent , RunContext , DeferredToolRequests from pydantic import BaseModel agent = Agent ( ' openai:gpt-4.1 ' , output_type = str , # 通过 deferred=True 标记需要审批的工具 ) @agent.tool ( deferred = True ) async def delete_user_account ( ctx : RunContext , user_id : str ) -> str : """ 永久删除用户账户。需要人工审批。 """ # 这段代码只在人工审批通过后才会执行 await db . users . delete ( user_id ) return f " 用户 { user_id } 已删除 " # 运行 Agent——如果它尝试调用 delete_user_account, # 执行会暂停并返回 DeferredToolRequests 对象 result = await agent . run ( " 清理不活跃账户 " ) if isinstance ( result . output , DeferredToolRequests ): # 将待执行的工具调用展示给人类审批 for tool_call in result . output . calls : print ( f " Agent 想要执行: { tool_call . tool_name } ( { tool_call . args } ) " ) approved = input ( " 是否批准?(y/n): " ) if approved . lower () == ' y ' : # 带审批结果恢复执行 result = await agent . run ( " 已批准 " , message_history = result . all_messages (), deferred_tool_requests = result . output , ) 效果: Agent 可以自主处理安全操作(读取数据、生成报告),而在危险操作上自动暂停等待人工判断。不再有删库跑路的意外。 数据来源: Pydantic AI GitHub 17,895 Stars(通过 GitHub API 验证,最后推送 2026-06-21)。HN Algolia 搜索"pydantic-ai agent framework"获得 12 分讨论帖。"AI agent deleted production database"故事在 HN 上获得 860 分/1032 条评论(数据来源:HN Algolia API)。 隐藏用法 #2:基于图的多 Agent 工作流 + 类型安全状态 大多数人的做法: 构建线性

2026-06-22 原文 →
AI 资讯

[Gemini API Hands-on]

Origin: Halfway through a chat, where is that meme? Every heavy chat user has a bunch of memes saved on their phone and computer, but when they actually need one—halfway through a conversation, wanting to send a "Thanks, let's keep in touch" or "I'm just bad"—they can never find it. The filename is IMG_4821.jpg , albums are not categorized, and searching is impossible. I first came across a great open-source project ShiQu1218/MemeTalk , which uses Python + Streamlit + SQLite to build a local meme semantic search system. It scans your local meme folder, creates an index using OCR and vector embeddings, and then performs multi-way retrieval. It's fully functional but research-oriented and requires running Streamlit in a browser. What I wanted was something closer to an "everyday handy tool": A native Mac App, a search box, where I type what I'm looking for, relevant memes pop up, and a single click copies it directly to the clipboard. Thus MemeFinder was born. This article documents its development process from scratch to "menu bar resident + global hotkey

2026-06-22 原文 →
AI 资讯

BITCOIN HACKATHON

After a full week of intensive Bitcoin programming training, the developers at Zone01 Kisumu moved into the most exciting phase of the bootcamp: building real-world solutions powered by Bitcoin, the Lightning Network, and LND. One thing I learned throughout the experience is that the human mind is truly fascinating. The room was filled with innovative ideas, each attempting to solve a different problem. As the saying goes, no idea is a bad idea—every concept had the potential to make an impact. A total of 17 teams were formed, and each team embarked on a 24-hour hackathon journey to transform their ideas into working products. After an intense day of development came the presentation phase, where we had the privilege of showcasing what we had built. Our team developed Kasi , a WhatsApp chatbot that enables Bitcoin transactions directly through WhatsApp. The goal was to make Bitcoin payments more accessible by leveraging a platform that millions of people already use daily. To build Kasi, we integrated the Twilio API for WhatsApp communication and utilized the Bitnob platform to facilitate Bitcoin transactions. Python was used throughout the development process. The project was brought to life by six developers: Claire, Lamka, Ijay, Dishon, Talo, and myself. Beyond the technical implementation, the hackathon strengthened our understanding of collaborative software development. We practiced Git workflows, team coordination, version control, task management, and effective communication under tight deadlines—skills that are just as valuable as writing code. Although we did not finish at the top of the leaderboard, the experience was incredibly rewarding. Every team brought something unique to the table, and the winners fully deserved their recognition. Congratulations to all the teams that participated and showcased their creativity, determination, and technical skills. One moment from the presentation will stay with me for a long time. As we were demonstrating Kasi to

2026-06-22 原文 →
AI 资讯

I Got Tired of Paying $99/mo for Options Data — So I Built My Own API tags: python, api, finance, showdev

I build algorithmic trading bots as a side project. Nothing fancy — just small strategies that trade US equity options automatically. The problem I kept running into wasn't the strategy logic. It was the data. Every time I wanted to pull real-time options chains, Greeks, or IV, I had two options: Pay $99+/mo to a data provider Scrape something I probably shouldn't be scraping Neither felt right for a hobbyist project. So I built Market-Options — a simple REST API for US equity options data at $20/mo. What It Does It's a plain REST API. No SDK, no special client library — just HTTP requests and JSON responses. It covers four endpoints: chain — full options chain for a given underlying contract — data for a single contract contracts — batch lookup across multiple contracts contract-overview — Greeks, IV, expiration details Coverage is the top 100 US equity underlyings, which accounts for roughly 95% of actual US options volume. If you're building a bot that trades SPY, QQQ, AAPL, TSLA, or anything in that tier — it's covered. Why Only 100 Underlyings? Because that's what most people actually trade. When I looked at my own bots, and at what most retail algo traders focus on, the top 100 covers everything practical. Exotic underlyings with low volume are also harder to get real data on reliably — so rather than promise coverage I can't deliver, I focused on doing the core well. A Simple Example curl "https://api.market-option.com/chain?symbol=SPY&expiration=2025-01-17" \ -H "Authorization: Bearer YOUR_API_KEY" Response is clean JSON: { "symbol" : "SPY" , "expiration" : "2025-01-17" , "options" : [ { "strike" : 480 , "type" : "call" , "bid" : 3.45 , "ask" : 3.50 , "iv" : 0.182 , "delta" : 0.42 , "gamma" : 0.031 , "theta" : -0.18 , "vega" : 0.29 } ] } No parsing headaches, no weird date formats. Pricing Free tier : 1,000 credits/day — enough to test and build Pro : $20/mo, unlimited within fair use Trial : New accounts get 7 days of Pro, no credit card required Who It's F

2026-06-21 原文 →
AI 资讯

Your AI agent has sudo. I built a tool to take it away.

A few weeks ago I gave an AI agent access to my machine through MCP. It read files, opened PRs, queried a database. It was great — until I looked at what it could have done if a tool description had been poisoned, or a prompt injection had slipped through. The answer was: anything. ~/.ssh/id_rsa . DROP TABLE users . rm -rf / . The agent had sudo, and nobody had voted for that. So I built AgentPerms — a CLI that gives MCP agents least-privilege permissions the same way you'd lock down any other process: figure out the minimum it actually needs, pin it, prove it, and enforce it. pip install agentperms The gap nobody was filling MCP (the Model Context Protocol) is quietly becoming the USB-C of AI tooling. Claude Desktop, Cursor, VS Code, Windsurf, Gemini CLI — they all speak it. Which is wonderful, and also means your agent is one config file away from your filesystem, your repos, your inbox, and prod. The existing tools each do part of the job: Scanners tell you something looks risky. Then they leave. You still have a risky thing. Firewalls / allowlists make you hand-write YAML up front — before you have any idea what the agent will actually use. Neither closes the loop. What I wanted was the boring, proven security workflow we already use for everything else: observe real behavior → derive least privilege → enforce it → keep it honest in CI. That's the whole thesis of AgentPerms, as a pipeline: record → infer → lock → replay → enforce See it in 30 seconds (no setup, no network) AgentPerms ships with a deliberately over-privileged demo MCP server, so you can watch a real policy decision without wiring anything up: # Flag risky config: a ~/.ssh mount and an unpinned npx server agentperms scan --path examples/vulnerable-mcp-demo # Replay a pack of canned attacks against an example policy agentperms replay --policy examples/policies/example.mcp.policy.yaml Output: 8/8 attacks blocked. SSH-key exfiltration, .env reads, rm -rf / , unapproved email, force-push, repo deletio

2026-06-21 原文 →