Metadata-Version: 2.4
Name: yian
Version: 0.0.3
Summary: Bridging the trust gap between humans and agents — a readable, Docker-Compose-shaped YAML surface where both people and LLMs compose, inspect, and refine agent workflows.
Author: Ngoc Bui
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/ngocbh/yian
Project-URL: Repository, https://github.com/ngocbh/yian
Project-URL: Documentation, https://yian.readthedocs.io
Keywords: llm,agents,workflow,orchestration,langchain,yaml
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langchain-core>=0.3.81
Requires-Dist: pydantic>=2.7.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: lark>=1.1
Requires-Dist: typing-extensions>=4.14.0
Requires-Dist: typer>=0.21.0
Requires-Dist: rich>=13.7.0
Requires-Dist: questionary>=2.1.0
Provides-Extra: anthropic
Requires-Dist: langchain-anthropic>=0.3.15; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: langchain-openai==1.6.2; extra == "openai"
Provides-Extra: google
Requires-Dist: langchain-google-genai>=4.0.0; extra == "google"
Provides-Extra: ollama
Requires-Dist: langchain-ollama>=1.1.0; extra == "ollama"
Provides-Extra: all
Requires-Dist: langchain-anthropic>=0.3.15; extra == "all"
Requires-Dist: langchain-openai==1.6.2; extra == "all"
Requires-Dist: langchain-google-genai>=4.0.0; extra == "all"
Requires-Dist: langchain-ollama>=1.1.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.26; extra == "docs"
Requires-Dist: black>=24.0; extra == "docs"
Dynamic: license-file

# Yian - The Agent Composer

