wiltech-labs-ai 1.0.1__tar.gz

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.
Files changed (24) hide show
  1. wiltech_labs_ai-1.0.1/.gitignore +220 -0
  2. wiltech_labs_ai-1.0.1/PKG-INFO +178 -0
  3. wiltech_labs_ai-1.0.1/README.md +160 -0
  4. wiltech_labs_ai-1.0.1/pyproject.toml +49 -0
  5. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/__init__.py +88 -0
  6. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/agents/__init__.py +18 -0
  7. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/agents/tool.py +32 -0
  8. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/agents/tool_agent.py +122 -0
  9. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/embeddings/__init__.py +17 -0
  10. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/embeddings/embeddings.py +96 -0
  11. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/llm/__init__.py +3 -0
  12. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/llm/llm.py +128 -0
  13. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/providers/__init__.py +21 -0
  14. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/providers/ai.py +136 -0
  15. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/py.typed +0 -0
  16. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/search/__init__.py +3 -0
  17. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/search/rrf.py +24 -0
  18. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/vectors/__init__.py +15 -0
  19. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/vectors/database_vector_store.py +106 -0
  20. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/vectors/qdrant_vector_store.py +117 -0
  21. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/vectors/vector_store.py +67 -0
  22. wiltech_labs_ai-1.0.1/src/wiltech_labs_ai/vectors/vectorize_vector_store.py +108 -0
  23. wiltech_labs_ai-1.0.1/tests/test_llm_and_providers.py +123 -0
  24. wiltech_labs_ai-1.0.1/tests/test_vectors_search_agent.py +187 -0
