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

标签:#Python

找到 615 篇相关文章

AI 资讯

Windows ortamında Python geliştirme ve operasyon yönetimi için “çekirdek CLI komutları”

1. Python Ortam Kontrolü (Windows CLI) Python sürüm kontrol python --version py --version where python pip kontrol pip --version python -m pip --version pip güncelleme (kritik) python -m pip install --upgrade pip 2. Python Çalıştırma Mekanizması (Windows Standard) Script çalıştırma python app.py Py launcher ile sürüm seçme py app.py py -3 .12 app.py py -3 .11 app.py Modül çalıştırma python -m mymodule 3. Sanal Ortam (venv) – Kurumsal Standart Oluşturma python -m venv venv Aktivasyon (PowerShell) venv \S cripts \A ctivate.ps1 Aktivasyon (CMD) venv \S cripts \a ctivate.bat Deaktivasyon deactivate Sanal ortam kontrol where python where pip pip list 4. requirements.txt Yönetimi Oluşturma pip freeze > requirements.txt Kurulum pip install -r requirements.txt Güncelleme pip install --upgrade -r requirements.txt 5. Paket Yönetimi (pip Core Set) Paket yükleme pip install requests Versiyon sabitleme pip install requests == 2.31.0 Paket kaldırma pip uninstall requests Listeleme pip list Güncellenebilir paketler pip list --outdated 6. Windows .env Yönetimi (Konfigürasyon Standardı) .env dosyası oluşturma notepad .env Örnek içerik DEBUG=True API_KEY=123456 DB_URL=localhost Python tarafı (.env kullanımı) pip install python-dotenv from dotenv import load_dotenv import os load_dotenv () api_key = os . getenv ( " API_KEY " ) print ( api_key ) 7. Sistem Komutları ve Process Yönetimi Process listeleme tasklist Python process filtreleme tasklist | findstr python Process sonlandırma taskkill /PID 1234 /F Python process kill taskkill /IM python.exe /F 8. Dosya İşlemleri (CLI seviyesinde) Dosya listesi dir Klasör değiştirme cd project Dosya silme del file.txt Klasör silme rmdir /S /Q folder 9. Log ve Debug Yönetimi Dosya log izleme (PowerShell) Get-Content app.log -Wait Son satırlar Get-Content app.log -Tail 100 Filtreleme Select-String "ERROR" app.log 10. Uzaktan Erişim (Windows → SSH) SSH bağlantı ssh user@server_ip Dosya gönderme scp app.py user@server_ip:C: \U sers \u ser \ Klasör gön

2026-06-18 原文 →
AI 资讯

Building AI Agents with Agno — I Actually Ran It with Gemini and Built-in Tools

If you've ever felt like LangChain was too heavy, you're not alone. The dependency tree is enormous. Abstraction layers pile up. At some point you lose track of what's actually happening underneath. That frustration has pushed a lot of people toward lighter alternatives — frameworks that prove you can build a capable agent without a hundred transitive dependencies. Agno is one of those alternatives. It started as Phidata and rebranded in early 2025. I spent an afternoon installing Agno v2.6.17 in a clean sandbox and running through Calculator tools, Wikipedia retrieval, Pydantic structured output, and a two-agent Team. I'll share the real execution logs and, more importantly, the traps I hit that the docs don't warn you about. What Agno Is and Where It Came from Phidata built a solid reputation as "the Python framework for AI assistants." When it rebranded to Agno in 2025, the design philosophy got articulated more clearly around three ideas. Model-agnostic from day one. Over 70 LLMs — OpenAI, Anthropic, Google, Ollama, Cohere — can plug in with the same code structure. Swap the model, keep the agent logic. Multimodal as a default. Text, image, audio, video agents all use the same API surface. You don't need a different abstraction layer for each modality. Multi-agent orchestration as a first-class citizen. The Team class is built in. You can switch between coordinate , route , and collaborate modes with a single parameter change. Reading that, I thought: "How is this different from LangChain?" The answer showed up when I actually wrote code. Agno favors composition over class inheritance. One agent takes about 6 lines to set up. There's far less boilerplate to wade through. Installation: No Dependency Hell pip install agno google-genai ddgs wikipedia The agno package installs just the core. Tools require their own extra dependencies — wikipedia for the Wikipedia tool, google-genai for Gemini. This lazy-loading approach keeps the base install clean. $ python3 -c "im

