langchain-halu 0.1.0__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.
- langchain_halu-0.1.0/LICENSE +201 -0
- langchain_halu-0.1.0/PKG-INFO +172 -0
- langchain_halu-0.1.0/README.md +140 -0
- langchain_halu-0.1.0/pyproject.toml +63 -0
- langchain_halu-0.1.0/setup.cfg +4 -0
- langchain_halu-0.1.0/src/langchain_halu/__init__.py +46 -0
- langchain_halu-0.1.0/src/langchain_halu/_common.py +85 -0
- langchain_halu-0.1.0/src/langchain_halu/callbacks.py +117 -0
- langchain_halu-0.1.0/src/langchain_halu/py.typed +0 -0
- langchain_halu-0.1.0/src/langchain_halu/retry.py +81 -0
- langchain_halu-0.1.0/src/langchain_halu/runnables.py +107 -0
- langchain_halu-0.1.0/src/langchain_halu.egg-info/PKG-INFO +172 -0
- langchain_halu-0.1.0/src/langchain_halu.egg-info/SOURCES.txt +15 -0
- langchain_halu-0.1.0/src/langchain_halu.egg-info/dependency_links.txt +1 -0
- langchain_halu-0.1.0/src/langchain_halu.egg-info/requires.txt +5 -0
- langchain_halu-0.1.0/src/langchain_halu.egg-info/top_level.txt +1 -0
- langchain_halu-0.1.0/tests/test_smoke.py +111 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Komplex AI
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-halu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Thin LangChain integration for Komplex AI — a hallucination detector for LLM output (adapts the halu SDK to LCEL).
|
|
5
|
+
Author-email: Komplex AI <support@komplexai.io>
|
|
6
|
+
Maintainer-email: Komplex AI <support@komplexai.io>
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://detector.komplexai.io
|
|
9
|
+
Project-URL: Documentation, https://detector.komplexai.io/guide
|
|
10
|
+
Project-URL: Source, https://github.com/komplexai
|
|
11
|
+
Keywords: langchain,hallucination,hallucination-detection,llm,uncertainty,komplexai,halu,guardrails,runnable,callback
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: halu>=0.1.2
|
|
28
|
+
Requires-Dist: langchain-core>=0.3
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# langchain-halu
|
|
34
|
+
|
|
35
|
+
A thin [LangChain](https://python.langchain.com/) integration for
|
|
36
|
+
[**Komplex AI**](https://detector.komplexai.io) — a hallucination detector for
|
|
37
|
+
LLM output. It adapts the [`halu`](https://pypi.org/project/halu/) Python SDK to
|
|
38
|
+
LangChain so you can annotate, guard, monitor, or retry generations from inside
|
|
39
|
+
an LCEL pipeline.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install langchain-halu
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
This pulls in `halu` and `langchain-core` (not the full `langchain`).
|
|
48
|
+
|
|
49
|
+
Set your API key in the environment:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
export HALU_API_KEY="sk-..."
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Get a key at <https://detector.komplexai.io>.
|
|
56
|
+
|
|
57
|
+
## Three patterns
|
|
58
|
+
|
|
59
|
+
### 1. Annotate (non-blocking)
|
|
60
|
+
|
|
61
|
+
Enrich an answer with a verdict; the answer always passes through.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
65
|
+
from langchain_openai import ChatOpenAI # any LangChain chat model works
|
|
66
|
+
from langchain_halu import halu_annotate
|
|
67
|
+
|
|
68
|
+
llm = ChatOpenAI(model="gpt-4o-mini")
|
|
69
|
+
chain = llm | StrOutputParser() | halu_annotate()
|
|
70
|
+
|
|
71
|
+
result = chain.invoke("Who painted the Mona Lisa?")
|
|
72
|
+
# {
|
|
73
|
+
# "answer": "Leonardo da Vinci painted the Mona Lisa.",
|
|
74
|
+
# "p_hallucination": 0.02,
|
|
75
|
+
# "flag": False,
|
|
76
|
+
# "top_regime": "NORMAL",
|
|
77
|
+
# }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### 2. Guard (blocking)
|
|
81
|
+
|
|
82
|
+
Reject flagged answers so they never reach the user.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
86
|
+
from langchain_halu import halu_guard, HaluHallucinationFlagged
|
|
87
|
+
|
|
88
|
+
chain = llm | StrOutputParser() | halu_guard(threshold=0.5)
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
answer = chain.invoke("Summarize the plot of a book that does not exist.")
|
|
92
|
+
except HaluHallucinationFlagged as exc:
|
|
93
|
+
result = exc.detection_result
|
|
94
|
+
print(f"Blocked (p={result.p_hallucination:.2f}, regime={result.top_regime})")
|
|
95
|
+
answer = "Sorry, I couldn't produce a reliable answer."
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 3. Monitor (passive callback)
|
|
99
|
+
|
|
100
|
+
Observe every completion and log flagged answers, without changing behavior.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from langchain_halu import HaluCallbackHandler
|
|
104
|
+
|
|
105
|
+
monitor = HaluCallbackHandler(threshold=0.5)
|
|
106
|
+
llm.invoke("What year did the Great Fire of London happen?", config={"callbacks": [monitor]})
|
|
107
|
+
|
|
108
|
+
if monitor.last_result and monitor.last_result.flag:
|
|
109
|
+
print("Flagged:", monitor.last_result.top_regime)
|
|
110
|
+
# monitor.flagged_results holds every flagged DetectResult seen so far.
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Bonus: Retry until clean
|
|
114
|
+
|
|
115
|
+
Regenerate with regime feedback until the answer passes the detector.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
119
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
120
|
+
from langchain_halu import generate_clean
|
|
121
|
+
|
|
122
|
+
prompt = ChatPromptTemplate.from_template("{input}")
|
|
123
|
+
chain = prompt | llm | StrOutputParser()
|
|
124
|
+
|
|
125
|
+
answer = generate_clean(
|
|
126
|
+
chain,
|
|
127
|
+
prompt="Who discovered penicillin, and in what year?",
|
|
128
|
+
max_retries=2,
|
|
129
|
+
threshold=0.5,
|
|
130
|
+
)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`generate_clean` accepts any LangChain `Runnable` (anything with `.invoke`) or a
|
|
134
|
+
plain callable that takes a prompt string and returns text or an
|
|
135
|
+
`AIMessage`-like object.
|
|
136
|
+
|
|
137
|
+
## API
|
|
138
|
+
|
|
139
|
+
| Name | Kind | Purpose |
|
|
140
|
+
|------|------|---------|
|
|
141
|
+
| `halu_annotate(prompt=None)` | `Runnable` factory | Return `{"answer", "p_hallucination", "flag", "top_regime"}` |
|
|
142
|
+
| `halu_guard(threshold=0.5, prompt=None)` | `Runnable` factory | Pass the answer through or raise `HaluHallucinationFlagged` |
|
|
143
|
+
| `HaluCallbackHandler(threshold=0.5, prompt=None, log_level=WARNING)` | Callback | Detect on `on_llm_end`, log + store flagged results |
|
|
144
|
+
| `generate_clean(chain_or_callable, prompt, max_retries=2, threshold=0.5)` | Function | Retry generation until clean |
|
|
145
|
+
|
|
146
|
+
`DetectResult`, `HaluError`, and `HaluHallucinationFlagged` are re-exported from
|
|
147
|
+
`halu` for convenience.
|
|
148
|
+
|
|
149
|
+
## Configuration
|
|
150
|
+
|
|
151
|
+
Detection reads `HALU_API_KEY` from the environment by default and talks to
|
|
152
|
+
`https://api.komplexai.io`. All the standard `halu` options (`api_key`,
|
|
153
|
+
`base_url`, `timeout`) are honored through `halu`'s own configuration; see the
|
|
154
|
+
[`halu` docs](https://pypi.org/project/halu/).
|
|
155
|
+
|
|
156
|
+
## Scope & limits
|
|
157
|
+
|
|
158
|
+
The detector is optimized for a specific slice, and results outside it are not
|
|
159
|
+
reliable:
|
|
160
|
+
|
|
161
|
+
- **English, natural-language** responses only.
|
|
162
|
+
- Responses up to **2048 characters**.
|
|
163
|
+
- The **first call after an idle period can cold-start for ~10–30 s**; subsequent
|
|
164
|
+
calls are fast. Build a warm-up call into latency-sensitive apps.
|
|
165
|
+
- Regimes reported: `NORMAL`, `FABRICATED`, `NEAR_FALSE`, `CF_AUTH` (fake or
|
|
166
|
+
misattributed citation), `FALSE_REFUSAL`, `Other`.
|
|
167
|
+
|
|
168
|
+
Full guidance and best practices: <https://detector.komplexai.io/guide>.
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# langchain-halu
|
|
2
|
+
|
|
3
|
+
A thin [LangChain](https://python.langchain.com/) integration for
|
|
4
|
+
[**Komplex AI**](https://detector.komplexai.io) — a hallucination detector for
|
|
5
|
+
LLM output. It adapts the [`halu`](https://pypi.org/project/halu/) Python SDK to
|
|
6
|
+
LangChain so you can annotate, guard, monitor, or retry generations from inside
|
|
7
|
+
an LCEL pipeline.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install langchain-halu
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This pulls in `halu` and `langchain-core` (not the full `langchain`).
|
|
16
|
+
|
|
17
|
+
Set your API key in the environment:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
export HALU_API_KEY="sk-..."
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Get a key at <https://detector.komplexai.io>.
|
|
24
|
+
|
|
25
|
+
## Three patterns
|
|
26
|
+
|
|
27
|
+
### 1. Annotate (non-blocking)
|
|
28
|
+
|
|
29
|
+
Enrich an answer with a verdict; the answer always passes through.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
33
|
+
from langchain_openai import ChatOpenAI # any LangChain chat model works
|
|
34
|
+
from langchain_halu import halu_annotate
|
|
35
|
+
|
|
36
|
+
llm = ChatOpenAI(model="gpt-4o-mini")
|
|
37
|
+
chain = llm | StrOutputParser() | halu_annotate()
|
|
38
|
+
|
|
39
|
+
result = chain.invoke("Who painted the Mona Lisa?")
|
|
40
|
+
# {
|
|
41
|
+
# "answer": "Leonardo da Vinci painted the Mona Lisa.",
|
|
42
|
+
# "p_hallucination": 0.02,
|
|
43
|
+
# "flag": False,
|
|
44
|
+
# "top_regime": "NORMAL",
|
|
45
|
+
# }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### 2. Guard (blocking)
|
|
49
|
+
|
|
50
|
+
Reject flagged answers so they never reach the user.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
54
|
+
from langchain_halu import halu_guard, HaluHallucinationFlagged
|
|
55
|
+
|
|
56
|
+
chain = llm | StrOutputParser() | halu_guard(threshold=0.5)
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
answer = chain.invoke("Summarize the plot of a book that does not exist.")
|
|
60
|
+
except HaluHallucinationFlagged as exc:
|
|
61
|
+
result = exc.detection_result
|
|
62
|
+
print(f"Blocked (p={result.p_hallucination:.2f}, regime={result.top_regime})")
|
|
63
|
+
answer = "Sorry, I couldn't produce a reliable answer."
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 3. Monitor (passive callback)
|
|
67
|
+
|
|
68
|
+
Observe every completion and log flagged answers, without changing behavior.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from langchain_halu import HaluCallbackHandler
|
|
72
|
+
|
|
73
|
+
monitor = HaluCallbackHandler(threshold=0.5)
|
|
74
|
+
llm.invoke("What year did the Great Fire of London happen?", config={"callbacks": [monitor]})
|
|
75
|
+
|
|
76
|
+
if monitor.last_result and monitor.last_result.flag:
|
|
77
|
+
print("Flagged:", monitor.last_result.top_regime)
|
|
78
|
+
# monitor.flagged_results holds every flagged DetectResult seen so far.
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Bonus: Retry until clean
|
|
82
|
+
|
|
83
|
+
Regenerate with regime feedback until the answer passes the detector.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
87
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
88
|
+
from langchain_halu import generate_clean
|
|
89
|
+
|
|
90
|
+
prompt = ChatPromptTemplate.from_template("{input}")
|
|
91
|
+
chain = prompt | llm | StrOutputParser()
|
|
92
|
+
|
|
93
|
+
answer = generate_clean(
|
|
94
|
+
chain,
|
|
95
|
+
prompt="Who discovered penicillin, and in what year?",
|
|
96
|
+
max_retries=2,
|
|
97
|
+
threshold=0.5,
|
|
98
|
+
)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`generate_clean` accepts any LangChain `Runnable` (anything with `.invoke`) or a
|
|
102
|
+
plain callable that takes a prompt string and returns text or an
|
|
103
|
+
`AIMessage`-like object.
|
|
104
|
+
|
|
105
|
+
## API
|
|
106
|
+
|
|
107
|
+
| Name | Kind | Purpose |
|
|
108
|
+
|------|------|---------|
|
|
109
|
+
| `halu_annotate(prompt=None)` | `Runnable` factory | Return `{"answer", "p_hallucination", "flag", "top_regime"}` |
|
|
110
|
+
| `halu_guard(threshold=0.5, prompt=None)` | `Runnable` factory | Pass the answer through or raise `HaluHallucinationFlagged` |
|
|
111
|
+
| `HaluCallbackHandler(threshold=0.5, prompt=None, log_level=WARNING)` | Callback | Detect on `on_llm_end`, log + store flagged results |
|
|
112
|
+
| `generate_clean(chain_or_callable, prompt, max_retries=2, threshold=0.5)` | Function | Retry generation until clean |
|
|
113
|
+
|
|
114
|
+
`DetectResult`, `HaluError`, and `HaluHallucinationFlagged` are re-exported from
|
|
115
|
+
`halu` for convenience.
|
|
116
|
+
|
|
117
|
+
## Configuration
|
|
118
|
+
|
|
119
|
+
Detection reads `HALU_API_KEY` from the environment by default and talks to
|
|
120
|
+
`https://api.komplexai.io`. All the standard `halu` options (`api_key`,
|
|
121
|
+
`base_url`, `timeout`) are honored through `halu`'s own configuration; see the
|
|
122
|
+
[`halu` docs](https://pypi.org/project/halu/).
|
|
123
|
+
|
|
124
|
+
## Scope & limits
|
|
125
|
+
|
|
126
|
+
The detector is optimized for a specific slice, and results outside it are not
|
|
127
|
+
reliable:
|
|
128
|
+
|
|
129
|
+
- **English, natural-language** responses only.
|
|
130
|
+
- Responses up to **2048 characters**.
|
|
131
|
+
- The **first call after an idle period can cold-start for ~10–30 s**; subsequent
|
|
132
|
+
calls are fast. Build a warm-up call into latency-sensitive apps.
|
|
133
|
+
- Regimes reported: `NORMAL`, `FABRICATED`, `NEAR_FALSE`, `CF_AUTH` (fake or
|
|
134
|
+
misattributed citation), `FALSE_REFUSAL`, `Other`.
|
|
135
|
+
|
|
136
|
+
Full guidance and best practices: <https://detector.komplexai.io/guide>.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-halu"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Thin LangChain integration for Komplex AI — a hallucination detector for LLM output (adapts the halu SDK to LCEL)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Komplex AI", email = "support@komplexai.io" },
|
|
14
|
+
]
|
|
15
|
+
maintainers = [
|
|
16
|
+
{ name = "Komplex AI", email = "support@komplexai.io" },
|
|
17
|
+
]
|
|
18
|
+
keywords = [
|
|
19
|
+
"langchain",
|
|
20
|
+
"hallucination",
|
|
21
|
+
"hallucination-detection",
|
|
22
|
+
"llm",
|
|
23
|
+
"uncertainty",
|
|
24
|
+
"komplexai",
|
|
25
|
+
"halu",
|
|
26
|
+
"guardrails",
|
|
27
|
+
"runnable",
|
|
28
|
+
"callback",
|
|
29
|
+
]
|
|
30
|
+
classifiers = [
|
|
31
|
+
"Development Status :: 4 - Beta",
|
|
32
|
+
"Intended Audience :: Developers",
|
|
33
|
+
"License :: OSI Approved :: Apache Software License",
|
|
34
|
+
"Programming Language :: Python :: 3",
|
|
35
|
+
"Programming Language :: Python :: 3.9",
|
|
36
|
+
"Programming Language :: Python :: 3.10",
|
|
37
|
+
"Programming Language :: Python :: 3.11",
|
|
38
|
+
"Programming Language :: Python :: 3.12",
|
|
39
|
+
"Programming Language :: Python :: 3.13",
|
|
40
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
41
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
42
|
+
"Typing :: Typed",
|
|
43
|
+
]
|
|
44
|
+
dependencies = [
|
|
45
|
+
"halu>=0.1.2",
|
|
46
|
+
"langchain-core>=0.3",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[project.urls]
|
|
50
|
+
Homepage = "https://detector.komplexai.io"
|
|
51
|
+
Documentation = "https://detector.komplexai.io/guide"
|
|
52
|
+
Source = "https://github.com/komplexai"
|
|
53
|
+
|
|
54
|
+
[project.optional-dependencies]
|
|
55
|
+
test = [
|
|
56
|
+
"pytest>=7.0",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.packages.find]
|
|
60
|
+
where = ["src"]
|
|
61
|
+
|
|
62
|
+
[tool.setuptools.package-data]
|
|
63
|
+
langchain_halu = ["py.typed"]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""langchain-halu: a thin LangChain integration for Komplex AI — a hallucination detector for LLM output.
|
|
2
|
+
|
|
3
|
+
This package adapts the ``halu`` SDK (Komplex AI's hallucination detector) to
|
|
4
|
+
LangChain, exposing three complementary patterns:
|
|
5
|
+
|
|
6
|
+
* :func:`halu_annotate` -- a Runnable that enriches an answer with a verdict
|
|
7
|
+
(non-blocking "annotate").
|
|
8
|
+
* :func:`halu_guard` -- a Runnable that passes clean answers through and raises
|
|
9
|
+
on flagged ones (blocking "guard").
|
|
10
|
+
* :class:`HaluCallbackHandler` -- a callback that passively monitors LLM
|
|
11
|
+
completions and logs flagged answers (observability "monitor").
|
|
12
|
+
* :func:`generate_clean` -- regenerate an answer until it passes the detector
|
|
13
|
+
(the "retry" pattern).
|
|
14
|
+
|
|
15
|
+
The ``halu`` error and result types are re-exported for convenience so callers
|
|
16
|
+
do not need a separate ``import halu`` just to catch a flagged answer.
|
|
17
|
+
|
|
18
|
+
Set ``HALU_API_KEY`` in the environment (or pass ``api_key`` through ``halu``)
|
|
19
|
+
before use. See https://detector.komplexai.io/guide for details and limits.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from halu import (
|
|
25
|
+
DetectResult,
|
|
26
|
+
HaluError,
|
|
27
|
+
HaluHallucinationFlagged,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
from .callbacks import HaluCallbackHandler
|
|
31
|
+
from .retry import generate_clean
|
|
32
|
+
from .runnables import halu_annotate, halu_guard
|
|
33
|
+
|
|
34
|
+
__version__ = "0.1.0"
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"halu_annotate",
|
|
38
|
+
"halu_guard",
|
|
39
|
+
"HaluCallbackHandler",
|
|
40
|
+
"generate_clean",
|
|
41
|
+
# Re-exported from halu for convenience.
|
|
42
|
+
"DetectResult",
|
|
43
|
+
"HaluError",
|
|
44
|
+
"HaluHallucinationFlagged",
|
|
45
|
+
"__version__",
|
|
46
|
+
]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Shared helpers for the langchain-halu integration.
|
|
2
|
+
|
|
3
|
+
This module isolates the small amount of glue logic used across the
|
|
4
|
+
Runnable factories, the callback handler, and the retry helper: importing
|
|
5
|
+
``langchain_core`` with a friendly error, and normalizing the many shapes a
|
|
6
|
+
LangChain LLM step can hand us into a plain string.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def require_langchain_core() -> None:
|
|
15
|
+
"""Raise a clear, actionable error if ``langchain-core`` is not installed.
|
|
16
|
+
|
|
17
|
+
``langchain-core`` is a declared dependency, but users occasionally end up
|
|
18
|
+
with a broken environment (e.g. after a partial install). Surfacing a
|
|
19
|
+
targeted message beats a bare ``ModuleNotFoundError`` from deep in an
|
|
20
|
+
import chain.
|
|
21
|
+
"""
|
|
22
|
+
try:
|
|
23
|
+
import langchain_core # noqa: F401
|
|
24
|
+
except ImportError as exc: # pragma: no cover - environment-dependent
|
|
25
|
+
raise ImportError(
|
|
26
|
+
"langchain-halu requires 'langchain-core' (>=0.3). "
|
|
27
|
+
"Install it with `pip install langchain-core` "
|
|
28
|
+
"or `pip install langchain-halu`."
|
|
29
|
+
) from exc
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def to_text(output: Any) -> str:
|
|
33
|
+
"""Normalize a LangChain LLM/chain output into a plain string.
|
|
34
|
+
|
|
35
|
+
Handles the common shapes seen at the tail of a LangChain pipeline:
|
|
36
|
+
|
|
37
|
+
* a plain ``str`` (e.g. from ``StrOutputParser``);
|
|
38
|
+
* a message-like object exposing ``.content`` (e.g. ``AIMessage``),
|
|
39
|
+
whose content may itself be a string or a list of content blocks;
|
|
40
|
+
* anything else, which is coerced with ``str()`` as a last resort.
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
output:
|
|
45
|
+
The value produced by an upstream LLM or chain step.
|
|
46
|
+
|
|
47
|
+
Returns
|
|
48
|
+
-------
|
|
49
|
+
str
|
|
50
|
+
The best-effort text representation of ``output``.
|
|
51
|
+
"""
|
|
52
|
+
if isinstance(output, str):
|
|
53
|
+
return output
|
|
54
|
+
|
|
55
|
+
content = getattr(output, "content", None)
|
|
56
|
+
if content is not None:
|
|
57
|
+
return _content_to_text(content)
|
|
58
|
+
|
|
59
|
+
return str(output)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _content_to_text(content: Any) -> str:
|
|
63
|
+
"""Flatten a message ``.content`` payload into a string.
|
|
64
|
+
|
|
65
|
+
Modern LangChain messages may carry ``content`` as a list of content
|
|
66
|
+
blocks (dicts with a ``"text"`` key, or already-plain strings) instead of
|
|
67
|
+
a single string. We concatenate the textual parts and ignore non-text
|
|
68
|
+
blocks (e.g. images/tool calls), which are not meaningful to a
|
|
69
|
+
natural-language hallucination detector.
|
|
70
|
+
"""
|
|
71
|
+
if isinstance(content, str):
|
|
72
|
+
return content
|
|
73
|
+
|
|
74
|
+
if isinstance(content, (list, tuple)):
|
|
75
|
+
parts = []
|
|
76
|
+
for block in content:
|
|
77
|
+
if isinstance(block, str):
|
|
78
|
+
parts.append(block)
|
|
79
|
+
elif isinstance(block, dict):
|
|
80
|
+
text = block.get("text")
|
|
81
|
+
if isinstance(text, str):
|
|
82
|
+
parts.append(text)
|
|
83
|
+
return "".join(parts)
|
|
84
|
+
|
|
85
|
+
return str(content)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""LangChain callback handler for passive hallucination monitoring.
|
|
2
|
+
|
|
3
|
+
``HaluCallbackHandler`` observes LLM completions as they finish and runs the
|
|
4
|
+
Komplex AI detector on each one, logging a warning (and stashing the last
|
|
5
|
+
result) whenever an answer is flagged. It never blocks or alters generation —
|
|
6
|
+
this is the "monitor" pattern, meant for observability, dashboards, and alerts.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Any, List, Optional
|
|
13
|
+
|
|
14
|
+
import halu
|
|
15
|
+
|
|
16
|
+
from ._common import require_langchain_core
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger("langchain_halu")
|
|
19
|
+
|
|
20
|
+
require_langchain_core()
|
|
21
|
+
from langchain_core.callbacks import BaseCallbackHandler # noqa: E402
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class HaluCallbackHandler(BaseCallbackHandler):
|
|
25
|
+
"""Run hallucination detection on every LLM completion, passively.
|
|
26
|
+
|
|
27
|
+
On ``on_llm_end`` the handler extracts each generated text, runs
|
|
28
|
+
``halu.detect`` on it, and — when the result is flagged — emits a warning
|
|
29
|
+
log record and stores the result. Generation is never interrupted; use
|
|
30
|
+
:func:`langchain_halu.halu_guard` if you need to block flagged answers.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
threshold:
|
|
35
|
+
Probability at or above which a warning is logged. The detector's own
|
|
36
|
+
``.flag`` is authoritative for the flagged/monitor decision; this
|
|
37
|
+
threshold is used as an additional gate so callers can tighten
|
|
38
|
+
sensitivity without changing the SDK default. Defaults to 0.5.
|
|
39
|
+
prompt:
|
|
40
|
+
Optional static prompt/context passed to the detector for every call.
|
|
41
|
+
Most callers leave this ``None`` and rely on response-only detection,
|
|
42
|
+
since the callback does not receive the original prompt text.
|
|
43
|
+
log_level:
|
|
44
|
+
Logging level used for flagged answers. Defaults to ``logging.WARNING``.
|
|
45
|
+
|
|
46
|
+
Attributes
|
|
47
|
+
----------
|
|
48
|
+
last_result:
|
|
49
|
+
The most recent :class:`halu.DetectResult`, or ``None`` if no
|
|
50
|
+
completion has been processed yet.
|
|
51
|
+
flagged_results:
|
|
52
|
+
A list of all flagged :class:`halu.DetectResult` objects seen so far.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
threshold: float = 0.5,
|
|
58
|
+
prompt: Optional[str] = None,
|
|
59
|
+
log_level: int = logging.WARNING,
|
|
60
|
+
) -> None:
|
|
61
|
+
super().__init__()
|
|
62
|
+
self.threshold = threshold
|
|
63
|
+
self.prompt = prompt
|
|
64
|
+
self.log_level = log_level
|
|
65
|
+
self.last_result: Optional["halu.DetectResult"] = None
|
|
66
|
+
self.flagged_results: List["halu.DetectResult"] = []
|
|
67
|
+
|
|
68
|
+
def on_llm_end(self, response: Any, **kwargs: Any) -> None:
|
|
69
|
+
"""Detect on each generated text when an LLM run completes.
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
response:
|
|
74
|
+
A LangChain ``LLMResult``-like object exposing ``.generations``
|
|
75
|
+
(a list of lists of generation objects, each with ``.text``).
|
|
76
|
+
"""
|
|
77
|
+
for text in self._iter_texts(response):
|
|
78
|
+
if not text:
|
|
79
|
+
continue
|
|
80
|
+
try:
|
|
81
|
+
result = halu.detect(text, prompt=self.prompt)
|
|
82
|
+
except halu.HaluError as exc:
|
|
83
|
+
# Monitoring must never break the host application; log and move on.
|
|
84
|
+
logger.warning("langchain-halu: detection failed: %s", exc)
|
|
85
|
+
continue
|
|
86
|
+
|
|
87
|
+
self.last_result = result
|
|
88
|
+
if result.flag or result.p_hallucination >= self.threshold:
|
|
89
|
+
self.flagged_results.append(result)
|
|
90
|
+
logger.log(
|
|
91
|
+
self.log_level,
|
|
92
|
+
"langchain-halu: possible hallucination flagged "
|
|
93
|
+
"(p=%.3f, top_regime=%s, request_id=%s)",
|
|
94
|
+
result.p_hallucination,
|
|
95
|
+
result.top_regime,
|
|
96
|
+
result.request_id,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def _iter_texts(response: Any) -> List[str]:
|
|
101
|
+
"""Best-effort extraction of generated texts from an ``LLMResult``."""
|
|
102
|
+
texts: List[str] = []
|
|
103
|
+
generations = getattr(response, "generations", None)
|
|
104
|
+
if not generations:
|
|
105
|
+
return texts
|
|
106
|
+
for batch in generations:
|
|
107
|
+
for generation in batch:
|
|
108
|
+
text = getattr(generation, "text", None)
|
|
109
|
+
if isinstance(text, str) and text:
|
|
110
|
+
texts.append(text)
|
|
111
|
+
continue
|
|
112
|
+
# Chat generations may carry the text on a nested message.
|
|
113
|
+
message = getattr(generation, "message", None)
|
|
114
|
+
content = getattr(message, "content", None)
|
|
115
|
+
if isinstance(content, str) and content:
|
|
116
|
+
texts.append(content)
|
|
117
|
+
return texts
|
|
File without changes
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Retry helper: regenerate an answer until the detector considers it clean.
|
|
2
|
+
|
|
3
|
+
This wraps ``halu.regenerate_until_clean`` so it can drive a LangChain chain or
|
|
4
|
+
any plain callable. It is the "retry" pattern: ask the model, check the answer,
|
|
5
|
+
and if it is flagged, ask again with feedback about the failing regime, up to a
|
|
6
|
+
bounded number of attempts.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Callable, Union
|
|
12
|
+
|
|
13
|
+
import halu
|
|
14
|
+
|
|
15
|
+
from ._common import to_text
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def generate_clean(
|
|
19
|
+
chain_or_callable: Union[Callable[[str], Any], Any],
|
|
20
|
+
prompt: str,
|
|
21
|
+
max_retries: int = 2,
|
|
22
|
+
threshold: float = 0.5,
|
|
23
|
+
) -> Any:
|
|
24
|
+
"""Generate an answer and retry until it passes the detector.
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
chain_or_callable:
|
|
29
|
+
Either a LangChain ``Runnable`` (anything exposing ``.invoke``) or a
|
|
30
|
+
plain callable. It is called with a single string argument (the prompt,
|
|
31
|
+
possibly augmented with regeneration feedback) and is expected to
|
|
32
|
+
return an answer as a ``str`` or an ``AIMessage``-like object.
|
|
33
|
+
prompt:
|
|
34
|
+
The prompt/question to send to the model. Also passed to the detector
|
|
35
|
+
as context to improve detection quality.
|
|
36
|
+
max_retries:
|
|
37
|
+
Maximum number of regeneration attempts after the first try.
|
|
38
|
+
Defaults to 2.
|
|
39
|
+
threshold:
|
|
40
|
+
Acceptance threshold; an answer with ``p_hallucination`` below this is
|
|
41
|
+
accepted. Defaults to 0.5.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
Any
|
|
46
|
+
Whatever ``halu.regenerate_until_clean`` returns — typically the
|
|
47
|
+
accepted answer text (see the ``halu`` documentation for the exact
|
|
48
|
+
shape and behavior when no clean answer is found within the retry
|
|
49
|
+
budget).
|
|
50
|
+
|
|
51
|
+
Notes
|
|
52
|
+
-----
|
|
53
|
+
The underlying ``ask`` callback normalizes chain output to text via
|
|
54
|
+
:func:`langchain_halu._common.to_text`, so both string-returning and
|
|
55
|
+
message-returning chains work.
|
|
56
|
+
|
|
57
|
+
Examples
|
|
58
|
+
--------
|
|
59
|
+
>>> chain = prompt_template | llm # doctest: +SKIP
|
|
60
|
+
>>> answer = generate_clean(chain, "Who discovered penicillin?") # doctest: +SKIP
|
|
61
|
+
"""
|
|
62
|
+
if hasattr(chain_or_callable, "invoke"):
|
|
63
|
+
invoke = chain_or_callable.invoke
|
|
64
|
+
elif callable(chain_or_callable):
|
|
65
|
+
invoke = chain_or_callable
|
|
66
|
+
else: # pragma: no cover - defensive
|
|
67
|
+
raise TypeError(
|
|
68
|
+
"chain_or_callable must be a LangChain Runnable (with .invoke) "
|
|
69
|
+
"or a callable."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def ask(augmented_prompt: str) -> str:
|
|
73
|
+
return to_text(invoke(augmented_prompt))
|
|
74
|
+
|
|
75
|
+
return halu.regenerate_until_clean(
|
|
76
|
+
ask,
|
|
77
|
+
prompt=prompt,
|
|
78
|
+
max_retries=max_retries,
|
|
79
|
+
acceptance_threshold=threshold,
|
|
80
|
+
feedback_detail="regime",
|
|
81
|
+
)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""LangChain ``Runnable`` factories for the Komplex AI hallucination detector.
|
|
2
|
+
|
|
3
|
+
These are thin adapters over ``halu.detect``. They accept whatever an upstream
|
|
4
|
+
LLM/chain step emits (a ``str`` or an ``AIMessage``-like object) and plug into a
|
|
5
|
+
LangChain Expression Language (LCEL) pipeline via the ``|`` operator.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Dict, Optional
|
|
11
|
+
|
|
12
|
+
import halu
|
|
13
|
+
|
|
14
|
+
from ._common import require_langchain_core, to_text
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def halu_annotate(prompt: Optional[str] = None) -> "Any":
|
|
18
|
+
"""Build a ``Runnable`` that annotates an LLM answer with a detection verdict.
|
|
19
|
+
|
|
20
|
+
The returned runnable takes an LLM output (a ``str`` or an object with a
|
|
21
|
+
``.content`` attribute, such as ``AIMessage``) and returns a dict::
|
|
22
|
+
|
|
23
|
+
{
|
|
24
|
+
"answer": <the original answer text>,
|
|
25
|
+
"p_hallucination": <float 0-1>,
|
|
26
|
+
"flag": <bool>,
|
|
27
|
+
"top_regime": <str>,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
This is the non-blocking "annotate" pattern: the answer always passes
|
|
31
|
+
through, enriched with the detector's verdict so downstream code (or a
|
|
32
|
+
human) can decide what to do.
|
|
33
|
+
|
|
34
|
+
Parameters
|
|
35
|
+
----------
|
|
36
|
+
prompt:
|
|
37
|
+
Optional prompt/context string passed to ``halu.detect`` to improve
|
|
38
|
+
detection. If ``None``, response-only detection is used.
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
Runnable[Any, Dict[str, Any]]
|
|
43
|
+
A LangChain runnable suitable for use in an LCEL pipeline.
|
|
44
|
+
|
|
45
|
+
Examples
|
|
46
|
+
--------
|
|
47
|
+
>>> from langchain_core.output_parsers import StrOutputParser
|
|
48
|
+
>>> chain = llm | StrOutputParser() | halu_annotate() # doctest: +SKIP
|
|
49
|
+
"""
|
|
50
|
+
require_langchain_core()
|
|
51
|
+
from langchain_core.runnables import RunnableLambda
|
|
52
|
+
|
|
53
|
+
def _annotate(output: Any) -> Dict[str, Any]:
|
|
54
|
+
answer = to_text(output)
|
|
55
|
+
result = halu.detect(answer, prompt=prompt)
|
|
56
|
+
return {
|
|
57
|
+
"answer": answer,
|
|
58
|
+
"p_hallucination": result.p_hallucination,
|
|
59
|
+
"flag": result.flag,
|
|
60
|
+
"top_regime": result.top_regime,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return RunnableLambda(_annotate)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def halu_guard(threshold: float = 0.5, prompt: Optional[str] = None) -> "Any":
|
|
67
|
+
"""Build a ``Runnable`` that gates an LLM answer on the detector's verdict.
|
|
68
|
+
|
|
69
|
+
The returned runnable takes an LLM output (a ``str`` or an object with a
|
|
70
|
+
``.content`` attribute) and either:
|
|
71
|
+
|
|
72
|
+
* returns the answer text unchanged when it is not flagged, or
|
|
73
|
+
* raises :class:`halu.HaluHallucinationFlagged` when the estimated
|
|
74
|
+
probability of hallucination meets or exceeds ``threshold``.
|
|
75
|
+
|
|
76
|
+
This is the blocking "guard" pattern: a flagged answer should not reach the
|
|
77
|
+
end user. Wrap downstream calls in ``try/except halu.HaluHallucinationFlagged``
|
|
78
|
+
to handle the rejection (e.g. show a fallback message or retry).
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
threshold:
|
|
83
|
+
Probability at or above which the answer is rejected. Defaults to 0.5.
|
|
84
|
+
prompt:
|
|
85
|
+
Optional prompt/context string passed to the detector.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
Runnable[Any, str]
|
|
90
|
+
A LangChain runnable that returns the answer text or raises.
|
|
91
|
+
|
|
92
|
+
Examples
|
|
93
|
+
--------
|
|
94
|
+
>>> chain = llm | StrOutputParser() | halu_guard(threshold=0.5) # doctest: +SKIP
|
|
95
|
+
"""
|
|
96
|
+
require_langchain_core()
|
|
97
|
+
from langchain_core.runnables import RunnableLambda
|
|
98
|
+
|
|
99
|
+
def _guard(output: Any) -> str:
|
|
100
|
+
answer = to_text(output)
|
|
101
|
+
# detect_or_raise applies the threshold and raises
|
|
102
|
+
# HaluHallucinationFlagged (with .detection_result) when flagged;
|
|
103
|
+
# it returns the DetectResult otherwise.
|
|
104
|
+
halu.detect_or_raise(answer, threshold=threshold, prompt=prompt)
|
|
105
|
+
return answer
|
|
106
|
+
|
|
107
|
+
return RunnableLambda(_guard)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-halu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Thin LangChain integration for Komplex AI — a hallucination detector for LLM output (adapts the halu SDK to LCEL).
|
|
5
|
+
Author-email: Komplex AI <support@komplexai.io>
|
|
6
|
+
Maintainer-email: Komplex AI <support@komplexai.io>
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://detector.komplexai.io
|
|
9
|
+
Project-URL: Documentation, https://detector.komplexai.io/guide
|
|
10
|
+
Project-URL: Source, https://github.com/komplexai
|
|
11
|
+
Keywords: langchain,hallucination,hallucination-detection,llm,uncertainty,komplexai,halu,guardrails,runnable,callback
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: halu>=0.1.2
|
|
28
|
+
Requires-Dist: langchain-core>=0.3
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# langchain-halu
|
|
34
|
+
|
|
35
|
+
A thin [LangChain](https://python.langchain.com/) integration for
|
|
36
|
+
[**Komplex AI**](https://detector.komplexai.io) — a hallucination detector for
|
|
37
|
+
LLM output. It adapts the [`halu`](https://pypi.org/project/halu/) Python SDK to
|
|
38
|
+
LangChain so you can annotate, guard, monitor, or retry generations from inside
|
|
39
|
+
an LCEL pipeline.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install langchain-halu
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
This pulls in `halu` and `langchain-core` (not the full `langchain`).
|
|
48
|
+
|
|
49
|
+
Set your API key in the environment:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
export HALU_API_KEY="sk-..."
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Get a key at <https://detector.komplexai.io>.
|
|
56
|
+
|
|
57
|
+
## Three patterns
|
|
58
|
+
|
|
59
|
+
### 1. Annotate (non-blocking)
|
|
60
|
+
|
|
61
|
+
Enrich an answer with a verdict; the answer always passes through.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
65
|
+
from langchain_openai import ChatOpenAI # any LangChain chat model works
|
|
66
|
+
from langchain_halu import halu_annotate
|
|
67
|
+
|
|
68
|
+
llm = ChatOpenAI(model="gpt-4o-mini")
|
|
69
|
+
chain = llm | StrOutputParser() | halu_annotate()
|
|
70
|
+
|
|
71
|
+
result = chain.invoke("Who painted the Mona Lisa?")
|
|
72
|
+
# {
|
|
73
|
+
# "answer": "Leonardo da Vinci painted the Mona Lisa.",
|
|
74
|
+
# "p_hallucination": 0.02,
|
|
75
|
+
# "flag": False,
|
|
76
|
+
# "top_regime": "NORMAL",
|
|
77
|
+
# }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### 2. Guard (blocking)
|
|
81
|
+
|
|
82
|
+
Reject flagged answers so they never reach the user.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
86
|
+
from langchain_halu import halu_guard, HaluHallucinationFlagged
|
|
87
|
+
|
|
88
|
+
chain = llm | StrOutputParser() | halu_guard(threshold=0.5)
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
answer = chain.invoke("Summarize the plot of a book that does not exist.")
|
|
92
|
+
except HaluHallucinationFlagged as exc:
|
|
93
|
+
result = exc.detection_result
|
|
94
|
+
print(f"Blocked (p={result.p_hallucination:.2f}, regime={result.top_regime})")
|
|
95
|
+
answer = "Sorry, I couldn't produce a reliable answer."
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 3. Monitor (passive callback)
|
|
99
|
+
|
|
100
|
+
Observe every completion and log flagged answers, without changing behavior.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from langchain_halu import HaluCallbackHandler
|
|
104
|
+
|
|
105
|
+
monitor = HaluCallbackHandler(threshold=0.5)
|
|
106
|
+
llm.invoke("What year did the Great Fire of London happen?", config={"callbacks": [monitor]})
|
|
107
|
+
|
|
108
|
+
if monitor.last_result and monitor.last_result.flag:
|
|
109
|
+
print("Flagged:", monitor.last_result.top_regime)
|
|
110
|
+
# monitor.flagged_results holds every flagged DetectResult seen so far.
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Bonus: Retry until clean
|
|
114
|
+
|
|
115
|
+
Regenerate with regime feedback until the answer passes the detector.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
119
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
120
|
+
from langchain_halu import generate_clean
|
|
121
|
+
|
|
122
|
+
prompt = ChatPromptTemplate.from_template("{input}")
|
|
123
|
+
chain = prompt | llm | StrOutputParser()
|
|
124
|
+
|
|
125
|
+
answer = generate_clean(
|
|
126
|
+
chain,
|
|
127
|
+
prompt="Who discovered penicillin, and in what year?",
|
|
128
|
+
max_retries=2,
|
|
129
|
+
threshold=0.5,
|
|
130
|
+
)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`generate_clean` accepts any LangChain `Runnable` (anything with `.invoke`) or a
|
|
134
|
+
plain callable that takes a prompt string and returns text or an
|
|
135
|
+
`AIMessage`-like object.
|
|
136
|
+
|
|
137
|
+
## API
|
|
138
|
+
|
|
139
|
+
| Name | Kind | Purpose |
|
|
140
|
+
|------|------|---------|
|
|
141
|
+
| `halu_annotate(prompt=None)` | `Runnable` factory | Return `{"answer", "p_hallucination", "flag", "top_regime"}` |
|
|
142
|
+
| `halu_guard(threshold=0.5, prompt=None)` | `Runnable` factory | Pass the answer through or raise `HaluHallucinationFlagged` |
|
|
143
|
+
| `HaluCallbackHandler(threshold=0.5, prompt=None, log_level=WARNING)` | Callback | Detect on `on_llm_end`, log + store flagged results |
|
|
144
|
+
| `generate_clean(chain_or_callable, prompt, max_retries=2, threshold=0.5)` | Function | Retry generation until clean |
|
|
145
|
+
|
|
146
|
+
`DetectResult`, `HaluError`, and `HaluHallucinationFlagged` are re-exported from
|
|
147
|
+
`halu` for convenience.
|
|
148
|
+
|
|
149
|
+
## Configuration
|
|
150
|
+
|
|
151
|
+
Detection reads `HALU_API_KEY` from the environment by default and talks to
|
|
152
|
+
`https://api.komplexai.io`. All the standard `halu` options (`api_key`,
|
|
153
|
+
`base_url`, `timeout`) are honored through `halu`'s own configuration; see the
|
|
154
|
+
[`halu` docs](https://pypi.org/project/halu/).
|
|
155
|
+
|
|
156
|
+
## Scope & limits
|
|
157
|
+
|
|
158
|
+
The detector is optimized for a specific slice, and results outside it are not
|
|
159
|
+
reliable:
|
|
160
|
+
|
|
161
|
+
- **English, natural-language** responses only.
|
|
162
|
+
- Responses up to **2048 characters**.
|
|
163
|
+
- The **first call after an idle period can cold-start for ~10–30 s**; subsequent
|
|
164
|
+
calls are fast. Build a warm-up call into latency-sensitive apps.
|
|
165
|
+
- Regimes reported: `NORMAL`, `FABRICATED`, `NEAR_FALSE`, `CF_AUTH` (fake or
|
|
166
|
+
misattributed citation), `FALSE_REFUSAL`, `Other`.
|
|
167
|
+
|
|
168
|
+
Full guidance and best practices: <https://detector.komplexai.io/guide>.
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/langchain_halu/__init__.py
|
|
5
|
+
src/langchain_halu/_common.py
|
|
6
|
+
src/langchain_halu/callbacks.py
|
|
7
|
+
src/langchain_halu/py.typed
|
|
8
|
+
src/langchain_halu/retry.py
|
|
9
|
+
src/langchain_halu/runnables.py
|
|
10
|
+
src/langchain_halu.egg-info/PKG-INFO
|
|
11
|
+
src/langchain_halu.egg-info/SOURCES.txt
|
|
12
|
+
src/langchain_halu.egg-info/dependency_links.txt
|
|
13
|
+
src/langchain_halu.egg-info/requires.txt
|
|
14
|
+
src/langchain_halu.egg-info/top_level.txt
|
|
15
|
+
tests/test_smoke.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
langchain_halu
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Light smoke tests for langchain-halu.
|
|
2
|
+
|
|
3
|
+
These verify that the package imports and that its runnables, callback handler,
|
|
4
|
+
and retry helper construct correctly without any network access. The single
|
|
5
|
+
live end-to-end test is skipped by default and only runs when
|
|
6
|
+
``HALU_LIVE_TEST=1`` is set in the environment (and a real ``HALU_API_KEY`` is
|
|
7
|
+
available).
|
|
8
|
+
|
|
9
|
+
Run with: ``pytest``
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
|
|
17
|
+
# The package depends on halu and langchain-core; if either is missing from the
|
|
18
|
+
# test environment, skip the whole module rather than error out.
|
|
19
|
+
pytest.importorskip("halu")
|
|
20
|
+
pytest.importorskip("langchain_core")
|
|
21
|
+
|
|
22
|
+
import langchain_halu # noqa: E402
|
|
23
|
+
from langchain_halu._common import to_text # noqa: E402
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _FakeMessage:
|
|
27
|
+
"""Minimal AIMessage-like object exposing ``.content``."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, content):
|
|
30
|
+
self.content = content
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_public_exports():
|
|
34
|
+
for name in (
|
|
35
|
+
"halu_annotate",
|
|
36
|
+
"halu_guard",
|
|
37
|
+
"HaluCallbackHandler",
|
|
38
|
+
"generate_clean",
|
|
39
|
+
"DetectResult",
|
|
40
|
+
"HaluError",
|
|
41
|
+
"HaluHallucinationFlagged",
|
|
42
|
+
):
|
|
43
|
+
assert hasattr(langchain_halu, name), name
|
|
44
|
+
assert langchain_halu.__version__ == "0.1.0"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_to_text_str():
|
|
48
|
+
assert to_text("hello") == "hello"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_to_text_message_content_str():
|
|
52
|
+
assert to_text(_FakeMessage("hi there")) == "hi there"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_to_text_message_content_blocks():
|
|
56
|
+
msg = _FakeMessage([{"type": "text", "text": "a"}, "b", {"image": "x"}])
|
|
57
|
+
assert to_text(msg) == "ab"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_to_text_fallback():
|
|
61
|
+
assert to_text(123) == "123"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_halu_annotate_constructs():
|
|
65
|
+
runnable = langchain_halu.halu_annotate()
|
|
66
|
+
assert hasattr(runnable, "invoke")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_halu_guard_constructs():
|
|
70
|
+
runnable = langchain_halu.halu_guard(threshold=0.7)
|
|
71
|
+
assert hasattr(runnable, "invoke")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_callback_handler_constructs():
|
|
75
|
+
handler = langchain_halu.HaluCallbackHandler(threshold=0.6)
|
|
76
|
+
assert handler.last_result is None
|
|
77
|
+
assert handler.flagged_results == []
|
|
78
|
+
assert handler.threshold == 0.6
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_callback_handler_is_base_callback_handler():
|
|
82
|
+
from langchain_core.callbacks import BaseCallbackHandler
|
|
83
|
+
|
|
84
|
+
assert isinstance(langchain_halu.HaluCallbackHandler(), BaseCallbackHandler)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_callback_iter_texts_empty_response():
|
|
88
|
+
class _EmptyResult:
|
|
89
|
+
generations = []
|
|
90
|
+
|
|
91
|
+
handler = langchain_halu.HaluCallbackHandler()
|
|
92
|
+
# Should not raise and should not call the network on empty generations.
|
|
93
|
+
handler.on_llm_end(_EmptyResult())
|
|
94
|
+
assert handler.last_result is None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_generate_clean_type_error_on_bad_input():
|
|
98
|
+
with pytest.raises(TypeError):
|
|
99
|
+
langchain_halu.generate_clean(object(), "prompt")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.mark.skipif(
|
|
103
|
+
os.environ.get("HALU_LIVE_TEST") != "1",
|
|
104
|
+
reason="live network test; set HALU_LIVE_TEST=1 and HALU_API_KEY to run",
|
|
105
|
+
)
|
|
106
|
+
def test_annotate_live():
|
|
107
|
+
runnable = langchain_halu.halu_annotate()
|
|
108
|
+
out = runnable.invoke("The Eiffel Tower is located in Berlin, Germany.")
|
|
109
|
+
assert set(out) == {"answer", "p_hallucination", "flag", "top_regime"}
|
|
110
|
+
assert 0.0 <= out["p_hallucination"] <= 1.0
|
|
111
|
+
logging.getLogger(__name__).info("live annotate result: %s", out)
|