[![Documentation](https://readthedocs.org/projects/yian/badge/?version=latest)](https://yian.readthedocs.io)

Yian is a small language and runtime for readable agent flows. You
author a fixed graph in Docker-Compose-shaped YAML; the framework infers data
dependencies, applies explicit ordering constraints, validates types, and runs
through an append-only log.

In this framework, an **agent** is a composable transformation from a named
input record to an output value. It can be represented by one node, a flow of
nodes, or a child flow used inside another flow. The YAML **AGENT node**
(`kind: agent`) is one concrete implementation: an LLM-backed node with a task
prompt and optional tool grants, model configuration, and long-term memory.

The author fixes the graph. LLMs generate values and may choose among explicitly
granted tools, but they do not rewrite the flow structure at run time.

```yaml
# hello.yaml — a compact one-node flow
id: hello
name: hello
input:
  name: str
output: str
kind: agent
prompt: Write a warm one-sentence greeting to ${name}.
```

```console
yian run hello.yaml --input name=Ada --provider ollama --model llama3.2:3b
```

See [Agent](docs/agent.md) for the conceptual model and
[Flow syntax](docs/syntax.md) for the complete YAML surface.
AGENT nodes can declare [typed local variables](docs/syntax.md#agent-owned-variables)
with validated defaults and reference them in prompts as `${name}`.

## Why fixed flows?

- **Readable:** the flow is the plan. Humans and models can inspect the same
  artifact before it runs.
- **Composable:** typed nodes build flows; CALL, MAP, and LOOP apply child flows
  recursively within the runtime depth limit.
- **Predictable:** data references determine the data edges, and the LLM never
  changes the authored call graph.
- **Recoverable:** every accepted transition is appended before it is applied,
  so an interrupted run can replay a validated record prefix.
- **Evolvable:** fixed flow and node identities give learning stable targets, so
  recorded outcomes from completed runs can improve later behavior without
  mutating the graph mid-run.

## Install

> **Early stage.** Yian is under active development. The API, YAML
> surface, and CLI may change quickly.

The current documentation describes the `main` branch. PyPI release `0.0.1`
contains an older, incompatible package, so install the current version from a
clone until the next release:

```console
git clone https://github.com/ngocbh/yian.git
cd yian
python -m pip install ".[all]"
```

For development, use `python -m pip install -e ".[all,dev]"` instead.

Provider extras can be installed separately: `anthropic`, `openai`, `google`,
or `ollama`. The core engine and CLI do not require a provider SDK; a flow needs
one only when it contains an AGENT node.

Connect OpenAI with `yian auth openai`, choose ChatGPT subscription sign-in or an
API key, and select a default model. Both methods use `provider: openai` with
Yian's ordinary tools and memory. OpenAI is the default provider; successful
setup saves your chosen model for subsequent runs. See
[authentication setup](docs/installation.md#openai-authentication).

## Run a flow

```console
yian run FLOW.yaml [--inputs inputs.json] [--input k=v]... \
  [--provider P] [--model M] [-w N] [--log PATH]
```

`--inputs` accepts a JSON object, including lists, records, and explicit nulls.
Repeatable `--input k=v` supplies scalar overrides. In a terminal, the CLI
prompts for declared inputs that are still missing.

New runs use up to eight workers for independent ready nodes. Set
`--num-workers N` / `-w N` to override the count, or `-w 0` for serial execution.
Resuming without a worker flag preserves the count recorded in the run log.

The CLI reports its selected JSONL path before execution. Once runtime
initialization commits `RunStarted`, that file is the authoritative log. The
default is `~/.yian/runs/<run_id>.jsonl`; choose another new path with
`--log`.
Resume an interrupted run against the same flow:

```console
yian run FLOW.yaml --resume PATH
```

Run logs can contain inputs, model/tool/human data, outputs, memory snapshots,
configuration, and tracebacks. Treat them as sensitive. See [The `yian`
CLI](docs/cli.md) for input behavior, diagnostics, concurrency, and recovery.

For an interactive flow-backed chat:

```console
yian chat [FLOW] [--workspace DIR] [--provider P] [--model M]
```

The default yian chat can inspect, validate, run, and—after explicit
approval—write flows inside its workspace. A supplied chat flow owns its own
typed exit behavior.

## Use the Python API

```python
from pathlib import Path

from yian import load_flow, run_flow

path = Path("hello.yaml")
flow = load_flow(
    path.read_text(),
    search_paths=[path.parent],
    source_label=path.name,
)
result = run_flow(
    flow,
    {"name": "Ada"},
    llm_config={"provider": "ollama", "model": "llama3.2:3b"},
)
print(result.status, result.output)
```

`load_flow` parses, validates, and compiles the YAML into a reusable
`ComposedFlow`. `run_flow` makes a private graph for one run and returns a
`RunResult` with either the flow output or an expected `Failure`. Host, control,
log, and invariant faults propagate as exceptions.

A library host can inject per-run tools (including its `ask_user` handler and
named tool groups that an AGENT grants by name) with `tools=`, provider
configuration, and named memory implementations. To pass a provider key without an
environment variable, add it to the run's config, as in
`llm_config={"provider": "anthropic", "model": "claude-sonnet-4-5", "api_key": key}`;
the key is never recorded or echoed, so pass it again to `resume_flow(...,
api_key=key)` or `result.backward(..., api_key=key)`. A `base_url` beside the key,
such as an Azure OpenAI resource's `https://<resource>.openai.azure.com/openai/v1/`
with `"provider": "openai"`, is where that key is sent; flow files cannot set it.
Without one, the provider's default or environment endpoint applies.
Passing `learnable=True`
retains accepted execution for a later explicit `result.backward(feedback)` call,
with or without memory. Each call is a new
attempt, so feedback can arrive several times, days later. Forward
execution returns before any learning or commit; memory recall is independent.
The returned `BackwardOutcome` and `result.backward_outcome` keep feedback and
learning separate from the forward output and failure. See the
[Python API](docs/api.md#explicit-backward-feedback) for feedback shapes, memory,
and silent terminal recovery.

Pass `on_stream=` to receive an AGENT's reply text as it is generated. Pass
`on_event=` to receive node transitions plus, while an AGENT runs, per-call
`ModelCallFinished` token usage and tool call observers. Both are live callbacks
only; see [Python API](docs/api.md#run_flow) for payloads.

A host can steer or interrupt a running `tool_calling` AGENT that declares
`steerable: true`. Pass `steering=inbox`, any object with `drain(node_id) ->
list[str]` and `interrupted(node_id) -> bool`. Queued steers reach the model as
user messages at the top of the next loop iteration. An interrupt ends the loop
at the next safe point, including mid-stream, and the node succeeds with its text
so far. See [Steering](docs/api.md#steering).

The built-in [`EpisodicMemory`](docs/learning.md#episodic-memory) keeps bounded,
model-free execution history for later runs. A flow declares a named memory,
`long_term_memory: {notes: episodic}`; its host builds the declared backends
with `build_memories` (in RAM unless given storage) and commits retained
episodes through explicit backward:

```python
from yian import build_memories

with build_memories(flow) as memory:
    result = run_flow(flow, inputs, memory=memory, learnable=True)
    result.backward()
```

[`ProfileMemory`](docs/learning.md#profile-memory) keeps one markdown document,
such as a person's profile, in a versioned file. Every AGENT under the declaring
flow sees the whole document; backward rewrites it with one model call and a
compare-and-set write. Declare `long_term_memory: {about: profile}` and supply
the backend under its key:

```python
from yian import build_memories
from yian.memory.profile import ProfileMemory
from yian.memory.storage import FileMarkdownStore

profile = ProfileMemory(FileMarkdownStore("people/ada.md"))
with build_memories(flow, supplied={"about": profile}) as memory:
    result = run_flow(flow, inputs, memory=memory, learnable=True)
    result.backward("Ada prefers short replies.")
```

[`SessionMemory`](docs/api.md#sessionmemory-foundation) supplies a structured session
transcript through the same memory context as notes from other memories. It keeps
conversation history across runs in the same process. Declare
`long_term_memory: {chat: session}` on the AGENT and reuse one registry:

```python
from yian import build_memories

with build_memories(flow) as memory:
    first = run_flow(flow, first_inputs, memory=memory)
    second = run_flow(flow, next_inputs, memory=memory)
    memory["chat"].reset()  # Starts fresh; fails while any turn is active or queued.
```

History advances automatically, without `learnable=True` or backward. Every call
site of the declaring AGENT shares its one conversation, and calls queue in
admission order. Two AGENTs cannot share a session key, so each keeps a separate
conversation. Explicit backward learning reuses API self-feedback
as committed notes for future runs, without another model call. API history uses a
soft 32,000-character context budget and preserves the latest four whole turns;
older context can be summarized without deleting raw history. Configure these
defaults on `SessionMemory(history_budget_chars=32_000, recent_turns=4)`.
Run logs do not reconstruct history. The episodic, reflective, and session
backends optionally retain their state across restarts in a SQLite file.
`build_memories` places one memory with `storage={key: path}`, or every memory
under `root=` (the flow `id:` must be usable as one directory name):

```python
with build_memories(flow, storage={"chat": "./session.sqlite"}) as memory:
    result = run_flow(flow, inputs, memory=memory)
```

An AGENT can also use Claude Code and Codex skills. `skills: [release-notes]` (or
`skills: all`) lists each granted skill's name and description in the system
message, and the model reads a skill's `SKILL.md` or bundled files through the
built-in `load_skill` tool when it needs them. `yian run` supplies the skills in
`~/.claude/skills`, `~/.agents/skills`, and the project's `.claude/skills` and
`.agents/skills`; a library host passes `skills=load_skills([...])` from
`yian.compose` (`{}` when a granting flow should get none). See [Skills](docs/api.md#skills).

Each local SQLite file has one owning backend until `close()` or context exit.
Idle run handles do not block closing; active work or queued turns do. Omit
`storage` to keep memory process-local. See [durable memory](docs/api.md#optional-durable-memory)
for ownership and recovery.

`yian run` builds every declared built-in memory (`episodic`, `reflective`,
`session`, `profile`). They stay in RAM unless a CLI option places them:

```bash
yian run flow.yaml --memory-root ./mem
yian run flow.yaml --resume ./run.jsonl --memory-root ./mem
```

`--memory-root DIR` keeps every memory under `DIR/<flow id>/` (the flow `id:`
must be usable as one directory name), and repeatable `--memory-storage KEY=PATH`
places one declared memory.
Use the same storage on resume; a run log is not a memory backup. The CLI does
not run backward learning. A flow that declares a custom memory type runs from
Python with `build_memories`; `yian run` exits 1 with a setup error for it.
See [CLI memory](docs/cli.md#memory-and-storage) for lifetime and examples.

## Documentation

- [Agent](docs/agent.md) — what “agent,” node, flow, child flow, memory, and run
  mean in this framework.
- [Architecture](docs/architecture.md) — how YAML becomes a compiled flow and a
  `RunResult`.
- [Flow syntax](docs/syntax.md) — the complete authoring reference.
- [Examples](docs/examples.md) — annotated flows from `examples/`.
- [Compose](docs/compose.md) — parsing, lowering, validation, and source origins.
- [The engine](docs/engine.md) — scheduling, records, recovery, and learning.
- [Runtime nodes](docs/nodes.md) — the `Node` / `NodeResult` contract.
- [Engine design](src/yian/README.md) — contributor invariants and
  package ownership.

## Develop and test

```console
pip install -e ".[all,dev]"
PYTHONPATH=src python -m pytest
```

See [Contributing](CONTRIBUTING.md) for the issue/branch/PR workflow and
[Installation](docs/installation.md) for local environment setup.

## License

Apache 2.0 — see [LICENSE](LICENSE).
