@anybio/govern 0.0.0 → 0.2.2

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,148 @@
1
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
+ import { BaseMessage, AIMessage } from '@langchain/core/messages';
3
+ import { Serialized } from '@langchain/core/load/serializable';
4
+ import { LLMResult } from '@langchain/core/outputs';
5
+ import { RunnableConfig, Runnable } from '@langchain/core/runnables';
6
+ import { G as Govern, p as GovernOptions, c as Channel, b as Audience, K as InboundMessage, g as Decision, r as GuardResult } from './client-CU46a__g.cjs';
7
+
8
+ /**
9
+ * `@anybio/govern/langchain`: a callback handler that records, and a runnable
10
+ * wrapper that gates.
11
+ *
12
+ * Callbacks in LangChain run beside the chain; by the time `handleLLMEnd`
13
+ * fires the output is already on its way to the caller, so a callback can
14
+ * record a decision but cannot withhold text. `GovernCallbackHandler` is
15
+ * therefore the observe-mode install. `governed(runnable, options)` is the
16
+ * gating path: it invokes the wrapped runnable, evaluates the `AIMessage` (or
17
+ * string) it returns, and returns the hold message in its place when the
18
+ * decision is not allow and `reply.showHoldText` is true, or empty text when
19
+ * it is false (an outbound channel with no holding line owed): the same
20
+ * channel rule as `guard`, see `isInSessionChannel`.
21
+ *
22
+ * Both name the model on every evaluation. `model` is the `model` option, else
23
+ * what the model itself says it is (a chat model's `model` or `modelName`, or
24
+ * the model LangChain passes to callbacks at the start of the run).
25
+ * `modelVersion` is the `modelVersion` option, else the model the provider
26
+ * reported on the response (`response_metadata.model_name`, or `model`), when
27
+ * it reports one.
28
+ */
29
+
30
+ /** The key under `config.configurable` the adapter reads per-call identifiers from. */
31
+ declare const CONFIGURABLE_KEY = "anybioGovern";
32
+ /** The key under `AIMessage.response_metadata` the wrapper writes the decision to. */
33
+ declare const RESPONSE_METADATA_KEY = "anybio_govern";
34
+ interface GovernConfigurable {
35
+ conversationId?: string;
36
+ turnId?: string;
37
+ patientRef?: string;
38
+ metadata?: Record<string, unknown>;
39
+ }
40
+ type Resolvable<T> = T | ((config: RunnableConfig | undefined) => T | undefined);
41
+ interface GovernLangChainOptions {
42
+ /** A `Govern` client, or the options to construct one. */
43
+ govern: Govern | GovernOptions;
44
+ channel: Channel;
45
+ audience: Audience;
46
+ /**
47
+ * Your thread id. A string, a function of the call config, or per call via
48
+ * `config.configurable.anybioGovern.conversationId`; `configurable.thread_id`
49
+ * is read as a last resort. Required by one of those routes.
50
+ */
51
+ conversationId?: Resolvable<string>;
52
+ /** Your message id. Default: `configurable.anybioGovern.turnId`, else the LangChain run id, else a random id. */
53
+ turnId?: Resolvable<string>;
54
+ patientRef?: Resolvable<string>;
55
+ metadata?: Resolvable<Record<string, unknown>>;
56
+ /** The model name recorded on each decision. Default: what the model reports about itself (see the module note). */
57
+ model?: Resolvable<string>;
58
+ /** The model version recorded on each decision. Default: the model the provider reported on the response, when it reports one. */
59
+ modelVersion?: Resolvable<string>;
60
+ inbound?: (config: RunnableConfig | undefined) => InboundMessage | undefined;
61
+ holdMessage?: string;
62
+ /** Called when reporting an outcome fails. */
63
+ onError?: (error: unknown) => void;
64
+ }
65
+ interface GovernedOptions extends GovernLangChainOptions {
66
+ /** Report the outcome as delivered with the text the wrapper returned. Default true. */
67
+ reportOutcome?: boolean;
68
+ /**
69
+ * What to do when the wrapped runnable returns something this adapter cannot
70
+ * read as text: a structured output, a dict, a list.
71
+ *
72
+ * Default `"error"`. A gate that cannot see the output must not imply it
73
+ * approved it, and a structured-output chain is a mainstream shape: passed
74
+ * through in silence, a correctly wired chain would gate nothing.
75
+ * The error is deterministic and arrives on the first call, which is where
76
+ * an integration mistake belongs.
77
+ *
78
+ * `"pass"` returns the output unevaluated for a chain whose text is gated
79
+ * somewhere else. It is still not silent: `onError` is called with the same
80
+ * error.
81
+ */
82
+ ungatedOutput?: "error" | "pass";
83
+ onDecision?: (info: {
84
+ reply: GuardResult;
85
+ conversationId: string;
86
+ turnId: string;
87
+ }) => void;
88
+ }
89
+ interface GovernCallbackHandlerOptions extends GovernLangChainOptions {
90
+ /**
91
+ * Report every recorded decision as delivered. Default false: a callback
92
+ * cannot know what the chain delivered, so leave outcome reporting to the
93
+ * code that sends the message.
94
+ */
95
+ reportOutcome?: boolean;
96
+ onDecision?: (info: {
97
+ decision: Decision;
98
+ runId: string;
99
+ }) => void;
100
+ }
101
+ /**
102
+ * What `governed` returns for a runnable that returns `T`.
103
+ *
104
+ * A string in, a string out. Anything else comes back either as it was (an
105
+ * allow the gate did not touch) or as the `AIMessage` the wrapper writes in
106
+ * its place: the hold message (or empty text, when `showHoldText` is false),
107
+ * plus the decision under
108
+ * `response_metadata.anybio_govern`. The gate has one message class it can
109
+ * construct, so wrapping a runnable whose output is some other `BaseMessage`
110
+ * subclass widens the type by exactly that much rather than pretending the
111
+ * subclass survives the substitution.
112
+ */
113
+ type GovernedOutput<T> = T extends string ? string : T | AIMessage;
114
+ /**
115
+ * Wrap a runnable (a chat model, a chain) so the text it returns is
116
+ * evaluated before the caller sees it. On a hold, string outputs are replaced
117
+ * by `reply.text`; message outputs are replaced by a new `AIMessage` with that
118
+ * text and the decision in `response_metadata.anybio_govern`. `reply.text` is
119
+ * the hold message when `showHoldText` is true (every hold on an in-session
120
+ * channel, an owed holding line on an outbound one) and empty otherwise, so an
121
+ * outbound caller that sends what it gets back sends nothing. An
122
+ * output this adapter cannot read as text is refused, not passed through: see
123
+ * `ungatedOutput`.
124
+ *
125
+ * `stream()` on the returned runnable yields one chunk after the decision:
126
+ * buffer and release, which is the patient-audience rule.
127
+ */
128
+ declare function governed<RunInput, RunOutput>(runnable: Runnable<RunInput, RunOutput>, options: GovernedOptions): Runnable<RunInput, GovernedOutput<RunOutput>>;
129
+ /**
130
+ * Records a decision for every generation an LLM or chat model produces.
131
+ * Cannot withhold output; pair it with observe mode, or use `governed` to
132
+ * gate.
133
+ */
134
+ declare class GovernCallbackHandler extends BaseCallbackHandler {
135
+ name: string;
136
+ private readonly options;
137
+ private readonly govern;
138
+ /** The model each run named at its start, until the run ends. Bounded, for runs that never end. */
139
+ private readonly runModels;
140
+ constructor(options: GovernCallbackHandlerOptions);
141
+ handleLLMStart(_llm: Serialized, _prompts: string[], runId: string, _parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>): void;
142
+ handleChatModelStart(_llm: Serialized, _messages: BaseMessage[][], runId: string, _parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>): void;
143
+ handleLLMError(_error: Error, runId: string): void;
144
+ handleLLMEnd(output: LLMResult, runId: string): Promise<void>;
145
+ private rememberModel;
146
+ }
147
+
148
+ export { CONFIGURABLE_KEY, GovernCallbackHandler, type GovernCallbackHandlerOptions, type GovernConfigurable, type GovernLangChainOptions, type GovernedOptions, type GovernedOutput, RESPONSE_METADATA_KEY, governed };
@@ -0,0 +1,148 @@
1
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
+ import { BaseMessage, AIMessage } from '@langchain/core/messages';
3
+ import { Serialized } from '@langchain/core/load/serializable';
4
+ import { LLMResult } from '@langchain/core/outputs';
5
+ import { RunnableConfig, Runnable } from '@langchain/core/runnables';
6
+ import { G as Govern, p as GovernOptions, c as Channel, b as Audience, K as InboundMessage, g as Decision, r as GuardResult } from './client-CU46a__g.js';
7
+
8
+ /**
9
+ * `@anybio/govern/langchain`: a callback handler that records, and a runnable
10
+ * wrapper that gates.
11
+ *
12
+ * Callbacks in LangChain run beside the chain; by the time `handleLLMEnd`
13
+ * fires the output is already on its way to the caller, so a callback can
14
+ * record a decision but cannot withhold text. `GovernCallbackHandler` is
15
+ * therefore the observe-mode install. `governed(runnable, options)` is the
16
+ * gating path: it invokes the wrapped runnable, evaluates the `AIMessage` (or
17
+ * string) it returns, and returns the hold message in its place when the
18
+ * decision is not allow and `reply.showHoldText` is true, or empty text when
19
+ * it is false (an outbound channel with no holding line owed): the same
20
+ * channel rule as `guard`, see `isInSessionChannel`.
21
+ *
22
+ * Both name the model on every evaluation. `model` is the `model` option, else
23
+ * what the model itself says it is (a chat model's `model` or `modelName`, or
24
+ * the model LangChain passes to callbacks at the start of the run).
25
+ * `modelVersion` is the `modelVersion` option, else the model the provider
26
+ * reported on the response (`response_metadata.model_name`, or `model`), when
27
+ * it reports one.
28
+ */
29
+
30
+ /** The key under `config.configurable` the adapter reads per-call identifiers from. */
31
+ declare const CONFIGURABLE_KEY = "anybioGovern";
32
+ /** The key under `AIMessage.response_metadata` the wrapper writes the decision to. */
33
+ declare const RESPONSE_METADATA_KEY = "anybio_govern";
34
+ interface GovernConfigurable {
35
+ conversationId?: string;
36
+ turnId?: string;
37
+ patientRef?: string;
38
+ metadata?: Record<string, unknown>;
39
+ }
40
+ type Resolvable<T> = T | ((config: RunnableConfig | undefined) => T | undefined);
41
+ interface GovernLangChainOptions {
42
+ /** A `Govern` client, or the options to construct one. */
43
+ govern: Govern | GovernOptions;
44
+ channel: Channel;
45
+ audience: Audience;
46
+ /**
47
+ * Your thread id. A string, a function of the call config, or per call via
48
+ * `config.configurable.anybioGovern.conversationId`; `configurable.thread_id`
49
+ * is read as a last resort. Required by one of those routes.
50
+ */
51
+ conversationId?: Resolvable<string>;
52
+ /** Your message id. Default: `configurable.anybioGovern.turnId`, else the LangChain run id, else a random id. */
53
+ turnId?: Resolvable<string>;
54
+ patientRef?: Resolvable<string>;
55
+ metadata?: Resolvable<Record<string, unknown>>;
56
+ /** The model name recorded on each decision. Default: what the model reports about itself (see the module note). */
57
+ model?: Resolvable<string>;
58
+ /** The model version recorded on each decision. Default: the model the provider reported on the response, when it reports one. */
59
+ modelVersion?: Resolvable<string>;
60
+ inbound?: (config: RunnableConfig | undefined) => InboundMessage | undefined;
61
+ holdMessage?: string;
62
+ /** Called when reporting an outcome fails. */
63
+ onError?: (error: unknown) => void;
64
+ }
65
+ interface GovernedOptions extends GovernLangChainOptions {
66
+ /** Report the outcome as delivered with the text the wrapper returned. Default true. */
67
+ reportOutcome?: boolean;
68
+ /**
69
+ * What to do when the wrapped runnable returns something this adapter cannot
70
+ * read as text: a structured output, a dict, a list.
71
+ *
72
+ * Default `"error"`. A gate that cannot see the output must not imply it
73
+ * approved it, and a structured-output chain is a mainstream shape: passed
74
+ * through in silence, a correctly wired chain would gate nothing.
75
+ * The error is deterministic and arrives on the first call, which is where
76
+ * an integration mistake belongs.
77
+ *
78
+ * `"pass"` returns the output unevaluated for a chain whose text is gated
79
+ * somewhere else. It is still not silent: `onError` is called with the same
80
+ * error.
81
+ */
82
+ ungatedOutput?: "error" | "pass";
83
+ onDecision?: (info: {
84
+ reply: GuardResult;
85
+ conversationId: string;
86
+ turnId: string;
87
+ }) => void;
88
+ }
89
+ interface GovernCallbackHandlerOptions extends GovernLangChainOptions {
90
+ /**
91
+ * Report every recorded decision as delivered. Default false: a callback
92
+ * cannot know what the chain delivered, so leave outcome reporting to the
93
+ * code that sends the message.
94
+ */
95
+ reportOutcome?: boolean;
96
+ onDecision?: (info: {
97
+ decision: Decision;
98
+ runId: string;
99
+ }) => void;
100
+ }
101
+ /**
102
+ * What `governed` returns for a runnable that returns `T`.
103
+ *
104
+ * A string in, a string out. Anything else comes back either as it was (an
105
+ * allow the gate did not touch) or as the `AIMessage` the wrapper writes in
106
+ * its place: the hold message (or empty text, when `showHoldText` is false),
107
+ * plus the decision under
108
+ * `response_metadata.anybio_govern`. The gate has one message class it can
109
+ * construct, so wrapping a runnable whose output is some other `BaseMessage`
110
+ * subclass widens the type by exactly that much rather than pretending the
111
+ * subclass survives the substitution.
112
+ */
113
+ type GovernedOutput<T> = T extends string ? string : T | AIMessage;
114
+ /**
115
+ * Wrap a runnable (a chat model, a chain) so the text it returns is
116
+ * evaluated before the caller sees it. On a hold, string outputs are replaced
117
+ * by `reply.text`; message outputs are replaced by a new `AIMessage` with that
118
+ * text and the decision in `response_metadata.anybio_govern`. `reply.text` is
119
+ * the hold message when `showHoldText` is true (every hold on an in-session
120
+ * channel, an owed holding line on an outbound one) and empty otherwise, so an
121
+ * outbound caller that sends what it gets back sends nothing. An
122
+ * output this adapter cannot read as text is refused, not passed through: see
123
+ * `ungatedOutput`.
124
+ *
125
+ * `stream()` on the returned runnable yields one chunk after the decision:
126
+ * buffer and release, which is the patient-audience rule.
127
+ */
128
+ declare function governed<RunInput, RunOutput>(runnable: Runnable<RunInput, RunOutput>, options: GovernedOptions): Runnable<RunInput, GovernedOutput<RunOutput>>;
129
+ /**
130
+ * Records a decision for every generation an LLM or chat model produces.
131
+ * Cannot withhold output; pair it with observe mode, or use `governed` to
132
+ * gate.
133
+ */
134
+ declare class GovernCallbackHandler extends BaseCallbackHandler {
135
+ name: string;
136
+ private readonly options;
137
+ private readonly govern;
138
+ /** The model each run named at its start, until the run ends. Bounded, for runs that never end. */
139
+ private readonly runModels;
140
+ constructor(options: GovernCallbackHandlerOptions);
141
+ handleLLMStart(_llm: Serialized, _prompts: string[], runId: string, _parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>): void;
142
+ handleChatModelStart(_llm: Serialized, _messages: BaseMessage[][], runId: string, _parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>): void;
143
+ handleLLMError(_error: Error, runId: string): void;
144
+ handleLLMEnd(output: LLMResult, runId: string): Promise<void>;
145
+ private rememberModel;
146
+ }
147
+
148
+ export { CONFIGURABLE_KEY, GovernCallbackHandler, type GovernCallbackHandlerOptions, type GovernConfigurable, type GovernLangChainOptions, type GovernedOptions, type GovernedOutput, RESPONSE_METADATA_KEY, governed };