codi-api-agent 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ Metadata-Version: 2.4
2
+ Name: codi-api-agent
3
+ Version: 0.3.1
4
+ Summary: Read-only, spec-driven natural-language agent over any API (OpenAPI/Swagger, GraphQL, or auto-converted Postman/RAML/API Blueprint), with citations and a faithfulness check.
5
+ Author: API Agent
6
+ License: MIT
7
+ Project-URL: Documentation, https://github.com/your-org/api-agent/blob/main/HOW_IT_WORKS.md
8
+ Keywords: openapi,graphql,llm,agent,api,postman,read-only,rag
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Developers
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: openai>=1.30
16
+ Requires-Dist: requests>=2.31
17
+ Requires-Dist: python-dotenv>=1.0
18
+ Requires-Dist: pyyaml>=6.0
19
+ Requires-Dist: graphql-core>=3.2
20
+ Provides-Extra: ui
21
+ Requires-Dist: streamlit>=1.30; extra == "ui"
22
+ Provides-Extra: embeddings
23
+ Requires-Dist: sentence-transformers>=3.0; extra == "embeddings"
24
+ Requires-Dist: numpy>=1.26; extra == "embeddings"
25
+ Provides-Extra: sql
26
+ Requires-Dist: psycopg[binary]>=3.1; extra == "sql"
27
+ Provides-Extra: all
28
+ Requires-Dist: streamlit>=1.30; extra == "all"
29
+ Requires-Dist: sentence-transformers>=3.0; extra == "all"
30
+ Requires-Dist: numpy>=1.26; extra == "all"
31
+ Provides-Extra: test
32
+ Requires-Dist: pytest>=8; extra == "test"
33
+ Provides-Extra: evals
34
+ Requires-Dist: evals>=3.0.1; extra == "evals"
35
+ Requires-Dist: pyyaml>=6; extra == "evals"
36
+
37
+ # API Agent
38
+
39
+ Load an **API description** — OpenAPI/Swagger or GraphQL natively, a Postman
40
+ collection / RAML / API Blueprint (auto-converted on load), or even a **prose API
41
+ reference doc** — ask a question in natural language, and the agent picks the
42
+ right operations, calls them (strictly read-only), and returns an **answer with
43
+ citations** plus a multi-signal **evaluation** (grounding, sufficiency,
44
+ responsiveness). Ships with a Streamlit UI with live steps, streaming answers,
45
+ and token/cost tracking.
46
+
47
+ ```
48
+ Load spec(s) / reference doc ──▶ Catalog of operations
49
+ │
50
+ User question ──▶ Router + intent (narrow to relevant ops) ──▶ Executor (call operations)
51
+ ──▶ Synthesis + Citation ──▶ Self-review ──▶ Evaluator ──▶ Answer
52
+ ```
53
+
54
+ The LLM provider is an **OpenAI-compatible endpoint**, so the model is a config
55
+ value — Groq, HuggingFace, Ollama and OpenAI are all swappable without code
56
+ changes. The **generator**, **judge** and **router** roles are configured separately.
57
+ Full internals in [How_It_Works.md](How_It_Works.md).
58
+
59
+ ## Install as a pip package (share it / minimal setup)
60
+
61
+ ```bash
62
+ python -m venv .venv && source .venv/bin/activate
63
+ pip install "codi-api-agent[all]" # from a package index
64
+ # or from a wheel someone shared with you:
65
+ # pip install "codi_api_agent-0.3.1-py3-none-any.whl[all]"
66
+ export LLM_API_KEY="your-groq-or-openai-key"
67
+ api-agent # opens the UI at http://localhost:8501
68
+ ```
69
+
70
+ The distribution is `codi-api-agent`; the import name stays `api_agent`
71
+ (`from api_agent import Agent`).
72
+
73
+ Then add a free no-auth demo spec in the sidebar (Countries GraphQL or the SWAPI Postman
74
+ collection) and ask away. **Full step-by-step in [TUTORIAL.md](TUTORIAL.md).** Build the wheel
75
+ yourself from a checkout with `pip install build && python -m build` (→ `dist/`).
76
+
77
+ ## Setup (from a source checkout)
78
+
79
+ ```bash
80
+ python3 -m venv .venv && source .venv/bin/activate
81
+ pip install -e ".[all]" # editable install with UI + embeddings
82
+ cp .env.example .env # then edit .env with your provider + key
83
+ ```
84
+
85
+ | Provider | `LLM_BASE_URL` | Key | Notes |
86
+ |---|---|---|---|
87
+ | **Groq** (recommended) | `https://api.groq.com/openai/v1` | free API key | fast, good tool-calling |
88
+ | **HuggingFace** | `https://router.huggingface.co/v1` | HF token | many open models |
89
+ | **Ollama** (local) | `http://localhost:11434/v1` | any non-empty string | offline; pick a tool-calling model |
90
+ | **OPENAI** | `https://api.openai.com/v1` | api-key | open ai models |
91
+
92
+ Set `GENERATOR_MODEL` / `JUDGE_MODEL` to models your provider serves **that support
93
+ tool/function calling** (e.g. on Groq, `llama-3.3-70b-versatile`).
94
+
95
+ **Rate-limit resilience:** give several keys (`LLM_API_KEYS=key1,key2,…`) and/or whole
96
+ backends (`LLM_POOL='[{"base_url":…,"api_key":…,"model":…}, …]'`) and the client rotates
97
+ over them per query and **fails over on a 429** with a cooldown — useful on free tiers.
98
+
99
+ **Cost controls (for paid, per-token providers):** set `MAX_RESPONSE_TOKENS` to cap tokens per
100
+ response — the agent stops early and returns a partial answer once the ceiling is hit (0 = unlimited).
101
+ Each response also shows an estimated **$ cost**; override the built-in per-model prices with
102
+ `MODEL_PRICING` (JSON per 1M tokens, e.g. `MODEL_PRICING='{"gpt-4o":[2.5,10]}'`) or the sidebar
103
+ **💲 Budget & cost** fields. Unknown/free models simply show no cost.
104
+
105
+ ## Run
106
+
107
+ ```bash
108
+ streamlit run app/streamlit_app.py
109
+ ```
110
+
111
+ It opens empty — add an API via the sidebar's **📚 Load an API** panel (set
112
+ `DEFAULT_SPEC=<url-or-path>` in `.env` to auto-load one on startup). Free, no-auth
113
+ demos to try: the **Countries GraphQL** endpoint `https://countries.trevorblades.com/`
114
+ (tick **GraphQL API**), or the Petstore spec
115
+ `https://petstore.swagger.io/v2/swagger.json` → *“fetch all pets that are sold”*.
116
+
117
+ ## Load any API spec
118
+
119
+ Sidebar → **📚 Load an API** → paste a spec **URL or file path** (or upload files) →
120
+ **➕ Add spec**. OpenAPI/Swagger and GraphQL load natively; a Postman collection,
121
+ RAML 0.8, or API Blueprint file is **detected from its content and auto-converted**
122
+ to OpenAPI on load. You can add **several sources** (any mix of formats) — each keeps
123
+ its own base URL and auth, and one question can span all of them.
124
+
125
+ Every `GET`/`HEAD` operation (or GraphQL **query** field) becomes a callable tool
126
+ (write operations are excluded — the read-only guardrail; they remain *describable*
127
+ in documentation mode). Each operation maps: `operationId` → name,
128
+ `summary`/`description` → routing text, `parameters` → arguments, `servers`
129
+ (or Swagger-2.0 `host`+`basePath`) → base URL.
130
+
131
+ **Authenticated (private) APIs:** open the **Auth (optional)** expander and set a
132
+ header before loading — e.g. `Authorization` = `Bearer <token>`, or `X-API-Key` =
133
+ `<key>`. It's attached to every call. If an API needs auth and none is set, the
134
+ agent says so instead of guessing.
135
+
136
+ **No spec?** Write a small one from the
137
+ [minimal template](examples/minimal_rest_template.openapi.yaml) — describe just the `GET`
138
+ endpoints you care about (copy a block per endpoint), then load it as a file path. You don't
139
+ need to be an OpenAPI expert; the `summary`/`description` you write are what the agent routes on.
140
+
141
+ ## Other formats (RAML / API Blueprint / Postman)
142
+
143
+ The agent's pipeline is format-agnostic — only the *loader* speaks OpenAPI — so these are
144
+ **converted to OpenAPI automatically when you load them** (in the UI or via `load_catalog`).
145
+ To pre-convert from the terminal instead:
146
+
147
+ ```bash
148
+ python scripts/convert_spec.py path/to/api.apib -o specs/api.openapi.json # API Blueprint
149
+ python scripts/convert_spec.py path/to/api.raml --base-url https://your-host.com # RAML 0.8
150
+ python scripts/convert_postman.py your.postman_collection.json --base-url https://your-host.com
151
+ ```
152
+
153
+ | Input | Converts to | Notes |
154
+ |---|---|---|
155
+ | **API Blueprint** (`.apib`) | Swagger 2.0 | read natively |
156
+ | **RAML 0.8** (`.raml`) | OpenAPI 3.0 | RAML **1.0** has no good free CLI converter — convert it to 0.8/OpenAPI first |
157
+ | **Postman collection** | OpenAPI 3.0 | see [scripts/convert_postman.py](scripts/convert_postman.py) |
158
+
159
+ Requires Node/npx (the converters are npm tools, fetched on first use).
160
+
161
+ ## No spec at all? Load a prose API reference doc
162
+
163
+ Sidebar → **📚 Load an API** → source type **API reference doc** → point it at a
164
+ reference page (URL, file, or upload) → **🔍 Extract endpoints**. The documented
165
+ `METHOD /path` lines, curl examples, path and query params are extracted from the
166
+ doc's **literal text** (free, deterministic — it cannot invent an endpoint); an
167
+ optional checkbox lets the LLM also enrich param types or handle prose-only docs.
168
+ You then **review and approve** the extracted endpoints before any become callable —
169
+ GETs load as tools, writes as documentation-only.
170
+
171
+ Inspect what a spec produces from the terminal:
172
+
173
+ ```bash
174
+ python scripts/load_openapi_demo.py # default: Petstore
175
+ python scripts/load_openapi_demo.py --source your_spec.yaml --no-call
176
+ ```
177
+
178
+ ## Verified working spec URLs (no auth)
179
+
180
+ | API | Spec URL |
181
+ |---|---|
182
+ | Petstore v2 (pets) — *default* | `https://petstore.swagger.io/v2/swagger.json` |
183
+ | APIs.guru (API directory) | `https://api.apis.guru/v2/specs/apis.guru/2.2.0/openapi.json` |
184
+ | ExchangeRate-API (FX rates) | `https://api.apis.guru/v2/specs/exchangerate-api.com/4/openapi.json` |
185
+ | Color Name API | `https://api.apis.guru/v2/specs/color.pizza/1.0.0/openapi.json` |
186
+
187
+ ## Query your own GitHub repos
188
+
189
+ GitHub publishes its OpenAPI spec, so you can ask about *your* account:
190
+
191
+ 1. **Load the public spec** (sidebar → **📚 Load an API** → *URL or file path*):
192
+ `https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json`
193
+ It has ~624 GET operations; the default **Max operations to load** (1000) loads them
194
+ all and the router narrows per query.
195
+ 2. **Set a token** in the **Auth** expander *before loading*: header `Authorization`,
196
+ value `Bearer <your GitHub PAT>` (a token with `repo` / read scope).
197
+ 3. **Ask:** *“show my repositories”* → routes to `GET /user/repos` and lists your repos.
198
+
199
+ More once loaded + authed: *“who am I on GitHub?”* (`GET /user`), *“list my open issues”*.
200
+
201
+ > The big GitHub spec takes a few seconds to fetch/parse on load. Without a token,
202
+ > authed endpoints return 401 and the agent tells you a key is needed.
203
+
204
+ ## Routing (large specs)
205
+
206
+ When a spec has many operations, the **router** narrows them to the most relevant
207
+ per query before the agent runs: **hybrid** recall — lexical (idf-weighted, stemmed)
208
+ fused with **local embeddings** (`all-MiniLM-L6-v2`, free/offline; catches paraphrases
209
+ with zero shared words) via Reciprocal Rank Fusion — then a fast LLM makes the final
210
+ pick **and classifies the request intent** (write/doc/data) in the same call. Falls
211
+ back to lexical-only if embeddings are unavailable. Specs with ≤ `router_min_tools`
212
+ (default 6) operations skip routing. Configure in the sidebar or via
213
+ `ROUTER_ENABLED` / `ROUTER_TOP_K` / `ROUTER_MODEL` / `ROUTER_MIN_TOOLS` /
214
+ `EMBEDDING_MODEL`.
215
+
216
+ ## Testing & performance report
217
+
218
+ Two ways to check the agent is behaving:
219
+
220
+ ```bash
221
+ ./scripts/run_checks.sh # deterministic regression suite (no LLM/network) — see tests/README.md
222
+ python evals/run_eval.py --offline # reliability report (from the suite), zero cost
223
+ python evals/run_eval.py # full report: reliability + live accuracy on public APIs (needs LLM_API_KEY)
224
+ ```
225
+
226
+ The eval harness writes a stakeholder-facing `evals/report.md` + `report.json` covering guardrail
227
+ reliability, per-category accuracy, faithfulness, read-only/PII safety, abstention, latency, and
228
+ (with `--repeats N`) run-to-run consistency. Details in [evals/README.md](evals/README.md).
229
+
230
+ ## Project layout
231
+
232
+ ```
233
+ api_agent/
234
+ config.py # env-driven settings (provider, per-component models, router, budget)
235
+ llm.py # OpenAI-compatible client + multi-LLM rotation + tool-call recovery
236
+ openapi_loader.py # OpenAPI/Swagger spec -> callable Tools; compaction + PII redaction
237
+ graphql_loader.py # GraphQL introspection/SDL + the load_catalog format dispatcher
238
+ spec_convert.py # Postman / RAML / API Blueprint -> OpenAPI (auto, via npx)
239
+ doc_extract.py # prose API reference doc -> draft OpenAPI (structural; LLM optional)
240
+ catalog.py # Tool + Catalog (operation registry + result cache + name recovery)
241
+ router.py # hybrid lexical+embedding routing per query
242
+ schemas.py # Evidence, Citation, ToolCall, Faithfulness, AgentResult, Usage
243
+ agent.py # pipeline: cache -> route -> execute -> synthesize -> review -> evaluate
244
+ ui.py # Streamlit app: live steps, streaming, Stop, token/cost, doc review gate
245
+ app/streamlit_app.py # entry point for the UI
246
+ scripts/load_openapi_demo.py # CLI: inspect a spec + one live call
247
+ tests/ # deterministic regression suite (no LLM/network)
248
+ evals/ # reliability + live-accuracy report harness
249
+ ```
250
+
251
+ ## Notes & limitations
252
+
253
+ - **Read-only:** only `GET`/`HEAD` operations are exposed; write endpoints are never called.
254
+ - **Honest failures:** if an operation needs a key (401/403), is unreachable, or the
255
+ server returns 5xx, the agent reports that clearly instead of guessing.
256
+ - **Not production-hardened:** the loader fetches the given spec URL and calls
257
+ endpoints as-is — SSRF egress controls and per-user credential scoping are
258
+ follow-ups; fine for dev against trusted specs.
259
+ - Public demo servers (e.g. Petstore **v3**) are often flaky — prefer v2 / a spec
260
+ whose server you control.
@@ -0,0 +1,31 @@
1
+ api_agent/__init__.py,sha256=SRr4n87J_1fiYWtA9eVSdxDyF3v8qiEomYwn_oXCBMc,1819
2
+ api_agent/__main__.py,sha256=cm4GAplCdbTKqB4q4GHQ46XSveEvil-aXo0pEUMQdgM,161
3
+ api_agent/_version.py,sha256=Q5frm4VFOXY1kVW1GZfGSmZjoxaajJ26mTtEH0P19P8,107
4
+ api_agent/agent.py,sha256=VQFI0rqLUBd8cOHs74wJHxQUKF2vjLsd5K01GlZqTts,409724
5
+ api_agent/catalog.py,sha256=c_yASjMu16Adwnr9jWxydWt8vsf3WkDSh2kwtpkTc10,7201
6
+ api_agent/chart.py,sha256=EniCGc5GQcaazBlpNG45trem3EXae2YXT_5QfTwyK8c,7558
7
+ api_agent/cli.py,sha256=exarta1dns3eoABAc7dJnhc6OxDBslumSTachRmLhyA,1101
8
+ api_agent/config.py,sha256=ZD-rBzgrH8WX5Ld3d7G5_HOQVam0mxNW0MCNq74zDpc,18978
9
+ api_agent/doc_extract.py,sha256=f8-xjlqEK5hLu7c0Dios22Tcy3zswd8mSxVs2cZD7OM,20919
10
+ api_agent/graphql_loader.py,sha256=fDK2E0gNt3N_m1wF-BLCrOpS8P3zGW_KDrgA4fcvA8w,14718
11
+ api_agent/llm.py,sha256=JTkUnbdP-WNFx2tEydOxY6bWkh3NzolU_DaYd7Q8GhQ,21736
12
+ api_agent/log.py,sha256=7-DxreeRbpOt1umtkXtGfM4ZJ1xugMjddpzaFto983E,6067
13
+ api_agent/metrics.py,sha256=nd72YB94erPYvFxKpsOKbnjgcdFzdTwbKPKspGYpNMs,54181
14
+ api_agent/openapi_loader.py,sha256=c3iSbAulqM7I6CQQ78I_z-zHuxl1G2oLmrTWCAj_bH0,27877
15
+ api_agent/router.py,sha256=m3uRrwiyL_nABDQS3P9ciwSRiPHSkS5ovKZMWFrATLs,14341
16
+ api_agent/schemas.py,sha256=jORxThmadYswOAcOMzwsQqjwllde8SkRrYnwcsQbPmM,12576
17
+ api_agent/spec_convert.py,sha256=bqQ_qrEOFbVuX_PAsoeTZhY-s8qRVliiMTyAggqZhDA,3901
18
+ api_agent/sql_loader.py,sha256=Os6-qcd8woT2Bm3xwglGuW14FI6cJelZPeIO6WSc_lU,67459
19
+ api_agent/supervisor.py,sha256=VolOu-V57BUKtEZ_HgFXtPXh3C0zSmK8b8PCxyt8GnU,8846
20
+ api_agent/ui.py,sha256=FYVY1yrGfANKEtMenVCIcn1vGH7G-aM7nJfVkgj_na4,51473
21
+ api_agent/prompts/__init__.py,sha256=4sA6Dpg1ef8W-vS8OOz-MA38PXBzz2XrPQvnTfmbnL4,1414
22
+ api_agent/prompts/advisory.py,sha256=rU0cd03gaGTFUP7zSo_wuD8cz6vETTX_vlMGwc8FZvU,3924
23
+ api_agent/prompts/executor.py,sha256=TcOwSWwCE5cPRxAUMKBRoryFLARPfMTldvKtk-04fsc,14119
24
+ api_agent/prompts/judges.py,sha256=TJxqOqC9LxZrnZHcRl3jSpkB1J7qg1rrnrxlIvmzpZs,15954
25
+ api_agent/prompts/support.py,sha256=ISAqipjK7-cMllEWxhzzyPiPa2he2SL8mBtMM3EXusk,4634
26
+ api_agent/prompts/synthesis.py,sha256=0fY-VOOe4dFhPRX4H_8ud0k4hEkuuAREHuorXY-1ky0,29069
27
+ codi_api_agent-0.3.1.dist-info/METADATA,sha256=MiAX1A-EpyqwvX26_CGaIUj_N-JclgFav_lpIGiCzEg,13250
28
+ codi_api_agent-0.3.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
29
+ codi_api_agent-0.3.1.dist-info/entry_points.txt,sha256=15AwPe9GGrAW7MpgyHqSfMWHS2lcIvKFQJVKHZMMrqQ,49
30
+ codi_api_agent-0.3.1.dist-info/top_level.txt,sha256=H84mDK01gK9siU_tWSmMMa4U8gZo3nduyH9-O0T4LZc,10
31
+ codi_api_agent-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ api-agent = api_agent.cli:main
@@ -0,0 +1 @@
1
+ api_agent