@@ -0,0 +1,220 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
219
+ /NEXT_STEPS11111.md
220
+ .idea/*
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.5
2
+ Name: wiltech-labs-ai
3
+ Version: 1.0.1
4
+ Summary: AI building blocks for Wiltech FastAPI apps: Workers AI / Groq / Ollama behind one protocol, OpenAI-compatible tool calling over httpx, embeddings, portable vector stores (database, Vectorize, Qdrant), hybrid-search fusion and a tool-calling agent loop.
5
+ Project-URL: Homepage, https://github.com/wilferraciolli/py-libraries/tree/main/packages/ai
6
+ Project-URL: Repository, https://github.com/wilferraciolli/py-libraries
7
+ Project-URL: Conventions, https://github.com/wilferraciolli/py-libraries/blob/main/docs/PYTHON_APP_CONVENTIONS.md
8
+ Author: Wiliam Ferraciolli
9
+ License-Expression: Apache-2.0
10
+ Keywords: embeddings,fastapi,groq,llm,ollama,qdrant,rag,vectorize,workers-ai
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.13
15
+ Requires-Dist: httpx>=0.27
16
+ Requires-Dist: wiltech-labs-core>=0.1.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # wiltech-labs-ai
20
+
21
+ AI building blocks for Wiltech FastAPI apps:
22
+
23
+ - **Providers**: Workers AI (binding or REST), Groq and **Ollama/any OpenAI-compatible
24
+ server** behind one `AI` protocol.
25
+ - **Tool calling**: `OpenAICompatibleLlm` over plain `httpx` (no `openai` package, which costs
26
+ about 1.4 s of CPU on a Python Worker cold start).
27
+ - **Embeddings**: Workers AI or Ollama.
28
+ - **Vector stores**: one `VectorStore` protocol with three adapters: the app's own database,
29
+ Cloudflare Vectorize, Qdrant.
30
+ - **Hybrid search**: `reciprocal_rank_fusion` to merge vector and keyword rankings.
31
+ - **Agent loop**: `ToolAgent` runs tools as the server-supplied user and returns the answer
32
+ with a trace.
33
+
34
+ Builds on [`wiltech-labs-core`](../core) (`get_config`, `Database`, errors). Pure Python
35
+ (`httpx`), so it runs in Cloudflare Workers.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ uv add wiltech-labs-ai
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ### Plain chat
46
+
47
+ ```python
48
+ from wiltech_labs_ai import get_ai
49
+
50
+ ai = get_ai(request, provider) # "cloudflare" | "groq" | "local"
51
+ reply = await ai.run(model, {"messages": [{"role": "user", "content": "Hello"}]})
52
+ reply["response"]
53
+ ```
54
+
55
+ ### "Ask your data": tools + agent
56
+
57
+ ```python
58
+ from wiltech_labs_ai import TOOL_RESULTS_ARE_DATA, Tool, ToolAgent, get_tool_llm
59
+
60
+
61
+ async def count_todos(user_id: str, args: dict) -> dict:
62
+ # user_id comes from the server (require_owner), never from the model
63
+ return {"count": await todo_repository.count(user_id, state=args.get("state"))}
64
+
65
+
66
+ tools = [Tool("count_todos", "Count the user's todos, optionally by state.",
67
+ {"type": "object", "properties": {"state": {"type": "string", "enum": ["NEW", "DONE"]}}},
68
+ count_todos)]
69
+
70
+ llm, model = get_tool_llm(request, provider) # 503 NotConfiguredError if a key is missing
71
+ result = await ToolAgent(llm, model, tools).run(user_id, [
72
+ {"role": "system", "content": f"Answer questions about the user's data. {TOOL_RESULTS_ARE_DATA}"},
73
+ {"role": "user", "content": question},
74
+ ])
75
+ result.answer, result.tool_calls, result.completed
76
+ ```
77
+
78
+ ### Embeddings + vector store + hybrid search
79
+
80
+ ```python
81
+ from wiltech_labs_ai import DatabaseVectorStore, VectorRecord, get_embedder, reciprocal_rank_fusion
82
+ from wiltech_labs_core import get_database
83
+
84
+ embed, model = get_embedder(request)
85
+ store = DatabaseVectorStore(get_database(request), namespace="todo")
86
+
87
+ # write path
88
+ [vector] = await embed([f"{todo.title}\n{todo.description or ''}"])
89
+ await store.upsert([VectorRecord(todo.id, scope=todo.user_id, vector=vector, model=model)])
90
+
91
+ # query path: meaning + exact words, fused
92
+ [query_vector] = await embed([q])
93
+ vector_hits = await store.query([user_id], query_vector, limit=30)
94
+ keyword_hits = await todo_repository.search_by_keyword(user_id, q, limit=30)
95
+ ranked = reciprocal_rank_fusion([m.id for m in vector_hits], [t.id for t in keyword_hits])
96
+
97
+ # backfill: embed only what's missing
98
+ missing = set(all_ids) - await store.existing_ids(all_ids)
99
+ ```
100
+
101
+ `scope` is the tenancy boundary: the owner's user id for private data, or a group id for
102
+ group data (query with every group the caller can see). Every `query` filters by it.
103
+
104
+ #### Choosing a store
105
+
106
+ | Store | Where | Good for | Setup |
107
+ |---|---|---|---|
108
+ | `DatabaseVectorStore(db, namespace)` | SQLite / D1 | Thousands of vectors per scope; no extra infra | `RESOURCE_EMBEDDINGS_TABLE_SQL` migration (the same table as `fastapi-ai` migration 007) |
109
+ | `VectorizeVectorStore(account, token, index, namespace)` | Cloudflare (free: ~5M stored dimensions, about 6.5k vectors at 768 dims) | Larger data on Cloudflare | `wrangler vectorize create <index> --dimensions=768 --metric=cosine` **and** `wrangler vectorize create-metadata-index <index> --propertyName=scope --type=string` |
110
+ | `QdrantVectorStore(url, collection, namespace, api_key)` | Home server (`qdrant/qdrant`) | No practical limit, private | `await store.ensure_collection(768)` once |
111
+
112
+ All three are interchangeable behind `VectorStore`. Switching store means re-embedding
113
+ (run your backfill against the new store).
114
+
115
+ ## Configuration
116
+
117
+ | Variable | Used by | Default |
118
+ |---|---|---|
119
+ | `AI_MODE` | `get_ai("cloudflare")` | `binding` if `env.AI` exists, else `http` |
120
+ | `CF_AI_ACCOUNT_ID`, `CF_AI_API_TOKEN` | Workers AI REST, `get_tool_llm("cloudflare")` | — |
121
+ | `CF_AI_MODEL` | `get_tool_llm("cloudflare")` | — |
122
+ | `GROQ_API_KEY`, `GROQ_BASE_URL`, `GROQ_MODEL` | Groq | — |
123
+ | `LOCAL_LLM_BASE_URL` | Ollama / local | `http://localhost:11434/v1` (in Docker: `http://ollama:11434/v1`) |
124
+ | `LOCAL_LLM_API_KEY` | local | `ollama` |
125
+ | `LOCAL_LLM_MODEL` | `get_tool_llm("local")` | — (e.g. `qwen3:8b`) |
126
+ | `EMBEDDING_PROVIDER` | `get_embedder` | `cloudflare` (or `local`) |
127
+ | `CF_EMBEDDING_MODEL` | `get_embedder` | `@cf/baai/bge-base-en-v1.5` (English only; `@cf/baai/bge-m3` for Greek/Portuguese) |
128
+ | `LOCAL_EMBEDDING_MODEL` | `get_embedder` (local) | `bge-m3` |
129
+
130
+ ## Public API
131
+
132
+ | Name | What it is |
133
+ |---|---|
134
+ | `AI`, `get_ai(request, provider)`, `ChatProvider` | Run a model: `run(model, inputs) -> dict` |
135
+ | `AiBindingAdapter`, `AiHttpAdapter`, `OpenAICompatibleChatAdapter` (alias `GroqAdapter`) | The adapters |
136
+ | `workers_ai_openai_base_url(account_id)` | `…/accounts/{id}/ai/v1` |
137
+ | `ToolLlm`, `OpenAICompatibleLlm`, `chat_completion`, `get_tool_llm(request, provider)` | Tool-calling chat completions; errors are `UpstreamError` (502), with the provider's body logged, not returned |
138
+ | `embed`, `embed_openai_compatible`, `get_embedder`, `EmbedFn`, `DEFAULT_EMBEDDING_MODEL`, `MAX_EMBED_CHARS` | Embeddings (batched by 50, truncated to 2,000 chars) |
139
+ | `VectorStore`, `VectorRecord`, `VectorMatch`, `normalise` | The vector protocol |
140
+ | `DatabaseVectorStore`, `RESOURCE_EMBEDDINGS_TABLE_SQL`, `VectorizeVectorStore`, `QdrantVectorStore` | The stores |
141
+ | `reciprocal_rank_fusion(*rankings, k=60)`, `RRF_K` | Hybrid-search fusion |
142
+ | `Tool`, `ToolHandler`, `ToolAgent`, `AgentResult`, `ToolCallRecord`, `STEP_LIMIT_ANSWER`, `TOOL_RESULTS_ARE_DATA` | The agent loop |
143
+
144
+ ## Development
145
+
146
+ ```bash
147
+ uv run --package wiltech-labs-ai pytest packages/ai
148
+ ```
149
+
150
+ ## Publishing
151
+
152
+ Publish `wiltech-labs-core` first; this package depends on it.
153
+
154
+ ```bash
155
+ cd packages/ai
156
+
157
+ # 1. Test, bump, build
158
+ uv run pytest
159
+ uv version --bump patch # or minor / major; skip for the first 0.1.0
160
+ rm -rf ../../dist && uv build # -> ../../dist/
161
+
162
+ # 2. TestPyPI (optional rehearsal), using a token from test.pypi.org
163
+ read -rsp "TestPyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
164
+ uv publish --index testpypi ../../dist/*
165
+ unset UV_PUBLISH_TOKEN
166
+
167
+ # 3. PyPI (the real thing), using a token from pypi.org
168
+ read -rsp "PyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
169
+ uv publish ../../dist/*
170
+ unset UV_PUBLISH_TOKEN
171
+
172
+ # 4. Commit and tag
173
+ git commit -am "wiltech-labs-ai <version>"
174
+ git tag ai-v<version> && git push && git push --tags
175
+ ```
176
+
177
+ A version number can only be uploaded once to each site. To retry after a fix, bump the
178
+ version and rebuild.
@@ -0,0 +1,160 @@
1
+ # wiltech-labs-ai
2
+
3
+ AI building blocks for Wiltech FastAPI apps:
4
+
5
+ - **Providers**: Workers AI (binding or REST), Groq and **Ollama/any OpenAI-compatible
6
+ server** behind one `AI` protocol.
7
+ - **Tool calling**: `OpenAICompatibleLlm` over plain `httpx` (no `openai` package, which costs
8
+ about 1.4 s of CPU on a Python Worker cold start).
9
+ - **Embeddings**: Workers AI or Ollama.
10
+ - **Vector stores**: one `VectorStore` protocol with three adapters: the app's own database,
11
+ Cloudflare Vectorize, Qdrant.
12
+ - **Hybrid search**: `reciprocal_rank_fusion` to merge vector and keyword rankings.
13
+ - **Agent loop**: `ToolAgent` runs tools as the server-supplied user and returns the answer
14
+ with a trace.
15
+
16
+ Builds on [`wiltech-labs-core`](../core) (`get_config`, `Database`, errors). Pure Python
17
+ (`httpx`), so it runs in Cloudflare Workers.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ uv add wiltech-labs-ai
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### Plain chat
28
+
29
+ ```python
30
+ from wiltech_labs_ai import get_ai
31
+
32
+ ai = get_ai(request, provider) # "cloudflare" | "groq" | "local"
33
+ reply = await ai.run(model, {"messages": [{"role": "user", "content": "Hello"}]})
34
+ reply["response"]
35
+ ```
36
+
37
+ ### "Ask your data": tools + agent
38
+
39
+ ```python
40
+ from wiltech_labs_ai import TOOL_RESULTS_ARE_DATA, Tool, ToolAgent, get_tool_llm
41
+
42
+
43
+ async def count_todos(user_id: str, args: dict) -> dict:
44
+ # user_id comes from the server (require_owner), never from the model
45
+ return {"count": await todo_repository.count(user_id, state=args.get("state"))}
46
+
47
+
48
+ tools = [Tool("count_todos", "Count the user's todos, optionally by state.",
49
+ {"type": "object", "properties": {"state": {"type": "string", "enum": ["NEW", "DONE"]}}},
50
+ count_todos)]
51
+
52
+ llm, model = get_tool_llm(request, provider) # 503 NotConfiguredError if a key is missing
53
+ result = await ToolAgent(llm, model, tools).run(user_id, [
54
+ {"role": "system", "content": f"Answer questions about the user's data. {TOOL_RESULTS_ARE_DATA}"},
55
+ {"role": "user", "content": question},
56
+ ])
57
+ result.answer, result.tool_calls, result.completed
58
+ ```
59
+
60
+ ### Embeddings + vector store + hybrid search
61
+
62
+ ```python
63
+ from wiltech_labs_ai import DatabaseVectorStore, VectorRecord, get_embedder, reciprocal_rank_fusion
64
+ from wiltech_labs_core import get_database
65
+
66
+ embed, model = get_embedder(request)
67
+ store = DatabaseVectorStore(get_database(request), namespace="todo")
68
+
69
+ # write path
70
+ [vector] = await embed([f"{todo.title}\n{todo.description or ''}"])
71
+ await store.upsert([VectorRecord(todo.id, scope=todo.user_id, vector=vector, model=model)])
72
+
73
+ # query path: meaning + exact words, fused
74
+ [query_vector] = await embed([q])
75
+ vector_hits = await store.query([user_id], query_vector, limit=30)
76
+ keyword_hits = await todo_repository.search_by_keyword(user_id, q, limit=30)
77
+ ranked = reciprocal_rank_fusion([m.id for m in vector_hits], [t.id for t in keyword_hits])
78
+
79
+ # backfill: embed only what's missing
80
+ missing = set(all_ids) - await store.existing_ids(all_ids)
81
+ ```
82
+
83
+ `scope` is the tenancy boundary: the owner's user id for private data, or a group id for
84
+ group data (query with every group the caller can see). Every `query` filters by it.
85
+
86
+ #### Choosing a store
87
+
88
+ | Store | Where | Good for | Setup |
89
+ |---|---|---|---|
90
+ | `DatabaseVectorStore(db, namespace)` | SQLite / D1 | Thousands of vectors per scope; no extra infra | `RESOURCE_EMBEDDINGS_TABLE_SQL` migration (the same table as `fastapi-ai` migration 007) |
91
+ | `VectorizeVectorStore(account, token, index, namespace)` | Cloudflare (free: ~5M stored dimensions, about 6.5k vectors at 768 dims) | Larger data on Cloudflare | `wrangler vectorize create <index> --dimensions=768 --metric=cosine` **and** `wrangler vectorize create-metadata-index <index> --propertyName=scope --type=string` |
92
+ | `QdrantVectorStore(url, collection, namespace, api_key)` | Home server (`qdrant/qdrant`) | No practical limit, private | `await store.ensure_collection(768)` once |
93
+
94
+ All three are interchangeable behind `VectorStore`. Switching store means re-embedding
95
+ (run your backfill against the new store).
96
+
97
+ ## Configuration
98
+
99
+ | Variable | Used by | Default |
100
+ |---|---|---|
101
+ | `AI_MODE` | `get_ai("cloudflare")` | `binding` if `env.AI` exists, else `http` |
102
+ | `CF_AI_ACCOUNT_ID`, `CF_AI_API_TOKEN` | Workers AI REST, `get_tool_llm("cloudflare")` | — |
103
+ | `CF_AI_MODEL` | `get_tool_llm("cloudflare")` | — |
104
+ | `GROQ_API_KEY`, `GROQ_BASE_URL`, `GROQ_MODEL` | Groq | — |
105
+ | `LOCAL_LLM_BASE_URL` | Ollama / local | `http://localhost:11434/v1` (in Docker: `http://ollama:11434/v1`) |
106
+ | `LOCAL_LLM_API_KEY` | local | `ollama` |
107
+ | `LOCAL_LLM_MODEL` | `get_tool_llm("local")` | — (e.g. `qwen3:8b`) |
108
+ | `EMBEDDING_PROVIDER` | `get_embedder` | `cloudflare` (or `local`) |
109
+ | `CF_EMBEDDING_MODEL` | `get_embedder` | `@cf/baai/bge-base-en-v1.5` (English only; `@cf/baai/bge-m3` for Greek/Portuguese) |
110
+ | `LOCAL_EMBEDDING_MODEL` | `get_embedder` (local) | `bge-m3` |
111
+
112
+ ## Public API
113
+
114
+ | Name | What it is |
115
+ |---|---|
116
+ | `AI`, `get_ai(request, provider)`, `ChatProvider` | Run a model: `run(model, inputs) -> dict` |
117
+ | `AiBindingAdapter`, `AiHttpAdapter`, `OpenAICompatibleChatAdapter` (alias `GroqAdapter`) | The adapters |
118
+ | `workers_ai_openai_base_url(account_id)` | `…/accounts/{id}/ai/v1` |
119
+ | `ToolLlm`, `OpenAICompatibleLlm`, `chat_completion`, `get_tool_llm(request, provider)` | Tool-calling chat completions; errors are `UpstreamError` (502), with the provider's body logged, not returned |
120
+ | `embed`, `embed_openai_compatible`, `get_embedder`, `EmbedFn`, `DEFAULT_EMBEDDING_MODEL`, `MAX_EMBED_CHARS` | Embeddings (batched by 50, truncated to 2,000 chars) |
121
+ | `VectorStore`, `VectorRecord`, `VectorMatch`, `normalise` | The vector protocol |
122
+ | `DatabaseVectorStore`, `RESOURCE_EMBEDDINGS_TABLE_SQL`, `VectorizeVectorStore`, `QdrantVectorStore` | The stores |
123
+ | `reciprocal_rank_fusion(*rankings, k=60)`, `RRF_K` | Hybrid-search fusion |
124
+ | `Tool`, `ToolHandler`, `ToolAgent`, `AgentResult`, `ToolCallRecord`, `STEP_LIMIT_ANSWER`, `TOOL_RESULTS_ARE_DATA` | The agent loop |
125
+
126
+ ## Development
127
+
128
+ ```bash
129
+ uv run --package wiltech-labs-ai pytest packages/ai
130
+ ```
131
+
132
+ ## Publishing
133
+
134
+ Publish `wiltech-labs-core` first; this package depends on it.
135
+
136
+ ```bash
137
+ cd packages/ai
138
+
139
+ # 1. Test, bump, build
140
+ uv run pytest
141
+ uv version --bump patch # or minor / major; skip for the first 0.1.0
142
+ rm -rf ../../dist && uv build # -> ../../dist/
143
+
144
+ # 2. TestPyPI (optional rehearsal), using a token from test.pypi.org
145
+ read -rsp "TestPyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
146
+ uv publish --index testpypi ../../dist/*
147
+ unset UV_PUBLISH_TOKEN
148
+
149
+ # 3. PyPI (the real thing), using a token from pypi.org
150
+ read -rsp "PyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
151
+ uv publish ../../dist/*
152
+ unset UV_PUBLISH_TOKEN
153
+
154
+ # 4. Commit and tag
155
+ git commit -am "wiltech-labs-ai <version>"
156
+ git tag ai-v<version> && git push && git push --tags
157
+ ```
158
+
159
+ A version number can only be uploaded once to each site. To retry after a fix, bump the
160
+ version and rebuild.
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "wiltech-labs-ai"
3
+ version = "1.0.1"
4
+ description = "AI building blocks for Wiltech FastAPI apps: Workers AI / Groq / Ollama behind one protocol, OpenAI-compatible tool calling over httpx, embeddings, portable vector stores (database, Vectorize, Qdrant), hybrid-search fusion and a tool-calling agent loop."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.13"
8
+ authors = [{ name = "Wiliam Ferraciolli" }]
9
+ keywords = ["fastapi", "llm", "workers-ai", "groq", "ollama", "embeddings", "vectorize", "qdrant", "rag"]
10
+ classifiers = [
11
+ "Framework :: FastAPI",
12
+ "Programming Language :: Python :: 3",
13
+ "Typing :: Typed",
14
+ ]
15
+ dependencies = [
16
+ "httpx>=0.27",
17
+ "wiltech-labs-core>=0.1.0",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/wilferraciolli/py-libraries/tree/main/packages/ai"
22
+ Repository = "https://github.com/wilferraciolli/py-libraries"
23
+ Conventions = "https://github.com/wilferraciolli/py-libraries/blob/main/docs/PYTHON_APP_CONVENTIONS.md"
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "aiosqlite",
28
+ "pytest",
29
+ "pytest-asyncio",
30
+ ]
31
+
32
+ # In the workspace, use the local core; `uv build` drops this, so the
33
+ # published wheel depends on wiltech-labs-core from PyPI.
34
+ [tool.uv.sources]
35
+ wiltech-labs-core = { workspace = true }
36
+
37
+ [build-system]
38
+ requires = ["hatchling"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ exclude = ["CLAUDE.md", ".pytest_cache"]
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/wiltech_labs_ai"]
46
+
47
+ [tool.pytest.ini_options]
48
+ asyncio_mode = "auto"
49
+ testpaths = ["tests"]
@@ -0,0 +1,88 @@
1
+ """
2
+ wiltech-labs-ai: AI building blocks shared by Wiltech's FastAPI apps.
3
+
4
+ Workers AI / Groq / Ollama behind one protocol, OpenAI-compatible tool
5
+ calling over plain httpx, embeddings, portable vector stores (database,
6
+ Vectorize, Qdrant), reciprocal rank fusion for hybrid search, and a
7
+ tool-calling agent loop.
8
+
9
+ This module is the entire public surface — import from `wiltech_labs_ai`,
10
+ not from its sub-packages.
11
+ """
12
+ from wiltech_labs_ai.agents import (
13
+ STEP_LIMIT_ANSWER,
14
+ TOOL_RESULTS_ARE_DATA,
15
+ AgentResult,
16
+ Tool,
17
+ ToolAgent,
18
+ ToolCallRecord,
19
+ ToolHandler,
20
+ )
21
+ from wiltech_labs_ai.embeddings import (
22
+ DEFAULT_EMBEDDING_MODEL,
23
+ MAX_EMBED_CHARS,
24
+ EmbedFn,
25
+ embed,
26
+ embed_openai_compatible,
27
+ get_embedder,
28
+ )
29
+ from wiltech_labs_ai.llm import OpenAICompatibleLlm, ToolLlm, chat_completion, get_tool_llm
30
+ from wiltech_labs_ai.providers import (
31
+ AI,
32
+ AiBindingAdapter,
33
+ AiHttpAdapter,
34
+ ChatProvider,
35
+ GroqAdapter,
36
+ OpenAICompatibleChatAdapter,
37
+ get_ai,
38
+ workers_ai_openai_base_url,
39
+ )
40
+ from wiltech_labs_ai.search import RRF_K, reciprocal_rank_fusion
41
+ from wiltech_labs_ai.vectors import (
42
+ RESOURCE_EMBEDDINGS_TABLE_SQL,
43
+ DatabaseVectorStore,
44
+ QdrantVectorStore,
45
+ VectorizeVectorStore,
46
+ VectorMatch,
47
+ VectorRecord,
48
+ VectorStore,
49
+ normalise,
50
+ )
51
+
52
+ __all__ = [
53
+ "AI",
54
+ "DEFAULT_EMBEDDING_MODEL",
55
+ "MAX_EMBED_CHARS",
56
+ "RESOURCE_EMBEDDINGS_TABLE_SQL",
57
+ "RRF_K",
58
+ "STEP_LIMIT_ANSWER",
59
+ "TOOL_RESULTS_ARE_DATA",
60
+ "AgentResult",
61
+ "AiBindingAdapter",
62
+ "AiHttpAdapter",
63
+ "ChatProvider",
64
+ "DatabaseVectorStore",
65
+ "EmbedFn",
66
+ "GroqAdapter",
67
+ "OpenAICompatibleChatAdapter",
68
+ "OpenAICompatibleLlm",
69
+ "QdrantVectorStore",
70
+ "Tool",
71
+ "ToolAgent",
72
+ "ToolCallRecord",
73
+ "ToolHandler",
74
+ "ToolLlm",
75
+ "VectorMatch",
76
+ "VectorRecord",
77
+ "VectorStore",
78
+ "VectorizeVectorStore",
79
+ "chat_completion",
80
+ "embed",
81
+ "embed_openai_compatible",
82
+ "get_ai",
83
+ "get_embedder",
84
+ "get_tool_llm",
85
+ "normalise",
86
+ "reciprocal_rank_fusion",
87
+ "workers_ai_openai_base_url",
88
+ ]