2026-06-18 原文 →
AI 资讯

Stop Fighting Python for Webhooks: Why Node.js is Optimal for Cloud Function Signatures

The Cryptographic Trust Problem (Why Webhooks Are Unforgiving) Webhooks are the nervous system of modern production apps. Whether you are processing a payment on Stripe, tracking a subscription on Lemon Squeezy, or fulfilling an order via Shopify, webhooks are how external platforms tell your backend: "Hey, something important just happened". Because these webhook endpoints have to be publicly accessible, they are prime targets for malicious actors. To prevent this, platforms use cryptographic signature verification . The Golden Rule of Verification When a provider sends a webhook, they take the HTTP request body and hash it with a shared secret key using HMAC-SHA256 . They pass this resulting signature in the request headers (like Stripe-Signature). When the request hits your server, your code has to do the exact same math: Grab the shared secret. Grab the exact raw bytes of the incoming request body. Hash them together and compare your result with the signature in the header. This process is completely binary and zero-tolerance. If your backend framework alters even a single byte—adding a trailing newline, stripping a whitespace, or reordering a JSON key during parsing—the math changes entirely. The signatures won't match, and the verification will fail. This brings us to our fundamental architectural bottleneck: to verify a webhook, you must intercept the request before your framework touches it. Why Python/Werkzeug Struggles If you build a Cloud Function in Python using the Firebase Functions SDK, you are working on top of Flask, which relies on Werkzeug to handle the underlying web server mechanics. Werkzeug is fantastic for standard web apps, but it has a specific architectural design that makes webhook verification a nightmare: it treats the incoming request body as a one-time, sequential input stream. The Single-Consumption Stream Under the WSGI (Web Server Gateway Interface) standard that powers Python web frameworks, the network payload arrives as an activ

2026-06-18 原文 →
AI 资讯

Cognee AI 记忆平台的 5 个隐藏用法:让 Agent 拥有跨会话的持久记忆

你知道吗?GitHub 上有一个 17,889 Stars 的开源项目,能让你的 AI Agent 拥有跨会话的持久记忆——不是简单的向量检索,而是一个会自动进化的知识图谱。但大多数开发者只用它来做基础的文档搜索,完全忽略了它真正的能力。 Cognee 是一个开源 AI 记忆平台,它把知识图谱、向量搜索和认知本体论生成统一到一个记忆层中。在 2026 年,AI Agent 正从单轮对话机器人向长时间运行的自主系统演进,而瓶颈不再是模型能力,而是上下文管理。以下是大多数人不知道的五个隐藏用法。 隐藏用法 #1:自动图谱同步的会话记忆 大多数人的做法:把对话历史存在简单的列表或向量数据库里,上下文长了就塞进 prompt。这在前几轮还行,但会话一长就迅速退化。 隐藏技巧:Cognee 的会话记忆充当快速缓存,会在后台自动同步到持久化知识图谱。你既能获得内存上下文的速度,又能拥有图数据库的持久性——而且同步过程完全不需要手动编排。 import cognee import asyncio async def agent_session (): # 会话记忆——快速、临时、按会话隔离 await cognee . remember ( " 用户询问了 Q3 收入趋势并请求导出 CSV。 " , session_id = " support_ticket_4421 " ) # 后续查询会话记忆(快速路径) results = await cognee . recall ( " 用户问了什么收入相关的问题? " , session_id = " support_ticket_4421 " ) # 会话结束时,会话记忆自动同步到永久图谱 # 无需手动导出,不会丢失任何数据 asyncio . run ( agent_session ()) 效果:你的 Agent 在会话内部保持对话上下文以实现快速响应,但会话结束后不会丢失任何信息。知识图谱会自动跨所有会话积累洞察。 数据来源:Cognee GitHub 17,889 Stars,README 文档中 session_id 参数和自动同步行为在"Use with AI Agents"章节有详细说明。 隐藏用法 #2:面向领域推理的本体论 grounding 大多数人的做法:把文档灌入向量数据库,依赖语义相似性做检索。模糊匹配还行,但当你需要结构化的、领域感知的推理时就不行了。 隐藏技巧:Cognee 的 cognify 流水线不只是嵌入文档——它会从你的数据中生成认知本体论,创建带有类型化关系的结构化知识图谱。这意味着你的 Agent 可以对实体及其连接进行推理,而不仅仅是找到相似的文本。 import cognee import asyncio async def build_domain_memory (): # 摄入领域文档 await cognee . remember ( """ 客户 Acme Corp 有 3 个活跃订阅。 订阅 A:企业计划,到期日 2026-09-15。 订阅 B:入门计划,已于 2026-03-01 到期。 客户经理是 Sarah Chen。 升级路径:Sarah -> 销售副总裁 -> CRO。 """ ) # Cognee 自动提取实体和关系: # (Acme Corp) --拥有--> (订阅 A) # (订阅 A) --类型--> (企业计划) # (订阅 A) --到期--> (2026-09-15) # (Sarah Chen) --管理--> (Acme Corp) # 现在进行结构化精确查询 results = await cognee . recall ( " 哪些客户在未来 90 天内订阅到期? " ) # 返回 Acme Corp 及具体订阅和日期—— # 而不仅仅是"关于订阅的相似文本" asyncio . run ( build_domain_memory ()) 效果:你的 Agent 不再依赖向量相似性碰运气,而是从理解实体类型、关系和时间约束的本体论中获得结构化答案。 数据来源:Cognee README "Product Features"章节描述了"ontology grounding"和"cognitive-science-grounded ontology generation";ArXiv 论文 2505.24478 关于优化知识图谱与 LLM 的接口。 隐藏用法 #3:通过共享图谱实现跨 Agent 知识共享 大多数人的做法:每个 Agent 维护自己独立的记忆。客服 Agent 无法受益于销售 Agent 昨天学到的东西。知识按设计被隔离。 隐藏技巧:Cognee 的知识图谱是一个共享基础设施层。多个基于不同框

