开源项目
🔥 pipeshub-ai / pipeshub-ai - PipesHub is an open-source fully extensible AI context layer
GitHub热门项目 | PipesHub is an open-source fully extensible AI context layer that unifies your business data for explainable enterprise search and agentic workflow automation. | Stars: 3,405 | 50 stars today | 语言: Python
AI 资讯
GPT-4o API Costs Dropped 50% - How to Recalculate Your AI Budget
OpenAI has cut prices on its frontier models again. If you're running any production workload on the API, your cost assumptions from six months ago are probably stale. The Real Impact of a Pricing Halving A 50% price cut sounds like pure good news, but it changes the calculus on decisions you already made. Projects you shelved because the token costs didn't pencil out deserve a second look. Architectures you built around cheaper, less capable models to save money may now be false economies - the cost gap between "good enough" and "best available" just got smaller. The more interesting shift is for teams running retrieval-augmented generation (RAG) pipelines - systems that pull relevant documents from a database at query time and feed them into the model as context. RAG workflows tend to be token-heavy because every retrieved chunk counts against your input token bill. At the old pricing, teams were aggressively trimming context windows and limiting retrieved chunks to stay within budget. At half the cost, you can retrieve more, keep longer context, and let the model reason over richer information - without changing a line of retrieval logic. Real Example Here's a simplified cost check you can drop into any project that calls the OpenAI API: import openai # Approximate pricing per 1M tokens (check platform.openai.com for current rates) INPUT_COST_PER_1M = 2.50 # update to current figure OUTPUT_COST_PER_1M = 10.00 # update to current figure def estimate_cost ( input_tokens : int , output_tokens : int ) -> float : return ( input_tokens / 1_000_000 * INPUT_COST_PER_1M + output_tokens / 1_000_000 * OUTPUT_COST_PER_1M ) # Example: a RAG call with 3,000 input tokens and 500 output tokens print ( f " Estimated cost per call: $ { estimate_cost ( 3000 , 500 ) : . 5 f } " ) # Run this across your monthly volume to see the real delta Multiply that per-call number by your actual monthly call volume and compare it against what you budgeted. For many teams, the difference will jus
开发者
🚀 SoloEngine v0.4.0 Release
🚀 SoloEngine v0.4.0 Release — Context Compaction, Browser/Terminal Panels, Token Statistics...
AI 资讯
Designing AI Evals: Clarity Now and Visualization Next
AI evals and analysis Let's say you're testing out new AI tools. Perhaps you implement and...
AI 资讯
Your agent ignored a failed tool call. Here's how to catch that in CI.
You ship an AI agent. It calls tools, reads results, calls more tools, answers. Most of the time it works. Then a user reports something wrong, you open the trace, and you find it: the charge_card tool returned a 402, and the agent just... kept going and told the customer their order shipped. That's not a hallucination in the "made up a fact" sense. It's a structural defect in the run — an ignored tool error. And here's the thing about structural defects: you don't need another LLM to find them. They're decidable by looking at the trace. That's the whole premise of tracelint : a linter for agent runs. It reads the execution trace — what the agent actually did — and flags structural bugs deterministically, with the exact trace lines as evidence and a CI exit code. It runs after the run, on the trace, not on your code. No second model ever judges it. Why not just use an LLM judge? Because for this class of bug, a judge is the wrong tool. Published trace-error benchmarks show LLM judges have low localization accuracy — they'll tell you "something seems off" without reliably pointing at which step . They're also non-deterministic, cost money per trace, and can't gate CI (would you fail a build on a coin-flip?). Meanwhile, a whole category of agent bugs is structurally decidable : A tool call whose arguments violate the tool's JSON Schema. That's not an opinion — you run the schema validator. A tool that returned an error, followed by the agent proceeding as if it hadn't. The same tool called 5 times with identical arguments and identical results (a stuck loop). Arguments that don't appear anywhere in what the agent observed (a candidate hallucinated value). None of these needs a model. They need the trace and a validator. That's what tracelint does. The 60-second version pip install tracelint tracelint demo --html demo.html demo runs a keyless validation suite — one planted instance of every defect, plus clean controls — and writes an HTML report. No API key, no model d
AI 资讯
PromptShrink
How I Cut LLM Token Usage by Up to 60% in Production If you work with LLM APIs (OpenAI, Anthropic, Gemini), you know the pain: every call costs money, and a big chunk of that cost is pure waste — verbose prompts, code pasted with no filtering, repeated context the model doesn't even need to understand the task. That's why I built PromptShrink: a prompt pre-processor that trims the excess before it ever hits the API, without losing what actually matters for the model to understand. The real problem Every time you feed a code snippet or a long prompt to an LLM, you're paying per token, not per character. Comments, whitespace, formatting meant for humans — all of that is dead weight the model doesn't need to do its job. At scale (thousands of calls per month), that adds up to a real bill. What PromptShrink does Packages entire repositories, minifying code and stripping comments, ready to paste as context into any LLM Simulates real dollar savings, comparing your current spend against the optimized version Visualizes everything on a dashboard — tokens saved, % reduction, active rules Plugs straight into your code via a Python SDK Becomes a browser extension, adding a "Shrink" button directly on ChatGPT, Claude.ai, Google AI Studio, and Poe In practice bash Package an entire project into optimized context promptshrink repo --path ./src --save-to-file context.txt Simulate monthly savings promptshrink calc --calls 100000 --tokens 800 --model gpt-4o Running calc on a scenario of [insert your real number here, e.g. "100k calls/month with gpt-4o"], the estimated savings came out to [$X per month] — just by trimming what's unnecessary before it reaches the model. Try it out The project is open source, with a CLI, a FastAPI backend, and a Python SDK. If you're running LLMs in production and want to stop paying for tokens that add zero value, check it out: 🔗 github.com/HeloisaPeGarcia/PromptShrink Feedback and PRs are very welcome — this is my first published project like this,
AI 资讯
Cómo integrar un LLM (Claude o GPT) en tu aplicación Python
Integrar un modelo de lenguaje (LLM) en una aplicación Python es hoy más sencillo de lo que parece, y abre la puerta a chatbots, asistentes internos, extracción de datos y automatización con lenguaje natural. En esta guía verás el patrón completo, con código real. 1. Elige el proveedor Los tres más usados son Anthropic (Claude) , OpenAI (GPT) y Google (Gemini) . Todos exponen una API HTTP con un SDK de Python oficial, y la lógica de tu app apenas cambia entre ellos. En los ejemplos usaré Claude, pero el patrón es idéntico en los demás. Instala el SDK y guarda tu clave en una variable de entorno , nunca en el código: pip install anthropic export ANTHROPIC_API_KEY = "tu-clave" 2. La llamada mínima El patrón es siempre el mismo: envías una lista de mensajes y recibes una respuesta. from anthropic import Anthropic client = Anthropic () # lee ANTHROPIC_API_KEY del entorno resp = client . messages . create ( model = " claude-opus-4-8 " , max_tokens = 1024 , messages = [ { " role " : " user " , " content " : " Resume en una frase: la fotosíntesis... " } ], ) print ( resp . content [ 0 ]. text ) Dos detalles importantes: resp.content es una lista de bloques (comprueba .type antes de leer .text ), y max_tokens limita la longitud de la respuesta. 3. Streaming para una buena experiencia En una interfaz, esperar a que se genere todo el texto se siente lento. El streaming muestra la respuesta token a token, como en ChatGPT: with client . messages . stream ( model = " claude-opus-4-8 " , max_tokens = 1024 , messages = [{ " role " : " user " , " content " : " Escribe un email de bienvenida. " }], ) as stream : for text in stream . text_stream : print ( text , end = "" , flush = True ) Para salidas largas, el streaming además evita que la petición supere el tiempo de espera de la conexión. 4. Salida estructurada (JSON fiable) Si necesitas que el modelo devuelva datos en un formato exacto (por ejemplo para guardarlos en una base de datos), pide un esquema JSON en vez de parsear text
AI 资讯
How Python Takes Out Its Own Garbage
Python manages memory automatically, freeing developers from manual allocation and deallocation. It does this through two complementary mechanisms: reference counting and a generational garbage collector for cyclic references. This article covers how garbage collection works in CPython. In other implementations such as PyPy, it works under a different mechanism Reference Counting: The Primary Mechanism Every object in Python carries a reference count, a tally of how many references point to it. This count increments when: A new reference is assigned ( y = x ) It's stored in a container (list, dict, etc.) The object is passed into a function It decrements when: A reference goes out of scope A reference is reassigned del is manually called on a reference import sys x = [] y = x z = { " y " : y } print ( sys . getrefcount ( x )) # 4 (x + y + z + the arg to getrefcount) y = 1 del z print ( sys . getrefcount ( x )) # 2 (x + the arg to getrefcount) When the count hits zero, CPython deallocates the object immediately . This is a key difference from garbage-collected languages like Java, JS or the PyPy implementation, where collection timing is unpredictable. The Problem: Reference Cycles Reference counting alone cannot handle cyclic references, where objects reference each other and keep their counts above zero even when unreachable from the program: class MyClass : def __init__ ( self ): self . ref = None a = MyClass () b = MyClass () a . ref = b b . ref = a del a del b # a and b still reference each other -> the refcount never reaches 0 This causes a memory leak. The Solution: Generational Garbage Collector To catch scenarios like the above, Python includes a separate cyclic garbage collector, implemented in the gc module. It's based on the generational hypothesis : most objects die young, so recently created objects are checked more frequently than long-lived ones. Objects are organized into three generations : Generation Description Collection Frequency 0 Newly created
开发者
How to Reach Your Full Potential as a Programmer (It's Probably Not What You Think)
Every programmer wants to improve. We all dream about becoming the person who can look at a...
AI 资讯
Stop Guessing Calories: Build a Multimodal Food Estimation Pipeline with GPT-4o & SAM
We’ve all been there: staring at a delicious plate of pasta, trying to figure out if it's 400 or 800 calories. Manual tracking is a chore, and standard apps often fail at portion estimation. But what if we could combine Computer Vision , Multimodal LLMs , and Vector Databases to build an automated nutritionist? In this tutorial, we are building a state-of-the-art Multimodal Food Estimation Pipeline . By leveraging the Segment Anything Model (SAM) for precise boundary detection and GPT-4o Vision for contextual analysis, we can bridge the gap between "looking at a photo" and "calculating nutritional density." Whether you're interested in AI-driven wellness , FastAPI development , or Multimodal RAG , this guide covers the full stack. The Architecture 🏗️ The pipeline follows a sophisticated "Identify -> Analyze -> Match" flow. We don't just ask GPT-4o "what is this?"; we use SAM to isolate food items first to ensure the LLM focuses on the right pixels. graph TD A[User Uploads Image] --> B{SAM Model} B -->|Segmentation| C[Isolated Food Patches] C --> D[GPT-4o Vision API] D -->|Item + Volume Est.| E[Embedding Generation] E --> F[PostgreSQL + pgvector] F -->|RAG Retrieval| G[Verified Nutritional Data] G --> H[Final Response: Calories & Macros] Prerequisites 🛠️ Before we dive in, make sure you have the following ready: Python 3.10+ OpenAI API Key (for GPT-4o) PyTorch (for SAM) PostgreSQL with the pgvector extension enabled FastAPI for the backend Step 1: Precise Segmentation with SAM 🎯 The biggest challenge in food AI is overlapping items. Using Meta’s Segment Anything Model (SAM) , we can extract the exact mask of a food item, which helps in calculating the relative "area" occupied on the plate. import torch from segment_anything import sam_model_registry , SamPredictor import cv2 # Load SAM model sam_checkpoint = " sam_vit_h_4b8939.pth " model_type = " vit_h " sam = sam_model_registry [ model_type ]( checkpoint = sam_checkpoint ) predictor = SamPredictor ( sam ) def get_f
AI 资讯
How do you form a group nobody can admit they're in?
Arun invoiced a design agency ₹1,20,000 in January. It's August. He is in a 4,000-member designers' Discord. He could post the agency's name right now and warn everyone. He won't, and you already know why: the freelancer who publicly names a client stops getting briefs. He'd pay for it alone, and everyone else would benefit. Here's the part that makes it a systems problem rather than a sad story. Three other people in that same Discord are owed money by that same agency. None of them knows. Each one is running the same arithmetic Arun is, arriving at the same answer, and saying nothing. Four people who together have real leverage. Individually, none of them can afford the first move. I built an agent for this over a hackathon weekend. The interesting part wasn't the AI. It was that every obvious solution destroys the thing you're trying to protect. The obvious version, and why it dies "Just make a private channel for victims of bad clients." To join, you say who burned you. Now the group knows. One screenshot and Arun is on a list. "Okay, collect reports centrally and only reveal at a threshold." Better. This is roughly how Callisto Vault handles assault reports, and it's a good pattern. But it reveals the group to its own members at the threshold. Four people now know each other's names and amounts. Four times the leak surface, arriving exactly when things get tense. The requirement I ended up with was stricter than I expected: Nobody is exposed. Not to the channel, not to the accused, and not to each other — not even after it works. Which sounds impossible, because how do four people coordinate if they can't know who they are? They don't. The agent knows. Nobody else does. The public board that can't name the client Here's what actually appears in the Discord: PICKET · matter #1 > "invoiced in January, still chasing in August" ₹50k–2L · 180d+ overdue 🟩⬜⬜⬜ 1/4 joined [ JOIN ] One sentence Arun wrote himself. An amount band , not his figure. A counter. The agency's
开发者
i18n sin gettext: traducciones en JSON con claves de punto
Quieres que tu app hable español e inglés. Buscas cómo, y el ecosistema te empuja a gettext o Babel: ficheros .po , un paso de compilación a .mo , herramientas de extracción. Potente, sí. Pero para una app pequeña o mediana es un peaje que no querías pagar — solo necesitabas un t() honesto. Lo resolví tantas veces que lo empaqueté: dotkey-i18n , Python puro, sin dependencias. Tus traducciones son JSON que cualquiera puede editar: // locales/es.json { "login" : { "welcome" : "Hola, {name}" , "submit" : "Entrar" }, "menu" : { "reports" : "Informes" , "settings" : "Ajustes" } } from dotkey_i18n import Translator tr = Translator ( " locales " , default_lang = " es " ) tr . t ( " login.welcome " , name = " Juan " ) # "Hola, Juan" tr . t ( " menu.reports " , lang = " en " ) # "Reports" Tres detalles que marcan la diferencia Claves con notación de punto. t("login.submit") navega el JSON anidado. Agrupas las cadenas por pantalla o módulo sin claves planas kilométricas. Fallback al idioma por defecto. Si una clave falta en el idioma pedido, se busca en el idioma por defecto antes de rendirse. Tus traducciones pueden ir incompletas —la vida real— sin dejar huecos en blanco en la interfaz. Nunca revienta la interfaz. Una clave que no existe devuelve la propia clave (un marcador visible, no una excepción a mitad de render). Una interpolación con un campo que falta devuelve el texto sin formatear. Un JSON corrupto se trata como vacío. Nada de esto tumba la pantalla. Agnóstico del framework El idioma actual entra por un lang_getter inyectable, así el mismo Translator sirve en NiceGUI, Flask, FastAPI o un script suelto: # NiceGUI: idioma desde la sesión del usuario tr = Translator ( " locales " , default_lang = " es " , lang_getter = lambda : app . storage . user . get ( " idioma " )) # Flask tr = Translator ( " locales " , lang_getter = lambda : session . get ( " lang " )) La prioridad es clara: lang= explícito → lang_getter() → idioma por defecto. De dónde viene Salió del servic
AI 资讯
The Ultimate Code Review Checklist for Data Validation Frameworks
A comprehensive, production-ready checklist for reviewing data validation, ETL testing, and automated reconciliation codebases. Code reviews for data engineering tools need more rigor than standard web apps. A subtle bug in a data validation framework can cause silent pipeline failures, false positive test passes, or accidental execution of unbounded SQL queries on production warehouses. Whether you are building a custom data framework or maintaining automated ETL tests, use this generalized checklist during code reviews to keep your test suites secure, performant, and reliable. 1. Test Case Configuration (YAML / JSON) TC ID Matching: Ensure the tc_id value matches the configuration filename exactly. Schema Validity: Verify that type (e.g., count, data, recon, file) and source/target drivers are valid and supported. Explicit Enablers: Confirm the enabled field is explicitly set (true or false) rather than omitted. Relative File Paths: For file-based validation, ensure paths are relative to defined source/target data directories. Non-Empty Queries: Confirm SQL sources and targets include non-empty query strings or valid template paths. Unique Case IDs: Ensure test case identifiers are unique across the test suite directory. Documented Rationale: If a test case has enabled: false or uses numeric tolerance thresholds (validation_tolerance), ensure a comment explains the business reason. Dependency Order: Verify that basic structural checks (COUNT) run prior to deep comparisons (DATA / RECON). 2. SQL & Query Logic Explicit Projections: No SELECT *. All columns must be explicitly listed to avoid schema drift breaks. Alignment: Source and target queries must return compatible data types and matching column ordering. Environment Isolation: Check that query strings contain zero hardcoded hostnames, schema names, or environment paths. Secret Hygiene: Ensure queries contain no hardcoded credentials or connection strings. Warehouse Pushdown: Confirm filtering and heavy aggrega
开源项目
🔥 xai-org / grok-1 - Grok open release
GitHub热门项目 | Grok open release | Stars: 52,138 | 13 stars today | 语言: Python
AI 资讯
I stopped letting LLMs guess financial facts
LLMs can be surprisingly useful for company research. But I kept running into a strange split: parts of the reasoning were useful, while the financial facts underneath them were much harder to trust. A model could identify an accounting risk in one paragraph, then mix fiscal periods, accounting scopes, or currencies in the next. Missing values might quietly become zeros. A deterministic calculation could be performed probabilistically. A citation could point to a real filing without actually supporting the claim. Those are different failure modes, and treating all of them as one giant prompting problem did not feel like a reliable architecture. So I started building OpenThesis , an Apache-2.0 desktop system for evidence-first, AI-assisted company research. The project is not a stock picker or a trading bot. The idea is simpler: use ordinary software for work that should be deterministic, and give the LLM a bounded evidence set for the reasoning work where it can actually help. The monolithic prompt is doing too many jobs A common company-research workflow looks roughly like this: company question ↓ LLM ↓ answer That single model call is implicitly responsible for remembering reported values, selecting the right fiscal period, recognizing the accounting scope, finding sources, performing calculations, comparing scenarios, identifying risks, and writing a conclusion. Some of those tasks are probabilistic by nature. Others are not. Qualitative reasoning, connecting evidence, forming scenarios, and challenging an assumption are reasonable uses of a language model. Remembering an exact reported value, deciding whether a value is missing, and calculating a margin or valuation are poor places to accept probabilistic behavior. My design rule became: Deterministic work should stay deterministic. Use LLMs for reasoning, not as the database and calculator underneath the reasoning. Evidence before reasoning OpenThesis starts from official filings rather than from model memory o
AI 资讯
Shipping a vision-model verdict on Bedrock and Lightsail
Built 2026-08-15 against us.amazon.nova-lite-v1:0 via the Bedrock Converse API. FastAPI on Python 3.13, deployed to an Amazon Lightsail container service ( nano , scale 1) in us-east-1 . Scored against the live deployment, not localhost: 20/20 on the fixture set, median 880 ms per scan. Live: Dog or Not: Lite · Source: github.com/xbill9/dog-or-not-lite · Built for the AWS Weekend Challenge: Build a Creative App . TL;DR Make the model fill in a schema instead of writing a sentence. The Converse API's toolConfig plus toolChoice forces a named function call, so is_dog arrives as a boolean because it was declared as one. Every image comes back in the same shape — including the ambiguous ones, which is exactly where free-text output gets creative and a string-matching parser gets it wrong. The app is a webcam scanner that tells you whether the thing you are holding up is a dog. One HTML page, one POST /api/scan , one model call, no build step, no framework. The whole backend is 285 lines. Three AWS specifics are worth the price of admission: Lightsail container services have no IAM task role. There is nothing to attach a policy to, so the container needs a real access key as an environment variable. The mitigation is scope, not secrecy. A cross-region inference profile is authorized against every region it routes to. With the policy pinned to us-east-1 , a call made to us-east-1 was denied naming us-west-2 . Measured, not inferred. --platform linux/amd64 is not optional. An arm64 image builds, pushes and deploys cleanly, then crash-loops with an exec format error that never mentions architecture. And a mock mode that answers every scan locally is what made the frontend free to build — no credentials, no model access, no bill. 1. The shape: one route, one call The classification rule is the only opinionated part. is_dog is true only for a living domestic dog: a wolf is not a dog , nor is a coyote, fox, plush toy, bronze statue, cartoon, or person in a costume. That is a c
AI 资讯
Code Review From the Terminal and CI, No MCP Client Required
A month ago I shipped aicraft-code-review , an MCP server that reviews code locally. This week I added a CLI mode — because not everyone wants to wire up an MCP client just to check a diff. Now the same reviewer runs three ways: MCP tools — review_code / review_diff / review_file inside Claude Code, Cursor, Cline CLI — mcp-code-review review-file path/to/file.py CI — pipe git diff into it and branch on the exit code The CLI pip install aicraft-code-review # a single file (config auto-discovered from the file's directory upward) mcp-code-review review-file src/api.py # the current diff git diff | mcp-code-review review-diff # a snippet mcp-code-review review-code "import os; os.system('ls')" Exit codes are CI-friendly: Code Meaning 0 clean, or only info-level findings 1 high / medium issues found 2 critical issues found What it catches out of the box Security (OWASP patterns), performance (N+1, unbounded growth), quality (bare excepts, TODOs, missing type hints), style (naming, line length). Real output: ### 🟠 High (2) | Line | Issue | Category | Fix | | 4 | Command injection risk | security | subprocess.run with args list | | 9 | N+1 query in loop | performance | batch query / eager loading | ### 🟢 Info (2) — missing return type annotations Verdict: Conditional Pass — address high/medium issues Making it match YOUR rules The config file is the part I'd actually show a teammate: custom_rules : - name : no-console-log pattern : ' console\.log\(' severity : high category : quality issue : Console logging left in production code fix : Use a structured logger instead disabled_checks : - todo_comment severity_overrides : hardcoded_secret : critical .mcp-code-review.yaml is auto-discovered from the reviewed file's directory upward MCP_CODE_REVIEW_CONFIG points a whole team at one shared profile valid severities: critical / high / medium / info regex patterns work best in single quotes (double quotes will error on escapes like \. ) One caveat if you're also shipping Python
AI 资讯
How to Catch a Pine Script Repaint Bug Before It Costs You Real Money
I've watched too many TradingView strategies look great in the Strategy Tester and then fall apart the moment real money went live. Almost every time, the code compiled fine. The bug wasn't syntax. It was repainting, the script quietly using information it shouldn't have had yet. Repainting doesn't throw an error. It just quietly makes your backtest better than your live trading will ever be. Here are the four places it actually comes from, and how to catch each one before you trust a strategy. 1. request.security() with the wrong lookahead If you pull a higher-timeframe value with request.security() and don't handle the offset correctly, the current, still-forming HTF bar can leak into your calculation. The fix is barmerge.lookahead_off combined with offsetting the source by one bar, e.g. close[1]. lookahead_on is only safe when you've already offset the source yourself. Using it directly on a live value is the single most common repaint source in Pine scripts posted online. 2. Signals computed before the bar closes If your entry logic runs on close or ta.crossover() without a barstate.isconfirmed guard, the signal can appear, then disappear, then reappear as the candle's still-forming close price changes. What you saw fire in real time is not always what the finished bar actually did. Guard any entry/exit logic that matters with barstate.isconfirmed if you're evaluating it intrabar. 3. Same-bar stop/target ambiguity When your stop and your target could both have been hit inside the same bar's high-low range, the Strategy Tester has to guess which one happened first. It doesn't always tell you which assumption it made, and that one hidden assumption can flatter your win rate without you ever seeing it happen. 4. Bar Replay is the real manual test TradingView's Bar Replay tool is the closest thing to a repaint detector you already have. Step through history bar by bar and watch whether a signal that appeared in the past matches what you originally saw. If a signal m
AI 资讯
A Context Object Should Carry Its Receipt
A stored fact can be wrong in a quiet way. The answer still reads clean. A preference from an old exchange gets reused, the message goes out with confidence, and later nobody can tell why that detail was allowed back into the result. That is the failure I built around. When a system returns remembered material, the caller needs the text plus the reason it passed the reuse check. A log line found after the action is weak evidence. The object that leaves the memory service has to carry the admission record with it. 1. Keep the outside surface small This is the pattern I used in Holographic, Law-Bound Memory (HLM), a stand-alone memory brain outside application code. The README describes public Application Programming Interface (API) routes under /api/brain/* , with internal /api/v1/* services behind that layer. The outside shape is intentionally thin: register an agent, write a fact, build a capsule. The Python Software Development Kit (SDK) in sdks/python/hlm_sdk/client.py shows the boundary without exposing table names or policy code: import httpx class HLMClient : def __init__ ( self , base_url : str , token : str | None = None ): self . base_url = base_url . rstrip ( " / " ) self . _client = httpx . AsyncClient ( headers = { " Authorization " : f " Bearer { token } " } if token else None ) async def register_agent ( self , name : str ): r = await self . _client . post ( f " { self . base_url } /api/brain/agents/register " , json = { " name " : name }) r . raise_for_status return r . json async def write_fact ( self , text : str , tags : list [ str ] | None = None , selectors : list [ str ] | None = None ): r = await self . _client . post ( f " { self . base_url } /api/brain/memory/facts " , json = { " text " : text , " tags " : tags or [], " selectors " : selectors or []}) r . raise_for_status return r . json async def build_capsule ( self , query : str , budget_tokens : int = 2048 ): r = await self . _client . post ( f " { self . base_url } /api/brain/context/cap
AI 资讯
From CGM Alerts to Automated Grocery Shopping: Building an Autonomous Nutritionist Agent with Browser-use and LangChain
Imagine waking up to a notification on your phone: "Your blood sugar levels are dipping. I've already analyzed your recent CGM (Continuous Glucose Monitor) trends and added low-GI complex carbs to your grocery cart." 🚀 This isn't science fiction anymore. With the rise of Autonomous Agents and specialized libraries like Browser-use , we can now bridge the gap between health data analysis and real-world actions. In this tutorial, we are building a personalized Nutritionist Agent that monitors health metrics and navigates the web just like a human to fulfill your dietary needs. By leveraging LangChain for logic and Browser-use for web automation, we’re moving beyond simple chatbots to "Action-Oriented AI." 🏗 The Architecture: From Insight to Action The workflow involves three main layers: the Data Input (CGM reports), the Brain (LangChain Agent), and the Hands (Browser-use + Playwright/Selenium). graph TD A[CGM Sensor Data] -->|GraphQL/JSON| B(LangChain Agent) B -->|Analyze Risk| C{Hypoglycemia Detected?} C -->|Yes| D[Identify Low-GI Foods] D -->|Navigate Browser| E[Browser-use Controller] E -->|Automate Shopping| F[Fresh Grocery Site] F -->|Action| G[Add to Cart & Notify User] C -->|No| H[Continue Monitoring] 🛠 Prerequisites To follow along, you’ll need a Python environment and the following stack: LangChain : For orchestrating the LLM logic. Browser-use : The star of the show for AI-driven browser navigation. Playwright/Selenium : To handle the underlying browser instance. OpenAI/Anthropic API : To power the reasoning engine. Step 1: Analyzing the Health Data First, we need to process the CGM (Continuous Glucose Monitor) data. We'll use GraphQL to fetch the latest metrics and LangChain to determine if the user needs a nutritional intervention. import os from langchain_openai import ChatOpenAI from langchain.prompts import PromptTemplate # Mocking a CGM Data Fetcher via GraphQL logic def fetch_cgm_metrics (): # In a real scenario, use a GraphQL client to query your he