Metadata-Version: 2.4
Name: langchain-idemcore
Version: 0.1.3
Summary: LangChain chat model for Idemcore, with signed verifiable receipts in response metadata.
Author-email: Don Wick <don.wick@idemcore.net>
License-Expression: Apache-2.0
Project-URL: Homepage, https://idemcore.net/integrations/langchain
Project-URL: Documentation, https://idemcore.net/integrations/langchain
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: idemcore<0.4,>=0.3.0
Requires-Dist: idemcore-verify<0.4,>=0.3.6
Requires-Dist: langchain-core>=0.3.0
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"

# langchain-idemcore

LangChain chat model for the [Idemcore](https://idemcore.net) API. Every answer
comes with a signed, independently verifiable, bit-exact receipt, stored on
`AIMessage.response_metadata`.

Install guide: https://idemcore.net/integrations/langchain

## Install

```bash
pip install langchain-idemcore
export IDEMCORE_API_KEY=ick_...
```

Requires `idemcore>=0.3` (r2 receipts) and `idemcore-verify>=0.3.6`.

## Quickstart

```python
from langchain_core.messages import HumanMessage
from langchain_idemcore import ChatIdemcore, IdemcoreReceiptHandler, verify_langchain_receipt

llm = ChatIdemcore(model="your-model-id", max_tokens=64)
handler = IdemcoreReceiptHandler()

msg = llm.invoke(
    [HumanMessage(content="Name the three primary colours.")],
    config={"callbacks": [handler]},
)
print(msg.content)
print(msg.response_metadata["receipt_id"])   # rcpt_...
print(handler.to_jsonl())

# Local check of the signed receipt (and of a public token log, if you have one):
# bundle = verify_langchain_receipt(msg, log_text=log_text)
# print(bundle.ok, bundle.verification.levels)
```

Streaming works the same way: text arrives in chunks, and the receipt is
attached to a later chunk's `response_metadata` once the answer is complete.
Merging the `AIMessageChunk`s (or using `IdemcoreReceiptHandler`) preserves it.

```python
for chunk in llm.stream([HumanMessage(content="Write one short sentence.")]):
    print(chunk.content, end="")
```

## Tool calling

Since 0.1.3, `bind_tools` sends OpenAI-format tools to every hosted model.
Tool calls come back on `AIMessage.tool_calls`, and every answer, including
one that calls a tool, still carries a signed receipt.

```python
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_idemcore import ChatIdemcore, verify_langchain_receipt

@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return '{"city": "Hanoi", "temp_c": 24, "condition": "light rain"}'

llm = ChatIdemcore(model="qwen3.6-35b-a3b-idna", max_tokens=128).bind_tools([get_weather])
history = [HumanMessage(content="What is the weather in Hanoi right now?")]
ai = llm.invoke(history)
print(ai.tool_calls)  # [{'name': 'get_weather', 'args': {'city': 'Hanoi'}, 'id': 'call_…', ...}]

history += [ai, ToolMessage(content=get_weather.invoke(ai.tool_calls[0]["args"]),
                            tool_call_id=ai.tool_calls[0]["id"])]
final = llm.invoke(history)
print(final.content)
print(verify_langchain_receipt(final).ok)  # True
```

- `tool_choice` accepts `"auto"`, `"none"`, `"required"` (`"any"` or `True`
  mean the same) or a tool name.
- Streaming yields `tool_call_chunks`; merged chunks give `tool_calls`, and the
  receipt arrives on the last chunk.
- A call whose arguments are not valid JSON lands in `invalid_tool_calls`.
- In `auto` mode a model may occasionally answer a live-data question itself
  instead of calling your tool. Use `tool_choice="required"` (or the tool
  name) when a call must happen.

## Receipt metadata

`AIMessage.response_metadata` (and `ChatResult.llm_output`) contains:

- `receipt_id`, `receipt` (the full signed r2 receipt)
- `salt` (for `hash_only` receipts; store it with the conversation)
- `privacy`, `model`, `finish_reason`, `id`, `usage`
- for requests sent with tools: `prompt_messages` (the exact prompt the model
  saw, with the tool definitions) and `output_token_ids`; the verify helper
  uses them automatically

`IdemcoreReceiptHandler` collects those payloads for a whole run and can write
them as JSONL.

`verify_langchain_receipt` runs `idemcore.verify_receipt` (signature, optional
token-log chain, optional prompt/answer commitments). When `log_text` is
given it also runs the open `idemcore-verify` log check.

## Sampling

Idemcore decoding is greedy: **temperature is fixed at 0**. Passing any other
temperature, or sampling settings such as `top_p`, `top_k`, penalties, `seed`,
`n`, or stop sequences, raises an error before a request is made. The legacy
`functions` / `function_call` API is not supported; use `bind_tools`.

`max_tokens` must be a whole number from 1 to 2048. `privacy` is `hash_only`
(default) or `full`. Auth is `IDEMCORE_API_KEY` (or `api_key=`). Billing is
measured server-side in tokens.

## Tests

```bash
pip install -e ".[dev]"
pytest
```

Unit tests mock the SDK. A live smoke test runs only when `IDEMCORE_API_KEY`
is set in the environment.