2026-06-18 原文 →
AI 资讯

From Pixels to Proteins: Building a Precise Dietary Analysis System with GPT-4o and SAM

Have you ever tried to track your calories by manually searching for "half-eaten avocado toast" in a database? It’s a nightmare. While basic AI Computer Vision can identify an "apple," traditional models often fail at the granular level—distinguishing between 100g and 250g of pasta or identifying hidden toppings in a complex salad. In this tutorial, we are building a high-precision food nutrition AI engine. By combining the Segment Anything Model (SAM) for pixel-perfect object isolation and GPT-4o Vision for multi-modal reasoning and volume estimation, we can transform a simple smartphone photo into a detailed nutritional report. If you’re looking to dive deeper into production-grade AI patterns, I highly recommend checking out the advanced engineering guides at WellAlly Blog , which served as a major inspiration for this architecture. 🏗️ The Architecture: A Hybrid Vision Pipeline To achieve high accuracy, we don't just throw an image at an LLM. We use a "Segment-then-Analyze" pipeline. This ensures the LLM focuses on specific regions of interest (ROIs) rather than getting distracted by the background. graph TD A[User Uploads Food Image] --> B[Pre-processing with OpenCV] B --> C[SAM: Segment Anything Model] C --> D{Multi-Object Masking} D -->|Mask 1: Protein| E[GPT-4o Vision Reasoning] D -->|Mask 2: Carbs| E D -->|Mask 3: Veggies| E E --> F[Nutrient Mapping & Volume Estimation] F --> G[FastAPI Response: JSON Schema] G --> H[Final Dashboard] 🛠️ Prerequisites Before we start, ensure you have your environment ready: Python 3.10+ GPT-4o API Key (OpenAI) SAM Weights ( sam_vit_h_4b8939.pth ) Tech Stack : FastAPI , OpenCV , PyTorch , segment-anything 🚀 Step-by-Step Implementation 1. Object Segmentation with SAM First, we use Meta’s SAM to generate masks. This allows us to "cut out" each individual food item. import numpy as np import cv2 from segment_anything import sam_model_registry , SamPredictor # Initialize SAM sam_checkpoint = " sam_vit_h_4b8939.pth " model_type = "

2026-06-18 原文 →
AI 资讯

A model with R-squared near 0 can still give valid 90% prediction intervals - here's why (and the catch)

I recently calibrated a recovery-rate model that had only two weak features. Its point accuracy was almost nothing — R² basically zero. I expected its uncertainty estimates to be junk too. They weren't: the 90% conformal prediction intervals covered ~89% of held-out outcomes. Valid, just wide . That surprised me enough to nail it down, because it contradicts a belief a lot of us carry around: "my model isn't accurate, so I can't trust its uncertainty." For split conformal prediction, that's backwards. Here's the precise statement, a runnable demo, and the one caveat that actually bites. Coverage is a property of the procedure, not the model Split conformal prediction gives a distribution-free, finite-sample marginal coverage guarantee : P( Y ∈ Ĉ(X) ) ≥ 1 − α and it holds for any point model, as long as the calibration and test data are exchangeable. The model is a black box. You fit it however you like, then on a held-out calibration set you take the (1−α) quantile of the absolute residuals, and that quantile becomes the half-width of your intervals. Nowhere does that construction require the model to be good. A bad model just has large residuals, so the calibration quantile is large, so the intervals are wide — wide enough to still cover at the stated rate. Accuracy doesn't buy you validity ; it buys you efficiency (narrower intervals at the same coverage). The demo (numbers are reproducible, seed fixed) Same dataset and target, three models from strong to useless, target coverage 90%: model R² marginal coverage mean interval width gradient boosting 0.741 0.895 5.39 weak linear (1 noisy feature) 0.061 0.905 10.39 predict-the-mean −0.000 0.907 10.83 All three land at ~90% coverage. The only thing that changes is width: the good model's intervals are half as wide . That's the whole story in one table — validity is constant, efficiency tracks accuracy. import numpy as np from sklearn.linear_model import LinearRegression from sklearn.ensemble import GradientBoostingReg

2026-06-18 原文 →
AI 资讯

Spec-Driven Development: Let the Spec Drive the Code (With a Real Example)

By Sergio Colque Ponce — Software Engineering, Universidad Privada de Tacna. Full source code: github.com/srg-cp/spec-driven-development If you have used an AI coding agent — Copilot, Claude Code, Gemini CLI — you have probably lived this moment: you describe a feature, the agent produces code that compiles and looks right, and then it quietly does the wrong thing. The agent is not weak; the input was ambiguous. We have been treating coding agents like search engines when they behave more like very literal pair programmers. Spec-Driven Development (SDD) is the answer to that problem: instead of jumping straight to code, you write down what you want and why , refine it, and only then let the implementation follow. The specification — not the code — becomes the center of the project. What Spec-Driven Development actually is The idea is old (anyone who has written a Product Requirements Document will recognize it), but it has become practical again thanks to tools like GitHub's open-source Spec Kit . Spec Kit organizes the work into a small set of Markdown artifacts, each feeding the next: Constitution — the non-negotiable principles of the project (security rules, coding standards, architectural constraints). Spec — what you are building and why , with no implementation detail. Plan — the technical blueprint derived from the spec (stack, structure, decisions). Tasks — the plan broken into small, ordered, verifiable steps. Implement — the agent (or you) builds the tasks, with the previous artifacts as structured context. The workflow is usually summarized as Spec → Plan → Tasks → Implement , and the same process is meant to work regardless of language, framework, or which of the 30+ supported agents you use. The real shift is not "more documents." It is this: when requirements change, you update the spec, regenerate the plan, and let the implementation follow — instead of patching code and hoping the intent survives. The spec is a living artifact, not a dusty Word file

2026-06-18 原文 →
AI 资讯

Rate Limiting and Circuit Breakers in Distributed AI Systems

Rate Limiting and Circuit Breakers in Distributed AI Systems Distributed AI systems are inherently complex, handling massive volumes of requests, variable latency from model inference, and dependencies on external services like GPU clusters, databases, or third-party APIs. Without proper safeguards, a single misbehaving component or a sudden traffic surge can cascade into system-wide failure. Two fundamental patterns— rate limiting and circuit breakers —provide essential protection. This post explores their roles, implementation strategies, and practical Python examples tailored for AI workloads. Why Distributed AI Systems Need These Patterns Consider a typical AI pipeline: a user sends a prompt, which hits a load balancer, then an API gateway, then an inference service (e.g., a large language model), which may call a vector database or a fine-tuning API. Each component has capacity limits: GPU inference servers can handle limited concurrent requests. External APIs (e.g., OpenAI, HuggingFace) impose rate limits. Database connections are finite. Without rate limiting, a single abusive client can exhaust resources. Without circuit breakers, a failing downstream service can cause cascading timeouts and resource exhaustion across the entire system. Rate Limiting: Controlling Request Flow Rate limiting restricts how many requests a client, user, or service can make in a given time window. It prevents resource starvation and ensures fair access. Common Algorithms Algorithm Pros Cons Token Bucket Smooth burst handling, easy to implement Memory per bucket Leaky Bucket Constant outflow rate, simple Less flexible for bursts Fixed Window Simple, low overhead Boundary spikes (reset issues) Sliding Window Smoother than fixed, accurate Slightly more complex For AI systems, token bucket is often preferred because it allows short bursts (e.g., a user sending a batch of prompts) while maintaining a long-term average. Python Implementation: Token Bucket Rate Limiter import time impor

2026-06-17 原文 →
AI 资讯

Stop Saying Python Iterators Are Eager

As a backend developer, I sometimes help companies evaluate candidates by reviewing their recorded technical interviews. However, over time, I’ve noticed a deeply ingrained misconception. When discussing memory management or data streaming, many developers explicitly state: "Iterators in Python are inherently eager. If you want true lazy loading or lazy evaluation, you have to use generators and the yield keyword." This misconception is common. Many popular bootcamps and online courses introduce lazy evaluation exclusively through generators . Custom class-based iterators are usually skipped or dismissed as boilerplate-heavy OOP theory rarely used in production Python. This confusion is further reinforced by two common educational simplifications : The List vs. Generator Expression Analogy: Beginners are taught that square brackets [...] (list comprehensions) are eager and take up memory, while parentheses (...) (generator expressions) are lazy. This often creates a false binary mental model: "generators = lazy, everything else = eager." Standard "Textbook" Examples: When courses demonstrate a custom iterator, they usually write a basic class that accepts an already fully loaded list in its __init__ and simply increments an index in __next__ . While this is valid for in-memory data, it leads developers to assume that custom iterators inherently require loading all data upfront. In reality, generators are a specialized language feature designed to implement the iterator protocol automatically . They comply with the exact same interface ( __iter__ and __next__ ). A generator is lazy not because of some magical property of the yield keyword, but simply because it adheres to this underlying contract. To show that custom iterators can be lazy without using any generators or yield keywords, I’ve put together a lightweight and reproducible benchmark. 🧪 The Experiment: Proving Lazy Loading with Custom Iterators Suppose we need to read a database export file ( test_users_db.

2026-06-17 原文 →
AI 资讯

Ollama Structured Outputs in Practice — Getting Type-Safe JSON from Local LLMs with Pydantic

json.loads(response) fails at a certain point. You told the model "return JSON only," but it added a ```json markdown code fence around everything. A quick regex strips it — until that regex hits an edge case, and that edge case blows up in production. Since Ollama 0.3.0, passing a JSON schema to the format parameter eliminates this problem at the root. The model's inference itself is constrained by the schema, so no code fences, no explanatory text, no mid-thought artifacts. Just parseable JSON. I ran these tests locally with Gemma4 and Ollama 0.30.7 to see how well it holds up in practice. Why LLM Response Parsing Is Tricky The most common problem when running Ollama locally — without a cloud LLM API — is JSON parsing. Two reasons. First, text generation models are trained toward "natural text." Even if you ask for JSON only, they'll often wrap it in json ... blocks or prepend "Of course! Here is the JSON you requested:" style text. Here's what I reproduced directly: json Input: 'Give me 3 Python tips as JSON with keys: tips (array), difficulty (1-5)' Model output (no format parameter): ```json { "tips": [ "Master the fundamentals first...", ... ] } JSON parse: FAILED Python ' s `json.loads()` can ' t handle the markdown wrapper . The " JSON only " instruction is unreliable in production . Second , speed . I measured the same query both ways : 32 seconds without structured output , 5 seconds with it . More on why below . ## How the Ollama format Parameter Works Ollama ' s `/api/generate` endpoint has a `format` field. Pass a JSON schema object and Ollama applies **constrained decoding** during inference. python import json import urllib.request def ollama_structured(prompt, schema, model="gemma4:e4b"): payload = { "model": model, "prompt": prompt, "format": schema, # ← pass JSON schema object directly "stream": False, "options": {"temperature": 0} } data = json.dumps(payload).encode() req = urllib.request.Request( " http://localhost:11434/api/generate ", data=data

2026-06-17 原文 →
AI 资讯

pdf-pagenum: Fix Messy macOS Preview Page Numbers in PDFs from the CLI

A pip-installable CLI tool that auto-centers off-center page number annotations created by macOS Preview, or batch-adds new ones — with smart content avoidance and landscape support. The Problem If you've ever used macOS Preview to add page numbers to a PDF (via the text annotation tool), you know the pain: numbers land wherever you drop them, never centered, and manually positioning dozens or hundreds of them is soul-crushing. Especially when the PDF has mixed portrait and landscape pages. I ran into this preparing a thesis — 200+ pages of final manuscript, page numbers visibly off-center on every single page. Editing each one by hand wasn't an option. The Solution pdf-pagenum is a single CLI command that reads a folder of PDFs and centers every page number annotation to the bottom of its page. It works by: Detecting FreeText annotations that look like page numbers Measuring body content boundaries on each page Repositioning the annotation to a clean, centered position below the content — with proper margins Preserving the original page dimensions (no resizing, ever) If your PDF has pages with no annotations at all, it can generate new page numbers from scratch in the correct position. Install pip install pdf-pagenum That's it. PyMuPDF and natsort come along as dependencies. Usage Fix Mode (default) Reposition existing page number annotations so they're centered at the bottom: pdf-pagenum ./scans/ ./output/ This is the mode you'll use 90% of the time — it takes whatever rough page numbers Preview gave you and snaps them to the mathematically correct center. Add Mode Generate brand-new page numbers on pages that lack them: # Number all pages starting from 1 pdf-pagenum ./scans/ ./output/ --add all # Number pages 3 through 7 only pdf-pagenum ./scans/ ./output/ --add 3-7 # Number specific pages, starting count from 10 pdf-pagenum ./scans/ ./output/ --add 1,3,5-7 --start 10 Ranges and comma-separated lists can be mixed freely. Start Offset The --start N flag works in b

2026-06-17 原文 →
AI 资讯

How I Cut Costs 65% Migrating LangChain to DeepSeek

How I Cut Costs 65% Migrating LangChain to DeepSeek I want to tell you about a switch I made recently that genuinely surprised me. If you're running LangChain in production and haven't explored the DeepSeek models yet, this one's for you. Let me show you what I learned, what broke, and what I'll never go back to. The short version? I was burning cash on a generic LLM setup. I migrated to DeepSeek through Global API's unified interface, and my monthly inference bill dropped by over 60%. Setup took me less time than brewing coffee. Let me walk you through it. Why I Even Looked at This in the First Place Here's the thing about working in AI engineering: the model landscape moves so fast that whatever you chose six months ago is probably overpriced now. That's been my experience, anyway. When I first built my LangChain pipeline, I defaulted to a popular name-brand model because, well, that's what everyone was using. It worked. It was fine. Then I looked at my AWS bill. That's when I started digging into alternatives. And let me tell you, the rabbit hole is deep. Global API alone exposes 184 AI models at prices ranging from $0.01 to $3.50 per million tokens. That's a wild spread. The trick is finding the sweet spot where cost meets quality, and for migration workloads (think: code translation, schema conversion, content rewrites), I found it with DeepSeek. Let me show you the numbers that actually mattered to me. The Pricing Reality Nobody Talks About I built a comparison table when I was making this decision, and I want to share it because staring at these numbers side by side is what convinced me. Here's the lineup I evaluated through Global API: DeepSeek V4 Flash sits at $0.27 per million input tokens and $1.10 per million output tokens, with a 128K context window. That's my default for most production traffic now. Fast, cheap, and smart enough for almost everything. DeepSeek V4 Pro comes in at $0.55 input and $2.20 output with a beefier 200K context. I use this when

2026-06-17 原文 →