同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ""
|
||||
labels: ""
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
A clear and minimal example to reproduce the bug.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,29 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "cargo" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "daily"
|
||||
groups:
|
||||
development:
|
||||
dependency-type: "development"
|
||||
tree-sitter:
|
||||
patterns:
|
||||
- "tree-sitter*"
|
||||
aws:
|
||||
patterns:
|
||||
- "aws*"
|
||||
minor:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Bench
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
deployments: write
|
||||
|
||||
jobs:
|
||||
benchmark:
|
||||
name: Benchmark
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Run benchmark
|
||||
run: cargo bench -p benchmarks -- --output-format bencher | tee benchmarks/output.txt
|
||||
|
||||
- name: Store benchmark result
|
||||
uses: benchmark-action/github-action-benchmark@v1
|
||||
with:
|
||||
name: Rust Benchmark
|
||||
tool: "cargo"
|
||||
output-file-path: benchmarks/output.txt
|
||||
github-token: ${{ github.token }}
|
||||
auto-push: true
|
||||
# Show alert with commit comment on detecting possible performance regression
|
||||
alert-threshold: "200%"
|
||||
comment-on-alert: true
|
||||
fail-on-alert: true
|
||||
alert-comment-cc-users: "@timonv"
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Coverage
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-coverage
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
RUSTFLAGS: "-Dwarnings -Clink-arg=-fuse-ld=lld"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: coverage
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
with:
|
||||
components: llvm-tools-preview
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Install cargo-llvm-cov
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-llvm-cov
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y lld libcurl4-openssl-dev
|
||||
- name: Generate code coverage
|
||||
run: |
|
||||
cargo llvm-cov --tests -j 2 --all-features --lcov --output-path lcov.info
|
||||
|
||||
- name: Coveralls
|
||||
uses: coverallsapp/github-action@v2
|
||||
@@ -0,0 +1,20 @@
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
github-releases-to-discord:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Github Releases To Discord
|
||||
uses: SethCohen/github-releases-to-discord@v1.20.0
|
||||
with:
|
||||
webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
color: "2105893"
|
||||
username: "Release Changelog"
|
||||
avatar_url: "https://cdn.discordapp.com/avatars/487431320314576937/bd64361e4ba6313d561d54e78c9e7171.png"
|
||||
footer_title: "Changelog"
|
||||
footer_icon_url: "https://cdn.discordapp.com/avatars/487431320314576937/bd64361e4ba6313d561d54e78c9e7171.png"
|
||||
footer_timestamp: true
|
||||
@@ -0,0 +1,76 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-lint
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy
|
||||
- uses: r7kamura/rust-problem-matchers@v1
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libcurl4-openssl-dev
|
||||
- name: Check typos
|
||||
uses: crate-ci/typos@master
|
||||
# - name: Lint dependencies
|
||||
# uses: EmbarkStudios/cargo-deny-action@v2
|
||||
- name: clippy
|
||||
run: cargo clippy --all-targets --all-features --workspace
|
||||
env:
|
||||
RUSTFLAGS: "-Dwarnings"
|
||||
|
||||
lint-formatting:
|
||||
name: Lint formatting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
with:
|
||||
components: rustfmt
|
||||
- uses: r7kamura/rust-problem-matchers@v1
|
||||
- name: "Rustfmt"
|
||||
run: cargo +nightly fmt --all -- --check
|
||||
env:
|
||||
RUSTFLAGS: "-Dwarnings"
|
||||
|
||||
hack:
|
||||
name: Cargo Hack
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt
|
||||
- uses: r7kamura/rust-problem-matchers@v1
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libcurl4-openssl-dev
|
||||
- name: Install cargo-hack
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-hack
|
||||
- name: Check features with Cargo Hack
|
||||
run: cargo hack check --each-feature --no-dev-deps
|
||||
@@ -0,0 +1,86 @@
|
||||
name: Check Pull Requests
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- synchronize
|
||||
- labeled
|
||||
- unlabeled
|
||||
merge_group:
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
check-title:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check PR title
|
||||
if: github.event_name == 'pull_request_target'
|
||||
uses: amannn/action-semantic-pull-request@v6
|
||||
id: check_pr_title
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
# Add comment indicating we require pull request titles to follow conventional commits specification
|
||||
- uses: marocchino/sticky-pull-request-comment@v2
|
||||
if: always() && (steps.check_pr_title.outputs.error_message != null)
|
||||
with:
|
||||
header: pr-title-lint-error
|
||||
message: |
|
||||
Thank you for opening this pull request!
|
||||
|
||||
We require pull request titles to follow the [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/) and it looks like your proposed title needs to be adjusted.
|
||||
|
||||
Details:
|
||||
|
||||
> ${{ steps.check_pr_title.outputs.error_message }}
|
||||
|
||||
# Delete a previous comment when the issue has been resolved
|
||||
- if: ${{ steps.check_pr_title.outputs.error_message == null }}
|
||||
uses: marocchino/sticky-pull-request-comment@v2
|
||||
with:
|
||||
header: pr-title-lint-error
|
||||
delete: true
|
||||
|
||||
check-breaking-change-label:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# use an environment variable to pass untrusted input to the script
|
||||
# see https://securitylab.github.com/research/github-actions-untrusted-input/
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
steps:
|
||||
- name: Check breaking change label
|
||||
id: check_breaking_change
|
||||
run: |
|
||||
pattern='^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(\w+\))?!:'
|
||||
# Check if pattern matches
|
||||
if echo "${PR_TITLE}" | grep -qE "$pattern"; then
|
||||
echo "breaking_change=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "breaking_change=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Add label
|
||||
if: steps.check_breaking_change.outputs.breaking_change == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
script: |
|
||||
github.rest.issues.addLabels({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
labels: ['breaking change']
|
||||
})
|
||||
|
||||
do-not-merge:
|
||||
if: ${{ contains(github.event.*.labels.*.name, 'do not merge') }}
|
||||
name: Prevent Merging
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check for label
|
||||
run: |
|
||||
echo "Pull request is labeled as 'do not merge'"
|
||||
echo "This workflow fails so that the pull request cannot be merged"
|
||||
exit 1
|
||||
@@ -0,0 +1,33 @@
|
||||
name: Release
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
release-swiftide:
|
||||
name: Crates.io
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.RELEASE_PLZ_TOKEN }}
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Run release-plz
|
||||
uses: MarcoIeni/release-plz-action@v0.5
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
|
||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
GITHUB_REPO: ${{ github.repository }}
|
||||
@@ -0,0 +1,49 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-test
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTFLAGS: "-Dwarnings -Clink-arg=-fuse-ld=lld"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y lld libcurl4-openssl-dev
|
||||
- name: "Test"
|
||||
run: cargo test -j 2 --tests --all-features --no-fail-fast
|
||||
docs:
|
||||
name: Docs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install Protoc
|
||||
uses: arduino/setup-protoc@v3
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y lld libcurl4-openssl-dev
|
||||
- name: "Test"
|
||||
run: cargo test --doc --all-features --no-fail-fast
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
|
||||
# Added by cargo
|
||||
|
||||
target
|
||||
tmp
|
||||
|
||||
.env
|
||||
.env*.local
|
||||
|
||||
**/.fastembed_cache
|
||||
.idea/
|
||||
.history.cargo
|
||||
@@ -0,0 +1,8 @@
|
||||
# configuration for https://github.com/DavidAnson/markdownlint
|
||||
|
||||
first-line-heading: false
|
||||
no-inline-html: false
|
||||
line-length: false
|
||||
|
||||
# to support repeated headers in the changelog
|
||||
no-duplicate-heading: false
|
||||
@@ -0,0 +1,35 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
|
||||
Swiftide is a Rust workspace driven by the library in `swiftide/`, with supporting crates such as `swiftide-core/` for shared primitives, `swiftide-agents/` for agent orchestration, `swiftide-indexing/` and `swiftide-query/` for pipeline flows, and `swiftide-integrations/` for external connectors. Shared fixtures live in `swiftide-test-utils/`, while `examples/` hosts runnable demos and `benchmarks/` tracks performance scenarios. Static assets (logos and diagrams) are under `images/`.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
|
||||
- `cargo check --workspace --all-features` quickly verifies the entire workspace compiles with all feature flags enabled.
|
||||
- `cargo build --workspace --all-features` compiles every crate and surfaces feature-gating issues early.
|
||||
- `cargo check -p swiftide-agents` is a fast way to probe agent changes before touching the rest of the workspace.
|
||||
- `cargo +nightly fmt --all` applies the repo `rustfmt.toml` (comment wrapping requires nightly); use `cargo +nightly fmt --all -- --check` to mirror CI formatting validation.
|
||||
- `cargo clippy --workspace --all-targets --all-features -- -D warnings` mirrors the main lint job and keeps us aligned with the pedantic lint profile baked into `Cargo.toml`.
|
||||
- `cargo test -j 2 --tests --all-features --no-fail-fast` mirrors the main CI test job for unit and integration tests.
|
||||
- `cargo test --doc --all-features --no-fail-fast` mirrors the docs test job in CI.
|
||||
- `cargo hack check --each-feature --no-dev-deps` mirrors the Cargo Hack feature-matrix check run in CI.
|
||||
- `typos` mirrors the spelling check run in CI.
|
||||
- `cargo test --workspace` is still useful locally when you want a broader default test sweep; use `RUST_LOG=info` if you need verbose diagnostics.
|
||||
- Snapshot updates flow through `cargo insta review` after tests rewrite `.snap` files.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
|
||||
Follow Rust 2024 idioms with four-space indentation. Public APIs should embrace builder patterns and the naming guidance from the Rust API Guidelines: `snake_case` for functions, `UpperCamelCase` for types, and `SCREAMING_SNAKE_CASE` constants. Avoid `unsafe` blocks—`Cargo.toml` forbids them at the workspace level. Keep comments concise so `wrap_comments = true` can format them within 100 columns.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
Prefer focused crate runs such as `cargo test -p swiftide-integrations` when iterating, and opt into `-- --ignored` for heavier scenarios. Integration tests rely on `testcontainers`, so ensure Docker is available; keep fixtures inside `swiftide-test-utils/` to reuse container helpers. For `insta` snapshots, commit reviewed `.snap.new` diffs only after `cargo insta review` removes pending files.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
Commits follow conventional syntax (`feat(agents): …`, `fix(indexing): …`) with a lowercase imperative summary. Pull request titles are also checked against the conventional commits format in CI, and titles ending in `!` receive the `breaking change` label automatically. Each PR should describe the change, link any GitHub issue, note API or schema impacts, and include before/after traces or logs when behavior changes. Update docs (README, website, or inline rustdoc) and add tests or benchmarks alongside functional work. Before requesting review, run the full lint and test suite listed above.
|
||||
|
||||
## Tooling & Environment Notes
|
||||
|
||||
The workspace pins `stable` in `rust-toolchain.toml`; use the same channel unless a nightly tool is explicitly required. Dependency hygiene is enforced with `cargo deny --workspace`, and spelling checks may run via `typos`. Store local credentials with `mise` or environment variables—never commit secrets.
|
||||
+2702
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
# Contribution guidelines
|
||||
|
||||
|
||||
Swiftide is in a very early stage and we are aware that we do lack features for the wider community. Contributions are very welcome. :tada:
|
||||
|
||||
Indexing and querying are performance sensitive tasks. Please make sure to consider allocations and performance when contributing.
|
||||
|
||||
AI Generated code is welcome and not frowned upon. Please be genuine and think critically about what you add.
|
||||
|
||||
For AI agents read the [AGENTS.md](AGENTS.md) for workspace layout, commands, and expectations tailored to agents.
|
||||
|
||||
## Feature requests and feedback
|
||||
|
||||
We love them, please let us know what you would like. Use one of the templates provided.
|
||||
|
||||
## Code design
|
||||
|
||||
* Simple, thin wrappers with sane defaults
|
||||
* Provide a builder (derive_builder) for easy customization
|
||||
* Keep Rust complexity (Arc/Box/Lifetimes/Pinning ...) encapsulated and away from library users
|
||||
* Adhere to [Rust api naming](https://rust-lang.github.io/api-guidelines/naming.html) as much as possible
|
||||
|
||||
## Bug reports
|
||||
|
||||
It happens, but we still love them.
|
||||
|
||||
## Submitting pull requests
|
||||
|
||||
If you have a great idea, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
|
||||
Don't forget to give the project a star! Thanks again!
|
||||
|
||||
If you just want to contribute (bless you!), see [our issues](https://github.com/bosun-ai/swiftide/issues).
|
||||
|
||||
1. Fork the Project
|
||||
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Commit your Changes (`git commit -m 'feat: Add some AmazingFeature'`)
|
||||
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
||||
5. Open a Pull Request
|
||||
|
||||
Make sure that:
|
||||
|
||||
* Public functions are documented in code
|
||||
* Documentation is updated in the [user documentation](https://github.com/bosun-ai/swiftide-website)
|
||||
* Tests are added
|
||||
* Verified performance with benchmarks if applicable
|
||||
Generated
+12620
File diff suppressed because it is too large
Load Diff
+160
@@ -0,0 +1,160 @@
|
||||
cargo-features = ["edition2024"]
|
||||
|
||||
[workspace]
|
||||
members = ["swiftide", "swiftide-*", "examples", "benchmarks"]
|
||||
default-members = ["swiftide", "swiftide-*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.32.1"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
keywords = ["llm", "rag", "ai", "data", "openai"]
|
||||
description = "Fast, streaming indexing, query, and agentic LLM applications in Rust"
|
||||
categories = ["asynchronous"]
|
||||
repository = "https://github.com/bosun-ai/swiftide"
|
||||
homepage = "https://swiftide.rs"
|
||||
|
||||
[profile.dev.package]
|
||||
insta.opt-level = 3
|
||||
similar.opt-level = 3
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = { version = "1.0", default-features = false }
|
||||
thiserror = { version = "2.0", default-features = false }
|
||||
async-trait = { version = "0.1", default-features = false }
|
||||
derive_builder = { version = "0.20", default-features = true }
|
||||
fs-err = { version = "3.1", default-features = false }
|
||||
futures-util = { version = "0.3", default-features = true }
|
||||
tokio = { version = "1.46", features = [
|
||||
"rt-multi-thread",
|
||||
"time",
|
||||
], default-features = false }
|
||||
tokio-stream = { version = "0.1", default-features = false, features = [
|
||||
"time",
|
||||
] }
|
||||
tokio-util = { version = "0.7", default-features = false }
|
||||
tracing = { version = "0.1", features = [
|
||||
"log",
|
||||
"attributes",
|
||||
], default-features = false }
|
||||
num_cpus = { version = "1.17", default-features = false }
|
||||
pin-project = { version = "1.1", default-features = false }
|
||||
itertools = { version = "0.14", default-features = true }
|
||||
serde = { version = "1.0", features = [
|
||||
"derive",
|
||||
"std",
|
||||
], default-features = false }
|
||||
serde_json = { version = "1.0", default-features = false, features = ["std"] }
|
||||
strum = { version = "0.28", default-features = false }
|
||||
strum_macros = { version = "0.28", default-features = false }
|
||||
lazy_static = { version = "1.5", default-features = false }
|
||||
chrono = { version = "0.4", default-features = false }
|
||||
indoc = { version = "2.0", default-features = false }
|
||||
regex = { version = "1.11", default-features = false }
|
||||
uuid = { version = "1.18", features = [
|
||||
"v3",
|
||||
"v4",
|
||||
"serde",
|
||||
], default-features = false }
|
||||
dyn-clone = { version = "1.0", default-features = false }
|
||||
convert_case = { version = "0.11", default-features = false }
|
||||
base64 = { version = "0.22", default-features = false, features = ["std"] }
|
||||
|
||||
# Mcp
|
||||
rmcp = { version = "0.17", default-features = false, features = [
|
||||
"base64",
|
||||
"macros",
|
||||
"server",
|
||||
] }
|
||||
schemars = { version = "1.0", default-features = false }
|
||||
|
||||
# Integrations
|
||||
spider = { version = "2.45", default-features = false }
|
||||
async-openai = { version = ">=0.33.0", default-features = false }
|
||||
qdrant-client = { version = "1.17", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
fluvio = { version = "0.50.1", default-features = false }
|
||||
rdkafka = { version = "0.39.0", features = ["cmake-build"] }
|
||||
lancedb = { version = "0.26", default-features = false, features = ["remote"] }
|
||||
# Needs to stay in sync with whatever lancdb uses, nice
|
||||
arrow-array = { version = "57.1", default-features = false }
|
||||
parquet = { version = "57.1", default-features = false, features = ["async"] }
|
||||
redb = { version = "3.1", default-features = false }
|
||||
sqlx = { version = "0.8", features = [
|
||||
"postgres",
|
||||
"uuid",
|
||||
], default-features = false }
|
||||
aws-config = { version = "1.8", default-features = true }
|
||||
pgvector = { version = "0.4", features = ["sqlx"], default-features = false }
|
||||
aws-credential-types = { version = "1.2", default-features = false }
|
||||
aws-sdk-bedrockruntime = { version = "1.126", default-features = false }
|
||||
aws-smithy-types = { version = "1.3", default-features = false }
|
||||
criterion = { version = "0.8", default-features = false }
|
||||
darling = { version = "0.23", default-features = false }
|
||||
deadpool = { version = "0.13", default-features = false }
|
||||
document-features = { version = "0.2" }
|
||||
fastembed = { version = "5.5", default-features = false }
|
||||
flv-util = { version = "0.5", default-features = false }
|
||||
htmd = { version = "0.5", default-features = false }
|
||||
ignore = { version = "0.4", default-features = false }
|
||||
proc-macro2 = { version = "1.0", default-features = false }
|
||||
quote = { version = "1.0", default-features = false }
|
||||
redis = { version = "1.0", default-features = false }
|
||||
reqwest = { version = "0.13", default-features = false }
|
||||
secrecy = { version = "0.10", default-features = false }
|
||||
syn = { version = "2.0", default-features = false }
|
||||
tera = { version = "1.20", default-features = false }
|
||||
text-splitter = { version = "0.29", default-features = false }
|
||||
tracing-subscriber = { version = "0.3", default-features = true }
|
||||
tree-sitter = { version = "0.26", default-features = false, features = ["std"] }
|
||||
tree-sitter-java = { version = "0.23", default-features = false }
|
||||
tree-sitter-javascript = { version = "0.25", default-features = false }
|
||||
tree-sitter-python = { version = "0.25", default-features = false }
|
||||
tree-sitter-ruby = { version = "0.23", default-features = false }
|
||||
tree-sitter-rust = { version = "0.24", default-features = false }
|
||||
tree-sitter-typescript = { version = "0.23", default-features = false }
|
||||
tree-sitter-go = { version = "0.25", default-features = false }
|
||||
tree-sitter-solidity = { version = "1.2", default-features = false }
|
||||
tree-sitter-c = { version = "0.24", default-features = false }
|
||||
tree-sitter-cpp = { version = "0.23", default-features = false }
|
||||
tree-sitter-elixir = { version = "0.3.4", default-features = false }
|
||||
tree-sitter-html = { version = "0.23", default-features = false }
|
||||
tree-sitter-php = { version = "0.24", default-features = false }
|
||||
tree-sitter-c-sharp = { version = "0.23", default-features = false }
|
||||
async-anthropic = { version = "0.6.0", default-features = false }
|
||||
duckdb = { version = "1", default-features = false }
|
||||
libduckdb-sys = { version = "1", default-features = false }
|
||||
metrics = { version = "0.24", default-features = false }
|
||||
tiktoken-rs = { version = "0.9", default-features = false }
|
||||
reqwest-eventsource = { version = "0.6", default-features = false }
|
||||
|
||||
# Testing
|
||||
test-log = { version = "0.2" }
|
||||
testcontainers = { version = "0.27", features = ["http_wait"] }
|
||||
testcontainers-modules = { version = "0.15" }
|
||||
mockall = { version = "0.14" }
|
||||
temp-dir = { version = "0.2" }
|
||||
wiremock = { version = "0.6" }
|
||||
test-case = { version = "3.3" }
|
||||
pretty_assertions = { version = "1.4" }
|
||||
insta = { version = "1.45", features = ["yaml", "filters"] }
|
||||
eventsource-stream = { version = "0.2" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(coverage,coverage_nightly)',
|
||||
] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cargo = { level = "warn", priority = -1 }
|
||||
pedantic = { level = "warn", priority = -1 }
|
||||
blocks_in_conditions = "allow"
|
||||
must_use_candidate = "allow"
|
||||
module_name_repetitions = "allow"
|
||||
missing_fields_in_debug = "allow"
|
||||
# Should be fixed asap
|
||||
multiple_crate_versions = "allow"
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Bosun.ai
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,387 @@
|
||||
<details>
|
||||
<summary>Table of Contents</summary>
|
||||
|
||||
<!--toc:start-->
|
||||
|
||||
- [What is Swiftide?](#what-is-swiftide)
|
||||
- [High level features](#high-level-features)
|
||||
- [Latest updates on our blog :fire:](#latest-updates-on-our-blog-fire)
|
||||
- [Examples](#examples)
|
||||
- [Vision](#vision)
|
||||
- [Features](#features)
|
||||
- [In detail](#in-detail)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Usage and concepts](#usage-and-concepts)
|
||||
- [Indexing](#indexing)
|
||||
- [Querying](#querying)
|
||||
- [Contributing](#contributing)
|
||||
- [Core Team Members](#core-team-members)
|
||||
- [License](#license)
|
||||
<!--toc:end-->
|
||||
|
||||
</details>
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
<!-- PROJECT SHIELDS -->
|
||||
<!--
|
||||
*** I'm using markdown "reference style" links for readability.
|
||||
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
|
||||
*** See the bottom of this document for the declaration of the reference variables
|
||||
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
|
||||
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
|
||||
-->
|
||||
|
||||

|
||||

|
||||
[![Crate Badge]][Crate]
|
||||
[![Docs Badge]][API Docs]
|
||||
[![Contributors][contributors-shield]][contributors-url]
|
||||
[![Stargazers][stars-shield]][stars-url]
|
||||

|
||||
[![MIT License][license-shield]][license-url]
|
||||
[![LinkedIn][linkedin-shield]][linkedin-url]
|
||||
|
||||
<!-- PROJECT LOGO -->
|
||||
<br />
|
||||
<div align="center">
|
||||
<a href="https://github.com/bosun-ai/swiftide">
|
||||
<img src="https://raw.githubusercontent.com/bosun-ai/swiftide/master/images/logo.png" alt="Logo" width="250" height="250">
|
||||
</a>
|
||||
|
||||
<h3 align="center">Swiftide</h3>
|
||||
|
||||
<p align="center">
|
||||
Fast, streaming indexing, query, and agentic LLM applications in Rust
|
||||
<br />
|
||||
<a href="https://swiftide.rs"><strong>Read more on swiftide.rs »</strong></a>
|
||||
<br />
|
||||
<br />
|
||||
<!-- <a href="https://github.com/bosun-ai/swiftide">View Demo</a> -->
|
||||
<a href="https://docs.rs/swiftide/latest/swiftide/">API Docs</a>
|
||||
·
|
||||
<a href="https://github.com/bosun-ai/swiftide/issues/new?labels=bug&template=bug_report.md">Report Bug</a>
|
||||
·
|
||||
<a href="https://github.com/bosun-ai/swiftide/issues/new?labels=enhancement&template=feature_request.md">Request Feature</a>
|
||||
·
|
||||
<a href="https://discord.gg/3jjXYen9UY">Discord</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ABOUT THE PROJECT -->
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## What is Swiftide?
|
||||
|
||||
<!-- [![Product Name Screen Shot][product-screenshot]](https://example.com) -->
|
||||
|
||||
Swiftide is a Rust library for building LLM applications. From performing a simple prompt completion, to building fast, streaming indexing and querying pipelines, to building agents that can use tools and call other agents.
|
||||
|
||||
### High level features
|
||||
|
||||
- Simple primitives for common LLM tasks
|
||||
- Build fast, streaming indexing and querying pipelines
|
||||
- Easily build agents, mix and match with previously built pipelines
|
||||
- A modular and extendable API, with minimal abstractions
|
||||
- Integrations with popular LLMs and storage providers
|
||||
- Ready to use pipeline transformations or bring your own
|
||||
- Build graph like workflows with Tasks
|
||||
- [Langfuse](https://langfuse.com) support
|
||||
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/bosun-ai/swiftide/master/images/overview.png" alt="Swiftide overview" width="100%" >
|
||||
</div>
|
||||
|
||||
Part of the [bosun.ai](https://bosun.ai) project. An upcoming platform for autonomous code improvement.
|
||||
|
||||
We <3 feedback: project ideas, suggestions, and complaints are very welcome. Feel free to open an issue or contact us on [discord](https://discord.gg/3jjXYen9UY).
|
||||
|
||||
> [!CAUTION]
|
||||
> Swiftide is under heavy development and can have breaking changes. Documentation might fall short of all features, and despite our efforts be slightly outdated. We recommend to always keep an eye on our [github](https://github.com/bosun-ai/swiftide) and [api documentation](https://docs.rs/swiftide/latest/swiftide/). If you found an issue or have any kind of feedback we'd love to hear from you.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## Latest updates on our blog :fire:
|
||||
|
||||
- [Swiftide 0.31 - Tasks, Langfuse, Multi-Modal, and more](http://blog.bosun.ai/swiftide-0-31/)
|
||||
- [Swiftide 0.27 - Easy human-in-the-loop flows for agentic AI](http://blog.bosun.ai/swiftide-0-27/)
|
||||
- [Swiftide 0.26 - Streaming agents](http://blog.bosun.ai/swiftide-0-26/)
|
||||
- [Releasing kwaak with kwaak](https://bosun.ai/posts/releasing-kwaak-with-kwaak/)
|
||||
- [Swiftide 0.16 - AI Agents in Rust](https://bosun.ai/posts/swiftide-0-16/)
|
||||
- [Rust in LLM based tools for performance](https://bosun.ai/posts/rust-for-genai-performance/)
|
||||
- [Evaluate Swiftide pipelines with Ragas](https://bosun.ai/posts/evaluating-swiftide-with-ragas/) (2024-09-15)
|
||||
- [Release - Swiftide 0.12](https://bosun.ai/posts/swiftide-0-12/) (2024-09-13)
|
||||
- [Local code intel with Ollama, FastEmbed and OpenTelemetry](https://bosun.ai/posts/ollama-and-telemetry/) (2024-09-04)
|
||||
|
||||
More on our [blog](https://blog.bosun.ai/)
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## Examples
|
||||
|
||||
Indexing a local code project, chunking into smaller pieces, enriching the nodes with metadata, and persisting into [Qdrant](https://qdrant.tech):
|
||||
|
||||
```rust
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.with_default_llm_client(openai_client.clone())
|
||||
.filter_cached(Redis::try_from_url(
|
||||
redis_url,
|
||||
"swiftide-examples",
|
||||
)?)
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size(
|
||||
"rust",
|
||||
10..2048,
|
||||
)?)
|
||||
.then(MetadataQACode::default())
|
||||
.then(move |node| my_own_thing(node))
|
||||
.then_in_batch(Embed::new(openai_client.clone()))
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
```
|
||||
|
||||
Querying for an example on how to use the query pipeline:
|
||||
|
||||
```rust
|
||||
query::Pipeline::default()
|
||||
.then_transform_query(GenerateSubquestions::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_transform_query(Embed::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_retrieve(qdrant.clone())
|
||||
.then_answer(Simple::from_client(openai_client.clone()))
|
||||
.query("How can I use the query pipeline in Swiftide?")
|
||||
.await?;
|
||||
```
|
||||
|
||||
Running an agent that can search code:
|
||||
|
||||
```rust
|
||||
#[swiftide::tool(
|
||||
description = "Searches code",
|
||||
param(name = "code_query", description = "The code query")
|
||||
)]
|
||||
async fn search_code(
|
||||
context: &dyn AgentContext,
|
||||
code_query: &str,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let command_output = context
|
||||
.executor()
|
||||
.exec_cmd(&Command::shell(format!("rg '{code_query}'")))
|
||||
.await?;
|
||||
|
||||
Ok(command_output.into())
|
||||
}
|
||||
|
||||
agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
.tools(vec![search_code()])
|
||||
.build()?
|
||||
.query("In what file can I find an example of a swiftide agent?")
|
||||
.await?;
|
||||
```
|
||||
|
||||
Agents loop over LLM calls, tool calls, and lifecycle hooks until a final answer is reached.
|
||||
|
||||
_You can find more detailed examples in [/examples](https://github.com/bosun-ai/swiftide/tree/master/examples)_
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## Vision
|
||||
|
||||
Our goal is to create a fast, extendable platform for building LLM applications in Rust, to further the development of automated AI applications, with an easy-to-use and easy-to-extend api.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## Features
|
||||
|
||||
- Simple primitives for common LLM tasks
|
||||
- Fast, modular streaming indexing pipeline with async, parallel processing
|
||||
- Experimental query pipeline
|
||||
- Experimental agent framework
|
||||
- A variety of loaders, transformers, semantic chunkers, embedders, and more
|
||||
- Bring your own transformers by extending straightforward traits or use a closure
|
||||
- Splitting and merging pipelines
|
||||
- Jinja-like templating for prompts
|
||||
- Store into multiple backends
|
||||
- Integrations with OpenAI, Groq, Gemini, Anthropic, Redis, Qdrant, Ollama, FastEmbed-rs, Fluvio, LanceDB, and Treesitter
|
||||
- Evaluate pipelines with RAGAS
|
||||
- Sparse vector support for hybrid search
|
||||
- `tracing` supported for logging and tracing, see /examples and the `tracing` crate for more information.
|
||||
- Tracing layer for exporting to Langfuse
|
||||
|
||||
### In detail
|
||||
|
||||
| **Feature** | **Details** |
|
||||
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Supported Large Language Model providers** | OpenAI (and Azure) <br> Anthropic <br> Gemini <br> OpenRouter <br> AWS Bedrock (Converse API) <br> Groq - All models <br> Ollama - All models |
|
||||
| **Agents** | All the boiler plate for autonomous agents so you don't have to |
|
||||
| **Tasks** | Build graph like workflows with tasks, combining all the above to build complex applications |
|
||||
| **Loading data** | Files <br> Scraping <br> Fluvio <br> Parquet <br> Kafka <br> Other pipelines and streams |
|
||||
| **Example and pre-build transformers and metadata generation** | Generate Question and answerers for both text and code (Hyde) <br> Summaries, titles and queries via an LLM <br> Extract definitions and references with tree-sitter |
|
||||
| **Splitting and chunking** | Markdown <br> Text (text_splitter) <br> Code (with tree-sitter) |
|
||||
| **Storage** | Qdrant <br> Redis <br> LanceDB <br> Postgres <br> Duckdb |
|
||||
| **Query pipeline** | Similarity and hybrid search, query and response transformations, and evaluation |
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- GETTING STARTED -->
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Make sure you have the rust toolchain installed. [rustup](https://rustup.rs) Is the recommended approach.
|
||||
|
||||
To use OpenAI, an API key is required. Note that by default `async_openai` uses the `OPENAI_API_KEY` environment variables.
|
||||
|
||||
Other integrations might have their own requirements.
|
||||
|
||||
### Installation
|
||||
|
||||
1. Set up a new Rust project
|
||||
2. Add swiftide
|
||||
|
||||
```sh
|
||||
cargo add swiftide
|
||||
```
|
||||
|
||||
3. Enable the features of integrations you would like to use in your `Cargo.toml`
|
||||
4. Write a pipeline (see our examples and documentation)
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- USAGE EXAMPLES -->
|
||||
|
||||
## Usage and concepts
|
||||
|
||||
Before building your streams, you need to enable and configure any integrations required. See /examples.
|
||||
|
||||
_We have a lot of examples, please refer to /examples and the [Documentation](https://docs.rs/swiftide/latest/swiftide/)_
|
||||
|
||||
> [!NOTE]
|
||||
> No integrations are enabled by default as some are code heavy. We recommend you to cherry-pick the integrations you need. By convention flags have the same name as the integration they represent.
|
||||
|
||||
### Indexing
|
||||
|
||||
An indexing stream starts with a Loader that emits Nodes. For instance, with the Fileloader each file is a Node.
|
||||
|
||||
You can then slice and dice, augment, and filter nodes. Each different kind of step in the pipeline requires different traits. This enables extension.
|
||||
|
||||
Nodes are generic over their inner type. This is a transition in progress, but when you BYO, feel free to slice and dice. The inner type can change midway through the pipeline.
|
||||
|
||||
- **from_loader** `(impl Loader)` starting point of the stream, creates and emits Nodes
|
||||
- **filter_cached** `(impl NodeCache)` filters cached nodes
|
||||
- **then** `(impl Transformer)` transforms the node and puts it on the stream
|
||||
- **then_in_batch** `(impl BatchTransformer)` transforms multiple nodes and puts them on the stream
|
||||
- **then_chunk** `(impl ChunkerTransformer)` transforms a single node and emits multiple nodes
|
||||
- **then_store_with** `(impl Storage)` stores the nodes in a storage backend, this can be chained
|
||||
|
||||
Additionally, several generic transformers are implemented. They take implementers of `SimplePrompt` and `EmbedModel` to do their things.
|
||||
|
||||
> [!WARNING]
|
||||
> Due to the performance, chunking before adding metadata gives rate limit errors on OpenAI very fast, especially with faster models like gpt-5-nano. Be aware. The `async-openai` crate provides an exmponential backoff strategy. If that is still a problem, there is also a decorator that supports streaming in `swiftide_core/indexing_decorators`.
|
||||
|
||||
### Querying
|
||||
|
||||
A query stream starts with a search strategy. In the query pipeline a `Query` goes through several stages. Transformers and retrievers work together to get the right context into a prompt, before generating an answer. Transformers and Retrievers operate on different stages of the Query via a generic statemachine. Additionally, the search strategy is generic over the pipeline and Retrievers need to implement specifically for each strategy.
|
||||
|
||||
That sounds like a lot but, tl&dr; the query pipeline is _fully and strongly typed_.
|
||||
|
||||
- **Pending** The query has not been executed, and can be further transformed with transformers
|
||||
- **Retrieved** Documents have been retrieved, and can be further transformed to provide context for an answer
|
||||
- **Answered** The query is done
|
||||
|
||||
Additionally, query pipelines can also be evaluated. I.e. by [Ragas](https://ragas.io).
|
||||
|
||||
Similar to the indexing pipeline each step is governed by simple Traits and closures implement these traits as well.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- ROADMAP -->
|
||||
|
||||
## Contributing
|
||||
|
||||
Swiftide is in a very early stage and we are aware that we lack features for the wider community. Contributions are very welcome. :tada:
|
||||
|
||||
If you have a great idea, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
|
||||
Don't forget to give the project a star! Thanks again!
|
||||
|
||||
Indexing and querying are performance sensitive tasks. Please make sure to consider allocations and performance when contributing.
|
||||
|
||||
AI Generated code is welcome and not frowned upon. Please be genuine and think critically about what you add.
|
||||
|
||||
If you just want to contribute (bless you!), see [our issues](https://github.com/bosun-ai/swiftide/issues) or join us on Discord.
|
||||
|
||||
1. Fork the Project
|
||||
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Commit your Changes (`git commit -m 'feat: Add some AmazingFeature'`)
|
||||
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
||||
5. Open a Pull Request
|
||||
|
||||
AI Agents can refer to [AGENTS.md](AGENTS.md) for workspace layout, commands, and expectations tailored to agents.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
## Core Team Members
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://github.com/timonv">
|
||||
<img
|
||||
src="https://avatars.githubusercontent.com/u/49373?s=100"
|
||||
width="100px;"
|
||||
alt=""
|
||||
/>
|
||||
<br /><sub><b>timonv</b></sub>
|
||||
<br /><sub>open for swiftide consulting</sub>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://github.com/tinco">
|
||||
<img
|
||||
src="https://avatars.githubusercontent.com/u/22532?s=100"
|
||||
width="100px;"
|
||||
alt=""
|
||||
/>
|
||||
<br /><sub><b>tinco</b></sub>
|
||||
<br /><br />
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- LICENSE -->
|
||||
|
||||
## License
|
||||
|
||||
Distributed under the MIT License. See `LICENSE` for more information.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- MARKDOWN LINKS & IMAGES -->
|
||||
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
|
||||
|
||||
[contributors-shield]: https://img.shields.io/github/contributors/bosun-ai/swiftide.svg?style=flat-square
|
||||
[contributors-url]: https://github.com/bosun-ai/swiftide/graphs/contributors
|
||||
[stars-shield]: https://img.shields.io/github/stars/bosun-ai/swiftide.svg?style=flat-square
|
||||
[stars-url]: https://github.com/bosun-ai/swiftide/stargazers
|
||||
[license-shield]: https://img.shields.io/github/license/bosun-ai/swiftide.svg?style=flat-square
|
||||
[license-url]: https://github.com/bosun-ai/swiftide/blob/master/LICENSE.txt
|
||||
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
|
||||
[linkedin-url]: https://www.linkedin.com/company/bosun-ai
|
||||
[Crate Badge]: https://img.shields.io/crates/v/swiftide?logo=rust&style=flat-square&logoColor=E05D44&color=E05D44
|
||||
[Crate]: https://crates.io/crates/swiftide
|
||||
[Docs Badge]: https://img.shields.io/docsrs/swiftide?logo=rust&style=flat-square&logoColor=E05D44
|
||||
[API Docs]: https://docs.rs/swiftide
|
||||
@@ -0,0 +1,40 @@
|
||||
cargo-features = ["edition2024"]
|
||||
|
||||
[package]
|
||||
name = "benchmarks"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
description.workspace = true
|
||||
categories.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
swiftide = { path = "../swiftide", features = ["all", "redb"] }
|
||||
serde_json = { workspace = true }
|
||||
criterion = { workspace = true, features = ["html_reports", "async_tokio"] }
|
||||
anyhow = { workspace = true }
|
||||
futures-util = { workspace = true }
|
||||
testcontainers = { workspace = true, features = ["blocking"] }
|
||||
temp-dir = { workspace = true }
|
||||
|
||||
[[bench]]
|
||||
name = "fileloader"
|
||||
path = "fileloader.rs"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "index-readme-local"
|
||||
path = "local_pipeline.rs"
|
||||
harness = false
|
||||
|
||||
|
||||
[[bench]]
|
||||
name = "node-cache"
|
||||
path = "node_cache_comparison.rs"
|
||||
harness = false
|
||||
@@ -0,0 +1,28 @@
|
||||
use std::hint::black_box;
|
||||
|
||||
use anyhow::Result;
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use futures_util::stream::{StreamExt, TryStreamExt};
|
||||
use swiftide::traits::Loader;
|
||||
|
||||
async fn run_fileloader(num_files: usize) -> Result<usize> {
|
||||
let mut total_nodes = 0;
|
||||
let mut stream = swiftide::indexing::loaders::FileLoader::new("./benchmarks/fileloader.rs")
|
||||
.with_extensions(&["rs"])
|
||||
.into_stream()
|
||||
.take(num_files);
|
||||
|
||||
while stream.try_next().await?.is_some() {
|
||||
total_nodes += 1;
|
||||
}
|
||||
assert!(total_nodes == num_files);
|
||||
Ok(total_nodes)
|
||||
}
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
c.bench_function("load_1", |b| b.iter(|| run_fileloader(black_box(1))));
|
||||
c.bench_function("load_10", |b| b.iter(|| run_fileloader(black_box(10))));
|
||||
}
|
||||
|
||||
criterion_group!(benches, criterion_benchmark);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,25 @@
|
||||
use anyhow::Result;
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use swiftide::{
|
||||
indexing::Pipeline,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::persist::MemoryStorage,
|
||||
indexing::transformers::{ChunkMarkdown, Embed},
|
||||
integrations::fastembed::FastEmbed,
|
||||
};
|
||||
|
||||
async fn run_pipeline() -> Result<()> {
|
||||
Pipeline::from_loader(FileLoader::new("README.md").with_extensions(&["md"]))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(20..256))
|
||||
.then_in_batch(Embed::new(FastEmbed::builder().batch_size(10).build()?))
|
||||
.then_store_with(MemoryStorage::default())
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
c.bench_function("run_local_pipeline", |b| b.iter(run_pipeline));
|
||||
}
|
||||
|
||||
criterion_group!(benches, criterion_benchmark);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,74 @@
|
||||
use anyhow::Result;
|
||||
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
|
||||
use swiftide::indexing::transformers::ChunkCode;
|
||||
use swiftide::{
|
||||
indexing::{Pipeline, loaders::FileLoader, persist::MemoryStorage},
|
||||
traits::NodeCache,
|
||||
};
|
||||
use temp_dir::TempDir;
|
||||
use testcontainers::Container;
|
||||
use testcontainers::{
|
||||
GenericImage,
|
||||
core::{IntoContainerPort, WaitFor},
|
||||
runners::SyncRunner,
|
||||
};
|
||||
|
||||
async fn run_pipeline(node_cache: Box<dyn NodeCache<Input = String>>) -> Result<()> {
|
||||
Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.filter_cached(node_cache)
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size("rust", 10..256)?)
|
||||
.then_store_with(MemoryStorage::default())
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
let redis_container = start_redis();
|
||||
|
||||
let redis_url = format!(
|
||||
"redis://{host}:{port}",
|
||||
host = redis_container.get_host().unwrap(),
|
||||
port = redis_container.get_host_port_ipv4(6379).unwrap()
|
||||
);
|
||||
|
||||
let redis: Box<dyn NodeCache<Input = String>> = Box::new(
|
||||
swiftide::integrations::redis::Redis::try_from_url(redis_url, "criterion").unwrap(),
|
||||
);
|
||||
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
let redb: Box<dyn NodeCache<Input = String>> = Box::new(
|
||||
swiftide::integrations::redb::Redb::builder()
|
||||
.database_path(tempdir.child("criterion"))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
for node_cache in [(redis, "redis"), (redb, "redb")] {
|
||||
c.bench_with_input(
|
||||
BenchmarkId::new("node_cache", node_cache.1),
|
||||
&node_cache,
|
||||
|b, s| {
|
||||
let cache_clone = s.0.clone();
|
||||
runtime.spawn_blocking(move || async move { cache_clone.clear().await.unwrap() });
|
||||
|
||||
b.to_async(&runtime).iter(|| run_pipeline(s.0.clone()))
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_redis() -> Container<GenericImage> {
|
||||
GenericImage::new("redis", "7.2.4")
|
||||
.with_exposed_port(6379.tcp())
|
||||
.with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))
|
||||
.start()
|
||||
.expect("Redis started")
|
||||
}
|
||||
|
||||
criterion_group!(benches, criterion_benchmark);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,6 @@
|
||||
test load_1 ... bench: 6 ns/iter (+/- 0)
|
||||
|
||||
test load_10 ... bench: 6 ns/iter (+/- 0)
|
||||
|
||||
test run_local_pipeline ... bench: 846 ns/iter (+/- 7)
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
[remote.github]
|
||||
owner = "bosun-ai"
|
||||
repo = "swiftide"
|
||||
|
||||
[git]
|
||||
commit_parsers = [
|
||||
{ message = "(r|R)elease", skip = true },
|
||||
{ message = "^(feat|fix|perf|chore)\\(ci\\)", group = "<!-- 3 -->Miscellaneous" },
|
||||
{ message = "^feat*", group = "<!-- 0 -->New features" },
|
||||
{ message = "^fix*", group = "<!-- 1 -->Bug fixes" },
|
||||
{ message = "^perf*", group = "<!-- 2 -->Performance" },
|
||||
{ message = "^chore*", group = "<!-- 3 -->Miscellaneous" },
|
||||
]
|
||||
|
||||
[changelog]
|
||||
# changelog header
|
||||
header = """
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
"""
|
||||
body = """
|
||||
{%- if not version %}
|
||||
## [unreleased]
|
||||
{% else -%}
|
||||
## [{{ version }}](https://github.com/bosun-ai/swiftide/releases/tag/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }}
|
||||
{% endif -%}
|
||||
|
||||
{% macro commit(commit) -%}
|
||||
- [{{ commit.id | truncate(length=7, end="") }}]({{ "https://github.com/bosun-ai/swiftide/commit/" ~ commit.id }}) \
|
||||
{% if commit.scope %}*({{commit.scope | default(value = "uncategorized") | lower }})* {% endif %}\
|
||||
{%- if commit.breaking %} [**breaking**]{% endif %} \
|
||||
{{ commit.message | upper_first | trim }}\
|
||||
{% if commit.remote.username %} by @{{ commit.remote.username }}{%- endif -%}\
|
||||
{%- if commit.links %} \
|
||||
in {% for link in commit.links %}[{{link.text}}]({{link.href}}) {% endfor -%}\
|
||||
{% endif %}
|
||||
{%- if commit.body and commit.remote.username and commit.remote.username is not containing("[bot]") %}
|
||||
|
||||
````text {#- 4 backticks escape any backticks in body #}
|
||||
{{commit.body | indent(prefix=" ") }}
|
||||
````
|
||||
{%- endif %}
|
||||
{%- if commit.breaking_description %}
|
||||
|
||||
**BREAKING CHANGE**: {{ commit.breaking_description }}
|
||||
|
||||
{%- endif %}
|
||||
{% endmacro -%}
|
||||
|
||||
{% for group, commits in commits | group_by(attribute="group") %}
|
||||
### {{ group | striptags | trim | upper_first }}
|
||||
{% for commit in commits | filter(attribute="scope") | sort(attribute="scope") %}
|
||||
{{ self::commit(commit=commit) }}
|
||||
{%- endfor -%}
|
||||
{% for commit in commits %}
|
||||
{%- if not commit.scope %}
|
||||
{{ self::commit(commit=commit) }}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor %}
|
||||
|
||||
{%- if github.contributors -%}
|
||||
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
|
||||
### New Contributors
|
||||
{%- endif %}\
|
||||
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
|
||||
* @{{ contributor.username }} made their first contribution
|
||||
{%- if contributor.pr_number %} in \
|
||||
[#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \
|
||||
{%- endif %}
|
||||
{%- endfor -%}
|
||||
{% endif -%}
|
||||
|
||||
{% if version %}
|
||||
{% if previous.version %}
|
||||
**Full Changelog**: {{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}
|
||||
{% endif %}
|
||||
{% else -%}
|
||||
{% raw %}\n{% endraw %}
|
||||
{% endif %}
|
||||
|
||||
{%- macro remote_url() -%}
|
||||
{%- if remote.github -%}
|
||||
https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }}\
|
||||
{% else -%}
|
||||
https://github.com/bosun-ai/swiftide
|
||||
{%- endif -%}
|
||||
{% endmacro %}
|
||||
""" # template for the changelog body
|
||||
# https://keats.github.io/tera/docs/#introduction
|
||||
# note that the - before / after the % controls whether whitespace is rendered between each line.
|
||||
# Getting this right so that the markdown renders with the correct number of lines between headings
|
||||
# code fences and list items is pretty finicky. Note also that the 4 backticks in the commit macro
|
||||
# is intentional as this escapes any backticks in the commit body.
|
||||
|
||||
|
||||
# remove the leading and trailing whitespace from the template
|
||||
trim = false
|
||||
# changelog footer
|
||||
@@ -0,0 +1,52 @@
|
||||
[graph]
|
||||
all-features = true
|
||||
|
||||
[licenses]
|
||||
confidence-threshold = 0.8
|
||||
allow = [
|
||||
"Apache-2.0",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"ISC",
|
||||
"MIT",
|
||||
"Unicode-DFS-2016",
|
||||
"MPL-2.0",
|
||||
"Apache-2.0 WITH LLVM-exception",
|
||||
"Unlicense",
|
||||
"CC0-1.0",
|
||||
"zlib-acknowledgement",
|
||||
"Zlib",
|
||||
"0BSD",
|
||||
"Unicode-3.0",
|
||||
"NCSA",
|
||||
]
|
||||
exceptions = [{ allow = ["OpenSSL"], crate = "ring" }]
|
||||
|
||||
[advisories]
|
||||
version = 2
|
||||
ignore = [
|
||||
{ id = "RUSTSEC-2023-0086", reason = "Ignore a security adivisory on lexical-core" },
|
||||
{ id = "RUSTSEC-2021-0141", reason = "Dotenv is used by spider" },
|
||||
{ id = "RUSTSEC-2024-0384", reason = "Instant is unmaintained" },
|
||||
{ id = "RUSTSEC-2024-0421", reason = "Older version of idna used by reqwest" },
|
||||
]
|
||||
|
||||
[bans]
|
||||
multiple-versions = "allow"
|
||||
|
||||
[sources]
|
||||
unknown-registry = "deny"
|
||||
unknown-git = "warn"
|
||||
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
|
||||
|
||||
[[licenses.clarify]]
|
||||
crate = "ring"
|
||||
# SPDX considers OpenSSL to encompass both the OpenSSL and SSLeay licenses
|
||||
# https://spdx.org/licenses/OpenSSL.html
|
||||
# ISC - Both BoringSSL and ring use this for their new files
|
||||
# MIT - "Files in third_party/ have their own licenses, as described therein. The MIT
|
||||
# license, for third_party/fiat, which, unlike other third_party directories, is
|
||||
# compiled into non-test libraries, is included below."
|
||||
# OpenSSL - Obviously
|
||||
expression = "ISC AND MIT AND OpenSSL"
|
||||
license-files = [{ path = "LICENSE", hash = 0xbd0eed23 }]
|
||||
@@ -0,0 +1,199 @@
|
||||
cargo-features = ["edition2024"]
|
||||
|
||||
[package]
|
||||
name = "swiftide-examples"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
description.workspace = true
|
||||
categories.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
swiftide = { path = "../swiftide/", features = [
|
||||
"all",
|
||||
"scraping",
|
||||
"aws-bedrock",
|
||||
"groq",
|
||||
"ollama",
|
||||
"fluvio",
|
||||
"kafka",
|
||||
"lancedb",
|
||||
"pgvector",
|
||||
"swiftide-agents",
|
||||
"dashscope",
|
||||
"mcp",
|
||||
"anthropic",
|
||||
"gemini",
|
||||
"metrics",
|
||||
"langfuse",
|
||||
] }
|
||||
swiftide-macros = { path = "../swiftide-macros" }
|
||||
tracing-subscriber = { workspace = true, features = ["fmt", "env-filter"] }
|
||||
serde_json = { workspace = true }
|
||||
spider = { workspace = true }
|
||||
fluvio = { workspace = true }
|
||||
temp-dir = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
futures-util = { workspace = true }
|
||||
sqlx = { workspace = true }
|
||||
swiftide-test-utils = { path = "../swiftide-test-utils" }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
rmcp = { workspace = true, features = [
|
||||
"transport-child-process",
|
||||
"client",
|
||||
"server",
|
||||
] }
|
||||
metrics = { workspace = true }
|
||||
schemars.workspace = true
|
||||
base64 = { workspace = true }
|
||||
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "index-codebase"
|
||||
path = "index_codebase.rs"
|
||||
|
||||
[[example]]
|
||||
name = "index-codebase-reduced-context"
|
||||
path = "index_codebase_reduced_context.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "fastembed"
|
||||
path = "fastembed.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "index-redis"
|
||||
path = "index_into_redis.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "index-markdown-metadata"
|
||||
path = "index_markdown_lots_of_metadata.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "scraping-index"
|
||||
path = "scraping_index_to_markdown.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "aws-bedrock"
|
||||
path = "aws_bedrock.rs"
|
||||
|
||||
[[example]]
|
||||
name = "aws-bedrock-agent"
|
||||
path = "aws_bedrock_agent.rs"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "store-multiple-vectors"
|
||||
path = "store_multiple_vectors.rs"
|
||||
|
||||
[[example]]
|
||||
name = "index-groq"
|
||||
path = "index_groq.rs"
|
||||
|
||||
[[example]]
|
||||
name = "index-ollama"
|
||||
path = "index_ollama.rs"
|
||||
|
||||
[[example]]
|
||||
name = "query-pipeline"
|
||||
path = "query_pipeline.rs"
|
||||
|
||||
[[example]]
|
||||
name = "hybrid-search"
|
||||
path = "hybrid_search.rs"
|
||||
|
||||
[[example]]
|
||||
name = "fluvio"
|
||||
path = "fluvio.rs"
|
||||
|
||||
[[example]]
|
||||
name = "kakfa"
|
||||
path = "kafka.rs"
|
||||
|
||||
[[example]]
|
||||
name = "lancedb"
|
||||
path = "lancedb.rs"
|
||||
|
||||
[[example]]
|
||||
name = "describe-image"
|
||||
path = "describe_image.rs"
|
||||
|
||||
[[example]]
|
||||
name = "hello-agents"
|
||||
path = "hello_agents.rs"
|
||||
|
||||
[[example]]
|
||||
name = "index-md-pgvector"
|
||||
path = "index_md_into_pgvector.rs"
|
||||
|
||||
[[example]]
|
||||
name = "dashscope"
|
||||
path = "dashscope.rs"
|
||||
|
||||
[[example]]
|
||||
name = "reranking"
|
||||
path = "reranking.rs"
|
||||
|
||||
[[example]]
|
||||
name = "agents-mcp"
|
||||
path = "agents_mcp_tools.rs"
|
||||
|
||||
[[example]]
|
||||
name = "agents-resume"
|
||||
path = "agents_resume.rs"
|
||||
|
||||
[[example]]
|
||||
name = "streaming-agents"
|
||||
path = "streaming_agents.rs"
|
||||
|
||||
[[example]]
|
||||
name = "agents-hitl"
|
||||
path = "agents_with_human_in_the_loop.rs"
|
||||
|
||||
[[example]]
|
||||
name = "usage-metrics"
|
||||
path = "usage_metrics.rs"
|
||||
|
||||
[[example]]
|
||||
name = "tasks"
|
||||
path = "tasks.rs"
|
||||
|
||||
[[example]]
|
||||
name = "agent-can-fail-custom-schema"
|
||||
path = "agent_can_fail_custom_schema.rs"
|
||||
|
||||
[[example]]
|
||||
name = "stop-with-args-custom-schema"
|
||||
path = "stop_with_args_custom_schema.rs"
|
||||
|
||||
[[example]]
|
||||
name = "responses-api"
|
||||
path = "responses_api.rs"
|
||||
|
||||
[[example]]
|
||||
name = "responses-api-reasoning"
|
||||
path = "responses_api_reasoning.rs"
|
||||
|
||||
[[example]]
|
||||
name = "structured-prompt"
|
||||
path = "structured_prompt.rs"
|
||||
|
||||
[[example]]
|
||||
name = "langfuse"
|
||||
path = "langfuse.rs"
|
||||
|
||||
[[example]]
|
||||
name = "tool-custom-schema"
|
||||
path = "tool_custom_schema.rs"
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Demonstrates how to replace the default failure arguments for `AgentCanFail` with a custom
|
||||
//! JSON schema and capture the structured failure payload when the agent stops.
|
||||
//!
|
||||
//! Set the `OPENAI_API_KEY` environment variable before running the example. The agent is guided
|
||||
//! to use the `task_failed` tool with the schema defined below whenever it cannot complete the
|
||||
//! task.
|
||||
use anyhow::Result;
|
||||
use schemars::{JsonSchema, Schema, schema_for};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{self, to_string_pretty};
|
||||
use swiftide::agents::tools::control::AgentCanFail;
|
||||
use swiftide::agents::{Agent, StopReason};
|
||||
use swiftide::traits::Tool;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum FailureCategory {
|
||||
MissingDependency,
|
||||
PermissionDenied,
|
||||
UnexpectedRegression,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum RemediationStatus {
|
||||
Planned,
|
||||
Blocked,
|
||||
Complete,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
struct FailureReport {
|
||||
category: FailureCategory,
|
||||
summary: String,
|
||||
impact: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
recommended_actions: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
remediation_status: Option<RemediationStatus>,
|
||||
}
|
||||
|
||||
fn failure_schema() -> Schema {
|
||||
schema_for!(FailureReport)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let schema = failure_schema();
|
||||
let failure_tool = AgentCanFail::with_parameters_schema(schema.clone());
|
||||
|
||||
println!(
|
||||
"task_failed tool schema:\n{}",
|
||||
to_string_pretty(&failure_tool.tool_spec())?,
|
||||
);
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.build()?;
|
||||
|
||||
let mut builder = Agent::builder();
|
||||
builder
|
||||
.llm(&openai)
|
||||
.tools([failure_tool.clone()])
|
||||
.on_stop(|_, reason, _| {
|
||||
Box::pin(async move {
|
||||
if let StopReason::AgentFailed(Some(payload)) = reason {
|
||||
let json = to_string_pretty(&payload).unwrap();
|
||||
println!("agent reported failure:\n{json}");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
|
||||
if let Some(prompt) = builder.system_prompt_mut() {
|
||||
prompt
|
||||
.with_role("Incident response coordinator")
|
||||
.with_guidelines([
|
||||
"If the task cannot be completed, call the `task_failed` tool using the provided JSON schema.",
|
||||
"Populate all required fields and list at least one `recommended_actions` entry.",
|
||||
"Clearly document the impact so downstream teams can prioritize remediation.",
|
||||
])
|
||||
.with_constraints(["Do not claim success when blockers remain unresolved."]);
|
||||
}
|
||||
|
||||
let mut agent = builder.build()?;
|
||||
|
||||
agent
|
||||
.query_once(
|
||||
"You must restore last night's database backup, but the only backup file is corrupted and no redundant copy exists. Report the failure.",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! This is an example of how to build a Swiftide agent with tools using the MCP protocol.
|
||||
//!
|
||||
//! The agent in this example prints all messages using a channel.
|
||||
use anyhow::Result;
|
||||
use rmcp::{
|
||||
ServiceExt as _,
|
||||
model::{ClientInfo, Implementation},
|
||||
transport::{ConfigureCommandExt as _, TokioChildProcess},
|
||||
};
|
||||
use swiftide::agents::{self, tools::mcp::McpToolbox};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
println!("Hello, agents!");
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embeddings-3-small")
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()?;
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||
|
||||
tokio::spawn(async move {
|
||||
while let Some(msg) = rx.recv().await {
|
||||
println!("{msg}");
|
||||
}
|
||||
});
|
||||
|
||||
// First set up our client info to identify ourselves to the server
|
||||
let client_info = ClientInfo {
|
||||
client_info: Implementation {
|
||||
name: "swiftide-example".into(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
title: None,
|
||||
description: None,
|
||||
icons: None,
|
||||
website_url: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Use `rmcp` to start the server
|
||||
let running_service = client_info
|
||||
.serve(TokioChildProcess::new(
|
||||
tokio::process::Command::new("npx").configure(|cmd| {
|
||||
cmd.args(["-y", "@modelcontextprotocol/server-everything"]);
|
||||
}),
|
||||
)?)
|
||||
.await?;
|
||||
|
||||
// Create a toolbox from the running server, and only use the `add` tool
|
||||
//
|
||||
// A toolbox reveals it's tools to the swiftide agent the first time it starts (if the state of
|
||||
// the agent was pending). You can add as many toolboxes as you want. MCP services are an
|
||||
// implmenentation of a toolbox. A list of tools is another.
|
||||
let everything_toolbox = McpToolbox::from_running_service(running_service)
|
||||
.with_whitelist(["add"])
|
||||
.to_owned();
|
||||
|
||||
agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
// Add the toolbox to the agent
|
||||
.add_toolbox(everything_toolbox)
|
||||
// Every message added by the agent will be printed to stdout
|
||||
.on_new_message(move |_, msg| {
|
||||
let msg = msg.to_string();
|
||||
let tx = tx.clone();
|
||||
Box::pin(async move {
|
||||
tx.send(msg).unwrap();
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.build()?
|
||||
.query("Use the add tool to add 1 and 2")
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! This example illustrates how to resume an agent from existing messages.
|
||||
use anyhow::Result;
|
||||
use swiftide::agents::{self, DefaultContext};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
println!("Hello, agents!");
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embeddings-3-small")
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()?;
|
||||
|
||||
let mut first_agent = agents::Agent::builder().llm(&openai).build()?;
|
||||
|
||||
first_agent.query("Say hello!").await?;
|
||||
|
||||
// Let's store the messages in a database, retrieve them back, and start a new agent
|
||||
let stored_history = serde_json::to_string(&first_agent.history().await?)?;
|
||||
let retrieved_history: Vec<_> = serde_json::from_str(&stored_history)?;
|
||||
|
||||
let restored_context = DefaultContext::default()
|
||||
.with_existing_messages(retrieved_history)
|
||||
.await?
|
||||
.to_owned();
|
||||
|
||||
let mut second_agent = agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
.context(restored_context)
|
||||
// We'll use the one from the first agent, alternatively we could also pop it from the
|
||||
// previous history and add a new one here
|
||||
.no_system_prompt()
|
||||
.build()?;
|
||||
|
||||
second_agent.query("What did you say?").await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! This is an example of using a human in the loop pattern with switfide agents.
|
||||
//!
|
||||
//! In the example we send the tool call over an channel, and then manually approve it.
|
||||
//!
|
||||
//! In a more realistic example, you can use other rust primitives to make it work for your
|
||||
//! usecase. I.e., make an api request with a callback url that will add the feedback.
|
||||
//!
|
||||
//! Both requesting feedback and providing feedback support an optional payload (as a
|
||||
//! `serde_json::Value`).
|
||||
//!
|
||||
//! This allows for more custom workflows, to either display or provide more input to the
|
||||
//! underlying tool call.
|
||||
//!
|
||||
//! For an example on how to implement your own custom wrappers, refer to
|
||||
//! `tools::control::ApprovalRequired`
|
||||
|
||||
use anyhow::Result;
|
||||
use swiftide::{
|
||||
agents::{self, StopReason, tools::control::ApprovalRequired},
|
||||
chat_completion::{ToolOutput, errors::ToolError},
|
||||
traits::{AgentContext, ToolFeedback},
|
||||
};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[swiftide::tool(
|
||||
description = "Guess a number",
|
||||
param(name = "number", description = "Number to guess")
|
||||
)]
|
||||
async fn guess_a_number(
|
||||
_context: &dyn AgentContext,
|
||||
number: usize,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let actual_number = 42;
|
||||
|
||||
if number == actual_number {
|
||||
Ok("You guessed it!".into())
|
||||
} else {
|
||||
Ok("Try again!".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.compact()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
println!("Hello, agents!");
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()?;
|
||||
|
||||
// ApprovalRequired is a simple wrapper. You can also implement your own approval
|
||||
// flows by returning a `ToolOutput::FeedbackRequired` in a tool,
|
||||
// you can then use `has_received_feedback` and `received_feedback` on the context
|
||||
// to build your custom workflow.
|
||||
let guess_with_approval = ApprovalRequired::new(guess_a_number());
|
||||
|
||||
let mut agent = agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
.tools(vec![guess_with_approval])
|
||||
// Every message added by the agent will be printed to stdout
|
||||
.on_new_message(move |_, msg| {
|
||||
println!("{msg}");
|
||||
|
||||
Box::pin(async move { Ok(()) })
|
||||
})
|
||||
.limit(5)
|
||||
.build()?;
|
||||
|
||||
// First query the agent, the agent will stop with a reason that feedback is required
|
||||
agent
|
||||
.query("Guess a number between 0 and 100 using the `guess_a_number` tool")
|
||||
.await?;
|
||||
|
||||
// The agent stopped, lets get the tool call
|
||||
let Some(StopReason::FeedbackRequired { tool_call, .. }) = agent.stop_reason() else {
|
||||
panic!("expected a tool call to approve")
|
||||
};
|
||||
|
||||
// Alternatively, you can also get the stop reason from the agent state
|
||||
// agent.state().stop_reason().unwrap().feedback_required().unwrap()
|
||||
|
||||
// Register that this tool call is ok.
|
||||
println!("Approving number guessing");
|
||||
agent
|
||||
.context()
|
||||
.feedback_received(tool_call, &ToolFeedback::approved())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Run the agent again and it will pick up where it stopped.
|
||||
agent.run().await.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! # [Swiftide] Aws Bedrock example
|
||||
//!
|
||||
//! This example demonstrates how to use the `AwsBedrock` v2 integration to interact with Bedrock
|
||||
//! service.
|
||||
//!
|
||||
//! To use bedrock you will need the following:
|
||||
//! - AWS cli or environment variables configured
|
||||
//! - An aws region configured
|
||||
//! - Access to the bedrock models you want to use
|
||||
//! - A model id or arn
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
//! [AWS Bedrock documentation]: https://docs.aws.amazon.com/bedrock/
|
||||
|
||||
use swiftide::{
|
||||
indexing, indexing::loaders::FileLoader, indexing::persist::MemoryStorage,
|
||||
indexing::transformers, integrations,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let aws_bedrock = integrations::aws_bedrock_v2::AwsBedrock::builder()
|
||||
.default_prompt_model("global.anthropic.claude-haiku-4-5-20251001-v1:0")
|
||||
.build()?;
|
||||
|
||||
let memory_storage = MemoryStorage::default();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("./README.md"))
|
||||
.log_nodes()
|
||||
.then_chunk(transformers::ChunkMarkdown::from_chunk_range(100..512))
|
||||
.then(transformers::MetadataSummary::new(aws_bedrock.clone()))
|
||||
.then_store_with(memory_storage.clone())
|
||||
.log_all()
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
println!("Summaries:");
|
||||
println!(
|
||||
"{}",
|
||||
memory_storage
|
||||
.get_all_values()
|
||||
.await
|
||||
.iter()
|
||||
.filter_map(|n| n.metadata.get("Summary").map(|v| v.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n---\n")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! # [Swiftide] AWS Bedrock Agent Example
|
||||
//!
|
||||
//! This example demonstrates a simple agent setup with `AwsBedrock` v2.
|
||||
//!
|
||||
//! Requirements:
|
||||
//! - AWS credentials and region configured (CLI profile or environment variables)
|
||||
//! - Access to the Bedrock model you choose
|
||||
//! - A model with tool use support (the Claude model below supports this)
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
|
||||
use anyhow::Result;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swiftide::{
|
||||
agents,
|
||||
chat_completion::{ToolOutput, errors::ToolError},
|
||||
integrations::aws_bedrock_v2::AwsBedrock,
|
||||
traits::{AgentContext, Command},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
struct FormatTimestampRequest {
|
||||
/// Prefix to prepend to the timestamp.
|
||||
prefix: String,
|
||||
/// Timestamp to format.
|
||||
timestamp: String,
|
||||
}
|
||||
|
||||
#[swiftide::tool(description = "Get the current UTC date and time in RFC3339 format")]
|
||||
async fn current_utc_time(context: &dyn AgentContext) -> Result<ToolOutput, ToolError> {
|
||||
let command_output = context
|
||||
.executor()
|
||||
.exec_cmd(&Command::shell("date -u +\"%Y-%m-%dT%H:%M:%SZ\""))
|
||||
.await?;
|
||||
|
||||
Ok(command_output.into())
|
||||
}
|
||||
|
||||
#[swiftide::tool(
|
||||
description = "Format a timestamp with a caller-provided prefix",
|
||||
param(name = "request", description = "Timestamp formatting input")
|
||||
)]
|
||||
async fn format_timestamp(
|
||||
_context: &dyn AgentContext,
|
||||
request: FormatTimestampRequest,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
Ok(ToolOutput::text(format!(
|
||||
"{}{}",
|
||||
request.prefix, request.timestamp
|
||||
)))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let bedrock = AwsBedrock::builder()
|
||||
.default_prompt_model("global.anthropic.claude-sonnet-4-6")
|
||||
.build()?;
|
||||
|
||||
let mut agent = agents::Agent::builder()
|
||||
.llm(&bedrock)
|
||||
.tools(vec![current_utc_time(), format_timestamp()])
|
||||
.on_new_message(|_, msg| {
|
||||
let rendered = msg.to_string();
|
||||
Box::pin(async move {
|
||||
println!("{rendered}");
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.limit(6)
|
||||
.build()?;
|
||||
|
||||
agent
|
||||
.query(
|
||||
"Call current_utc_time once. Then call format_timestamp with prefix \"UTC now: \" and \
|
||||
that timestamp. After that, report the formatted result and stop.",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self, EmbeddedField,
|
||||
loaders::FileLoader,
|
||||
transformers::{ChunkMarkdown, Embed, MetadataQAText, metadata_qa_text},
|
||||
},
|
||||
integrations::{dashscope::DashscopeBuilder, lancedb::LanceDB},
|
||||
query::{
|
||||
self,
|
||||
answers::{self},
|
||||
query_transformers::{self},
|
||||
response_transformers,
|
||||
},
|
||||
};
|
||||
use temp_dir::TempDir;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let client = DashscopeBuilder::default()
|
||||
.default_embed_model("text-embedding-v2")
|
||||
.default_prompt_model("qwen-long")
|
||||
.build()?;
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
let lancedb = LanceDB::builder()
|
||||
.uri(tempdir.child("lancedb").to_str().unwrap())
|
||||
.vector_size(1536)
|
||||
.with_vector(EmbeddedField::Combined)
|
||||
.with_metadata(metadata_qa_text::NAME)
|
||||
.table_name("swiftide_test")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["md"]))
|
||||
.with_default_llm_client(client.clone())
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(client.clone()))
|
||||
.then_in_batch(Embed::new(client.clone()).with_batch_size(10))
|
||||
.then_store_with(lancedb.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
let pipeline = query::Pipeline::default()
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
client.clone(),
|
||||
))
|
||||
.then_transform_query(query_transformers::Embed::from_client(client.clone()))
|
||||
.then_retrieve(lancedb.clone())
|
||||
.then_transform_response(response_transformers::Summary::from_client(client.clone()))
|
||||
.then_answer(answers::Simple::from_client(client.clone()));
|
||||
|
||||
let result = pipeline
|
||||
.query("What is swiftide? Please provide an elaborate explanation")
|
||||
.await?;
|
||||
|
||||
println!("====");
|
||||
println!("{:?}", result.answer());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Demonstrates passing an image to Chat Completions using a data URL.
|
||||
//!
|
||||
//! Set the `OPENAI_API_KEY` environment variable before running.
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use swiftide::chat_completion::{ChatCompletionRequest, ChatMessage, ChatMessageContentPart};
|
||||
use swiftide::traits::ChatCompletion;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()?;
|
||||
|
||||
let image_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../images/logo.png");
|
||||
let image_bytes = std::fs::read(&image_path).with_context(|| format!("Read {image_path:?}"))?;
|
||||
let encoded = general_purpose::STANDARD.encode(&image_bytes);
|
||||
let data_url = format!("data:image/png;base64,{encoded}");
|
||||
|
||||
let message = ChatMessage::new_user_with_parts(vec![
|
||||
ChatMessageContentPart::text("Describe this image in one sentence."),
|
||||
ChatMessageContentPart::image(data_url),
|
||||
]);
|
||||
|
||||
let request = ChatCompletionRequest::builder()
|
||||
.messages(vec![message])
|
||||
.build()?;
|
||||
|
||||
let response = openai.complete(&request).await?;
|
||||
println!(
|
||||
"Image description: {}",
|
||||
response.message().unwrap_or("<no response>")
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! # [Swiftide] Indexing the Swiftide itself example
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself using FastEmbed.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load all `.rs` files from the current directory
|
||||
//! - Embed the chunks in batches of 10 using FastEmbed
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::transformers::Embed,
|
||||
integrations::{fastembed::FastEmbed, qdrant::Qdrant},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let qdrant_url = std::env::var("QDRANT_URL")
|
||||
.as_deref()
|
||||
.unwrap_or("http://localhost:6334")
|
||||
.to_owned();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.then_in_batch(Embed::new(FastEmbed::builder().batch_size(10).build()?))
|
||||
.then_store_with(
|
||||
Qdrant::try_from_url(qdrant_url)?
|
||||
.batch_size(50)
|
||||
.vector_size(384)
|
||||
.collection_name("swiftide-examples-fastembed".to_string())
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//! # [Swiftide] Loading data from Fluvio
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself.
|
||||
//! Note that for it to work correctly you need to have OPENAI_API_KEY set, redis and qdrant
|
||||
//! running.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load all `.rs` files from the current directory
|
||||
//! - Skip any nodes previously processed; hashes are based on the path and chunk (not the
|
||||
//! metadata!)
|
||||
//! - Run metadata QA on each chunk; generating questions and answers and adding metadata
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! Note that metadata is copied over to smaller chunks when chunking. When making LLM requests
|
||||
//! with lots of small chunks, consider the rate limits of the API.
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing::{self, transformers::Embed},
|
||||
integrations::{
|
||||
fastembed::FastEmbed,
|
||||
fluvio::{ConsumerConfigExt, Fluvio},
|
||||
qdrant::Qdrant,
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
static TOPIC_NAME: &str = "hello-rust";
|
||||
static PARTITION_NUM: u32 = 0;
|
||||
|
||||
let loader = Fluvio::builder()
|
||||
.consumer_config_ext(
|
||||
ConsumerConfigExt::builder()
|
||||
.topic(TOPIC_NAME)
|
||||
.partition(PARTITION_NUM)
|
||||
.offset_start(fluvio::Offset::from_end(1))
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
indexing::Pipeline::from_loader(loader)
|
||||
.then_in_batch(Embed::new(FastEmbed::try_default().unwrap()).with_batch_size(10))
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(384)
|
||||
.collection_name("swiftide-examples")
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! This is an example of how to build a Swiftide agent
|
||||
//!
|
||||
//! A swiftide agent runs completions in a loop, optionally with tools, to complete a task
|
||||
//! autonomously. Agents stop when either the LLM calls the always included `stop` tool, or
|
||||
//! (configurable) if the last message in the completion chain was from the assistant.
|
||||
//!
|
||||
//! Tools can be created by using the `tool` attribute macro as shown here. For more control (i.e.
|
||||
//! internal state), there
|
||||
//! is also a `Tool` derive macro for convenience. Anything that implements the `Tool` trait can
|
||||
//! act as a tool.
|
||||
//!
|
||||
//! Agents operate on an `AgentContext`, which is responsible for managaging the completion history
|
||||
//! and providing access to the outside world. For the latter, the context is expected to have a
|
||||
//! `ToolExecutor`, which by default runs locally.
|
||||
//!
|
||||
//! When building the agent, hooks are available to influence the state, completions, and general
|
||||
//! behaviour of the agent. Hooks are also traits.
|
||||
//!
|
||||
//! Refer to the api documentation for more detailed information.
|
||||
use anyhow::Result;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swiftide::{
|
||||
agents,
|
||||
chat_completion::{ToolOutput, errors::ToolError},
|
||||
traits::{AgentContext, Command},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
struct CodeSearchRequest {
|
||||
/// Search query to pass to ripgrep
|
||||
query: String,
|
||||
/// Optional repository root (defaults to the current working directory)
|
||||
repo: Option<String>,
|
||||
/// Optional list of glob filters for the search
|
||||
file_globs: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[swiftide::tool(
|
||||
description = "Searches code",
|
||||
param(name = "request", description = "Code search parameters")
|
||||
)]
|
||||
async fn search_code(
|
||||
context: &dyn AgentContext,
|
||||
request: CodeSearchRequest,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let repo = request.repo.as_deref().unwrap_or(".");
|
||||
let mut command = format!("cd {repo} && rg '{query}'", query = request.query);
|
||||
|
||||
if let Some(globs) = &request.file_globs {
|
||||
for glob in globs {
|
||||
command.push_str(&format!(" -g '{glob}'"));
|
||||
}
|
||||
}
|
||||
|
||||
let command_output = context
|
||||
.executor()
|
||||
.exec_cmd(&Command::shell(command))
|
||||
.await?;
|
||||
|
||||
Ok(command_output.into())
|
||||
}
|
||||
|
||||
const READ_FILE: &str = "Read a file";
|
||||
|
||||
#[swiftide::tool(
|
||||
description = READ_FILE,
|
||||
param(name = "path", description = "Path to the file")
|
||||
)]
|
||||
async fn read_file(context: &dyn AgentContext, path: &str) -> Result<ToolOutput, ToolError> {
|
||||
let command_output = context
|
||||
.executor()
|
||||
.exec_cmd(&Command::shell(format!("cat {path}")))
|
||||
.await?;
|
||||
|
||||
Ok(command_output.into())
|
||||
}
|
||||
|
||||
// The macro understands common Rust types (strings, numbers, bools, vectors, maps, structs, etc.)
|
||||
// and automatically derives a JSON Schema via `schemars`. If you need to tweak the schema
|
||||
// manually, implement the `Tool` trait and attach your own `parameters_schema`.
|
||||
//
|
||||
#[swiftide::tool(
|
||||
description = "Guess a number",
|
||||
param(name = "number", description = "Number to guess")
|
||||
)]
|
||||
async fn guess_a_number(
|
||||
_context: &dyn AgentContext,
|
||||
number: usize,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let actual_number = 42;
|
||||
|
||||
if number == actual_number {
|
||||
Ok("You guessed it!".into())
|
||||
} else {
|
||||
Ok("Try again!".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
println!("Hello, agents!");
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai = swiftide::integrations::gemini::Gemini::builder()
|
||||
.default_embed_model("gemini-embedding-exp-03-07")
|
||||
.default_prompt_model("gemini-2.0-flash")
|
||||
.build()?;
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||
|
||||
tokio::spawn(async move {
|
||||
while let Some(msg) = rx.recv().await {
|
||||
println!("{msg}");
|
||||
}
|
||||
});
|
||||
|
||||
agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
.tools(vec![search_code(), read_file(), guess_a_number()])
|
||||
.before_all(move |_context| {
|
||||
// This is a hook that runs before any command is executed
|
||||
// No native async closures in Rust yet, so we have to use Box::pin
|
||||
Box::pin(async move {
|
||||
println!("Hello hook!");
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
// Every message added by the agent will be printed to stdout
|
||||
.on_new_message(move |_, msg| {
|
||||
let msg = msg.to_string();
|
||||
let tx = tx.clone();
|
||||
Box::pin(async move {
|
||||
tx.send(msg).unwrap();
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.limit(5)
|
||||
.build()?
|
||||
.query("In what file can I find an example of a swiftide agent? When you are done guess a number and stop")
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! # [Swiftide] Hybrid search with qudrant
|
||||
//!
|
||||
//! This example demonstrates how to do hybrid search with Qdrant with Sparse vectors.
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self, EmbeddedField,
|
||||
loaders::FileLoader,
|
||||
transformers::{self, ChunkCode, MetadataQACode},
|
||||
},
|
||||
integrations::{fastembed::FastEmbed, openai, qdrant::Qdrant},
|
||||
query::{self, answers, query_transformers, search_strategies::HybridSearch},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Ensure all batching is consistent
|
||||
let batch_size = 64;
|
||||
|
||||
let fastembed_sparse = FastEmbed::try_default_sparse().unwrap().to_owned();
|
||||
let fastembed = FastEmbed::try_default().unwrap().to_owned();
|
||||
|
||||
// Set up openai with the mini model, which is great for indexing
|
||||
let openai = openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
// Set up qdrant and use the combined fields (metadata + chunks) for both sparse and dense
|
||||
// vectors
|
||||
let qdrant = Qdrant::builder()
|
||||
.batch_size(batch_size)
|
||||
.vector_size(384)
|
||||
.with_vector(EmbeddedField::Combined)
|
||||
.with_sparse_vector(EmbeddedField::Combined)
|
||||
.collection_name("swiftide-hybrid-example")
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("swiftide-core/").with_extensions(&["rs"]))
|
||||
// Chunk fairly large as the context window is big
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size(
|
||||
"rust",
|
||||
10..2048,
|
||||
)?)
|
||||
// Generate metadata on the code chunks to increase our chances of finding the right code
|
||||
.then(MetadataQACode::from_client(openai.clone()).build().unwrap())
|
||||
.then_in_batch(
|
||||
transformers::SparseEmbed::new(fastembed_sparse.clone()).with_batch_size(batch_size),
|
||||
)
|
||||
.then_in_batch(transformers::Embed::new(fastembed.clone()).with_batch_size(batch_size))
|
||||
.then_store_with(qdrant.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
// Use sophisticated model for our query
|
||||
let openai = openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let query_pipeline = query::Pipeline::from_search_strategy(
|
||||
// Return a large amount of documents because we have a large context window
|
||||
// By default it uses the Combined fields, no need to configure
|
||||
HybridSearch::default()
|
||||
.with_top_n(20)
|
||||
.with_top_k(20)
|
||||
.to_owned(),
|
||||
)
|
||||
// Generate subquestions on the initial query to increase our query coverage
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
openai.clone(),
|
||||
))
|
||||
// Generate the same embeddings we used for indexing
|
||||
.then_transform_query(query_transformers::Embed::from_client(fastembed.clone()))
|
||||
.then_transform_query(query_transformers::SparseEmbed::from_client(
|
||||
fastembed_sparse.clone(),
|
||||
))
|
||||
.then_retrieve(qdrant.clone())
|
||||
// Answer with Simple, which either takes the documents as is (in this case), or any
|
||||
// transformations applied after querying
|
||||
.then_answer(answers::Simple::from_client(openai.clone()));
|
||||
|
||||
let answer = query_pipeline
|
||||
.query("What are the different pipelines in Swiftide and how do they work? Provide an elaborate answer with examples.")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
println!("{}", answer.answer());
|
||||
|
||||
// ## Different Pipelines in Swiftide and How They Work
|
||||
//
|
||||
// Swiftide offers multiple pipelines, notably the indexing pipeline and the query pipeline. The
|
||||
// functionality of these pipelines is enhanced using traits and components like transformers,
|
||||
// stream handlers, and more. Below we elaborate on the key components and how they become part
|
||||
// of the larger pipeline system:
|
||||
//
|
||||
// ### Indexing Pipeline
|
||||
//
|
||||
// 1. **Transformers**:
|
||||
// - **Transformer Trait**: Transforms single nodes into single nodes. Mainly used for
|
||||
// transforming data in a singular manner.
|
||||
// - **BatchableTransformer Trait**: Transforms a batch of nodes into a stream of nodes,
|
||||
// useful for bulk processing.
|
||||
//
|
||||
// ```rust
|
||||
// #[async_trait]
|
||||
// pub trait Transformer: Send + Sync {
|
||||
// async fn transform_node(&self, node: Node) -> Result<Node>;
|
||||
// fn concurrency(&self) -> Option<usize> { None }
|
||||
// }
|
||||
//
|
||||
// #[async_trait]
|
||||
// impl<F> Transformer for F where F: Fn(Node) -> Result<Node> + Send + Sync {
|
||||
// async fn transform_node(&self, node: Node) -> Result<Node> {
|
||||
// self(node)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// #[async_trait]
|
||||
// pub trait BatchableTransformer: Send + Sync {
|
||||
// async fn batch_transform(&self, nodes: Vec<Node>) -> IndexingStream;
|
||||
// fn concurrency(&self) -> Option<usize> { None }
|
||||
// }
|
||||
//
|
||||
// #[async_trait]
|
||||
// impl<F> BatchableTransformer for F where F: Fn(Vec<Node>) -> IndexingStream + Send + Sync
|
||||
// { async fn batch_transform(&self, nodes: Vec<Node>) -> IndexingStream {
|
||||
// self(nodes)
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// 2. **Loaders**:
|
||||
// - Defines methods for converting a loader into an `IndexingStream`.
|
||||
//
|
||||
// ```rust
|
||||
// pub trait Loader {
|
||||
// fn into_stream(self) -> IndexingStream;
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// 3. **Chunker Transformers**:
|
||||
// - Splits one node into multiple nodes. It's useful for breaking down large nodes into
|
||||
// smaller, manageable chunks.
|
||||
//
|
||||
// ```rust
|
||||
// #[async_trait]
|
||||
// pub trait ChunkerTransformer: Send + Sync + Debug {
|
||||
// async fn transform_node(&self, node: Node) -> IndexingStream;
|
||||
// fn concurrency(&self) -> Option<usize> { None }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// 4. **IndexingStream**:
|
||||
// - An asynchronous stream of nodes, used internally by the indexing pipeline to handle
|
||||
// streams of `Node` items.
|
||||
//
|
||||
// ```rust
|
||||
// pub struct IndexingStream {
|
||||
// #[pin]
|
||||
// pub(crate) inner: Pin<Box<dyn Stream<Item = Result<Node>> + Send>>,
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// ### Query Pipeline
|
||||
//
|
||||
// 1. **QueryStream**:
|
||||
// - Handles query streams, ensuring data flows correctly through various query states.
|
||||
//
|
||||
// ```rust
|
||||
// pub struct QueryStream<'stream, Q: 'stream> {
|
||||
// #[pin]
|
||||
// pub(crate) inner: Pin<Box<dyn Stream<Item = Result<Query<Q>>> + Send + 'stream>>,
|
||||
// #[pin]
|
||||
// pub sender: Option<Sender<Result<Query<Q>>>>,
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// 2. **Query Handling**:
|
||||
// - Various state transitions and handling for queries in the pipeline.
|
||||
//
|
||||
// ```rust
|
||||
// pub struct Query<State> {
|
||||
// original: String,
|
||||
// current: String,
|
||||
// state: State,
|
||||
// transformation_history: Vec<TransformationEvent>,
|
||||
// pub embedding: Option<Embedding>,
|
||||
// pub sparse_embedding: Option<SparseEmbedding>,
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// ### Extending the Pipeline with Traits
|
||||
//
|
||||
// Swiftide allows developers to extend the pipeline by implementing custom transformers,
|
||||
// loaders, and other components by implementing the respective traits. This design ensures
|
||||
// flexibility and modularity, allowing seamless integration of custom functionality.
|
||||
//
|
||||
// For example, to create a custom transformer:
|
||||
// ```rust
|
||||
// use crate::node::Node;
|
||||
// use anyhow::Result;
|
||||
//
|
||||
// struct MyCustomTransformer;
|
||||
//
|
||||
// #[async_trait]
|
||||
// impl Transformer for MyCustomTransformer {
|
||||
// async fn transform_node(&self, node: Node) -> Result<Node> {
|
||||
// // Custom transformation logic here...
|
||||
// Ok(node)
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// ### Usage of Prompts in Transformers
|
||||
//
|
||||
// Swiftide utilizes the [`Template`] for templating prompts, making it easy to define and
|
||||
// manage prompts within transformers.
|
||||
//
|
||||
// ```rust
|
||||
// let template = PromptTemplate::try_compiled_from_str("hello {{world}}").await.unwrap();
|
||||
// let prompt = template.to_prompt().with_context_value("world", "swiftide");
|
||||
// assert_eq!(prompt.render().await.unwrap(), "hello swiftide");
|
||||
// ```
|
||||
//
|
||||
// ### Conclusion
|
||||
//
|
||||
// The Indexing and Query Pipelines in Swiftide are made extensible and modular via traits such
|
||||
// as `Transformer`, `BatchableTransformer`, `Loader`, and more. Custom implementations can
|
||||
// seamlessly integrate into the pipeline, providing flexibility in how data is processed,
|
||||
// transformed, and indexed. The use of prompts further enhances the capability to manage
|
||||
// dynamic and templated data within these pipelines.
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! # [Swiftide] Indexing the Swiftide itself example
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself.
|
||||
//! Note that for it to work correctly you need to have OPENAI_API_KEY set, redis and qdrant
|
||||
//! running.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load all `.rs` files from the current directory
|
||||
//! - Skip any nodes previously processed; hashes are based on the path and chunk (not the
|
||||
//! metadata!)
|
||||
//! - Run metadata QA on each chunk; generating questions and answers and adding metadata
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! Note that metadata is copied over to smaller chunks when chunking. When making LLM requests
|
||||
//! with lots of small chunks, consider the rate limits of the API.
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::LanguageModelWithBackOff,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::transformers::{ChunkCode, Embed, MetadataQACode},
|
||||
integrations::{self, qdrant::Qdrant, redis::Redis},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-3.5-turbo")
|
||||
.build()?;
|
||||
|
||||
// Optionally use the backoff decorator to handle rate limits and transient errors.
|
||||
//
|
||||
// This works with streaming as well, async openai does not support this properly yet.
|
||||
let openai_client = LanguageModelWithBackOff::new(openai_client, Default::default());
|
||||
|
||||
let redis_url = std::env::var("REDIS_URL")
|
||||
.as_deref()
|
||||
.unwrap_or("redis://localhost:6379")
|
||||
.to_owned();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.filter_cached(Redis::try_from_url(redis_url, "swiftide-examples")?)
|
||||
.then(MetadataQACode::new(openai_client.clone()))
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size(
|
||||
"rust",
|
||||
10..2048,
|
||||
)?)
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.collection_name("swiftide-examples")
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! # [Swiftide] Indexing the Swiftide itself example with reduced context size
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself, optimizing for a smaller
|
||||
//! context size. Note that for it to work correctly you need to have OPENAI_API_KEY set, redis and
|
||||
//! qdrant running.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load all `.rs` files from the current directory
|
||||
//! - Skip any nodes previously processed; hashes are based on the path and chunk (not the
|
||||
//! metadata!)
|
||||
//! - Generate an outline of the symbols defined in each file to be used as context in a later step
|
||||
//! and store it in the metadata
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - For each chunk, generate a condensed subset of the symbols outline tailored for that specific
|
||||
//! chunk and store that in the metadata
|
||||
//! - Run metadata QA on each chunk; generating questions and answers and adding metadata
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! Note that metadata is copied over to smaller chunks when chunking. When making LLM requests
|
||||
//! with lots of small chunks, consider the rate limits of the API.
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::indexing;
|
||||
use swiftide::indexing::loaders::FileLoader;
|
||||
use swiftide::indexing::transformers::{ChunkCode, Embed, MetadataQACode};
|
||||
use swiftide::integrations::{self, qdrant::Qdrant, redis::Redis};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-3.5-turbo")
|
||||
.build()?;
|
||||
|
||||
let redis_url = std::env::var("REDIS_URL")
|
||||
.as_deref()
|
||||
.unwrap_or("redis://localhost:6379")
|
||||
.to_owned();
|
||||
|
||||
let chunk_size = 2048;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.filter_cached(Redis::try_from_url(
|
||||
redis_url,
|
||||
"swiftide-examples-codebase-reduced-context",
|
||||
)?)
|
||||
.then(
|
||||
indexing::transformers::OutlineCodeTreeSitter::try_for_language(
|
||||
"rust",
|
||||
Some(chunk_size),
|
||||
)?,
|
||||
)
|
||||
.then(MetadataQACode::new(openai_client.clone()))
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size(
|
||||
"rust",
|
||||
10..chunk_size,
|
||||
)?)
|
||||
.then(indexing::transformers::CompressCodeOutline::new(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.collection_name("swiftide-examples-codebase-reduced-context")
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! # [Swiftide] Indexing with Groq
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself.
|
||||
//! Note that for it to work correctly you need to have set the GROQ_API_KEY
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Loads the readme from the project
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - Run metadata QA on each chunk with Groq; generating questions and answers and adding metadata
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Memory Storage
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::persist::MemoryStorage,
|
||||
indexing::transformers::{ChunkMarkdown, Embed, MetadataQAText},
|
||||
integrations,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let groq_client = integrations::groq::Groq::builder()
|
||||
.default_prompt_model("llama3-8b-8192")
|
||||
.to_owned()
|
||||
.build()?;
|
||||
|
||||
let fastembed = integrations::fastembed::FastEmbed::try_default()?;
|
||||
let memory_store = MemoryStorage::default();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md"))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(groq_client.clone()))
|
||||
.then_in_batch(Embed::new(fastembed).with_batch_size(10))
|
||||
.then_store_with(memory_store.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
println!("Example results:");
|
||||
println!(
|
||||
"{}",
|
||||
memory_store
|
||||
.get_all_values()
|
||||
.await
|
||||
.into_iter()
|
||||
.flat_map(|n| n.metadata.into_values().map(|v| v.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! # [Swiftide] Indexing the Swiftide itself example
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself.
|
||||
//! Note that for it to work correctly you need to have OPENAI_API_KEY set, redis and qdrant
|
||||
//! running.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load all `.rs` files from the current directory
|
||||
//! - Skip any nodes previously processed; hashes are based on the path and chunk (not the
|
||||
//! metadata!)
|
||||
//! - Run metadata QA on each chunk; generating questions and answers and adding metadata
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! Note that metadata is copied over to smaller chunks when chunking. When making LLM requests
|
||||
//! with lots of small chunks, consider the rate limits of the API.
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing, indexing::loaders::FileLoader, indexing::transformers::ChunkCode,
|
||||
integrations::redis::Redis,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let redis_url = std::env::var("REDIS_URL")
|
||||
.as_deref()
|
||||
.unwrap_or("redis://localhost:6379")
|
||||
.to_owned();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["rs"]))
|
||||
.then_chunk(ChunkCode::try_for_language_and_chunk_size(
|
||||
"rust",
|
||||
10..2048,
|
||||
)?)
|
||||
.then_store_with(
|
||||
// By default the value is the full node serialized to JSON.
|
||||
// We can customize this by providing a custom function.
|
||||
Redis::try_build_from_url(&redis_url)?
|
||||
.persist_value_fn(|node| Ok(serde_json::to_string(&node.metadata)?))
|
||||
.batch_size(50)
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! # [Swiftide] Indexing the Swiftide README with lots of metadata
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide README with lots of metadata.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load the README.md file from the current directory
|
||||
//! - Chunk the file into pieces of 20 to 1024 bytes
|
||||
//! - Generate questions and answers for each chunk
|
||||
//! - Generate a summary for each chunk
|
||||
//! - Generate a title for each chunk
|
||||
//! - Generate keywords for each chunk
|
||||
//! - Embed each chunk
|
||||
//! - Store the nodes in Qdrant
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::transformers::{
|
||||
ChunkMarkdown, Embed, MetadataKeywords, MetadataQAText, MetadataSummary, MetadataTitle,
|
||||
},
|
||||
integrations::{self, qdrant::Qdrant},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md").with_extensions(&["md"]))
|
||||
.with_concurrency(1)
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(20..2048))
|
||||
.then(MetadataQAText::new(openai_client.clone()))
|
||||
.then(MetadataSummary::new(openai_client.clone()))
|
||||
.then(MetadataTitle::new(openai_client.clone()))
|
||||
.then(MetadataKeywords::new(openai_client.clone()))
|
||||
.then_in_batch(Embed::new(openai_client.clone()))
|
||||
.log_all()
|
||||
.filter_errors()
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.collection_name("swiftide-examples")
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/// This example demonstrates how to index markdown into PGVector
|
||||
use std::path::PathBuf;
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self, EmbeddedField,
|
||||
loaders::FileLoader,
|
||||
transformers::{
|
||||
ChunkMarkdown, Embed, MetadataQAText, metadata_qa_text::NAME as METADATA_QA_TEXT_NAME,
|
||||
},
|
||||
},
|
||||
integrations::{self, fastembed::FastEmbed, pgvector::PgVector},
|
||||
query::{self, answers, query_transformers, response_transformers},
|
||||
traits::SimplePrompt,
|
||||
};
|
||||
|
||||
async fn ask_query(
|
||||
llm_client: impl SimplePrompt + Clone + 'static,
|
||||
embed: FastEmbed,
|
||||
vector_store: PgVector,
|
||||
questions: Vec<String>,
|
||||
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
||||
// By default the search strategy is SimilaritySingleEmbedding
|
||||
// which takes the latest query, embeds it, and does a similarity search
|
||||
//
|
||||
// Pgvector will return an error if multiple embeddings are set
|
||||
//
|
||||
// The pipeline generates subquestions to increase semantic coverage, embeds these in a single
|
||||
// embedding, retrieves the default top_k documents, summarizes them and uses that as context
|
||||
// for the final answer.
|
||||
let pipeline = query::Pipeline::default()
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
llm_client.clone(),
|
||||
))
|
||||
.then_transform_query(query_transformers::Embed::from_client(embed))
|
||||
.then_retrieve(vector_store.clone())
|
||||
.then_transform_response(response_transformers::Summary::from_client(
|
||||
llm_client.clone(),
|
||||
))
|
||||
.then_answer(answers::Simple::from_client(llm_client.clone()));
|
||||
|
||||
let results: Vec<String> = pipeline
|
||||
.query_all(questions)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|result| result.answer().to_string())
|
||||
.collect();
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
tracing::info!("Starting PgVector indexing test");
|
||||
|
||||
// Get the manifest directory path
|
||||
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
|
||||
|
||||
// Create a PathBuf to test dataset from the manifest directory
|
||||
let test_dataset_path = PathBuf::from(manifest_dir).join("../README.md");
|
||||
|
||||
tracing::info!("Test Dataset path: {:?}", test_dataset_path);
|
||||
|
||||
let (_pgv_db_container, pgv_db_url) = swiftide_test_utils::start_postgres().await;
|
||||
|
||||
tracing::info!("pgv_db_url :: {:#?}", pgv_db_url);
|
||||
|
||||
let llm_client = integrations::ollama::Ollama::default()
|
||||
.with_default_prompt_model("llama3.2:latest")
|
||||
.to_owned();
|
||||
|
||||
let fastembed =
|
||||
integrations::fastembed::FastEmbed::try_default().expect("Could not create FastEmbed");
|
||||
|
||||
// Configure Pgvector with a default vector size, a single embedding
|
||||
// and in addition to embedding the text metadata, also store it in a field
|
||||
let pgv_storage = PgVector::builder()
|
||||
.db_url(pgv_db_url)
|
||||
.vector_size(384)
|
||||
.with_vector(EmbeddedField::Combined)
|
||||
.with_metadata(METADATA_QA_TEXT_NAME)
|
||||
.table_name("swiftide_pgvector_test".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
// Drop the existing test table before running the test
|
||||
tracing::info!("Dropping existing test table & index if it exists");
|
||||
let drop_table_sql = "DROP TABLE IF EXISTS swiftide_pgvector_test";
|
||||
let drop_index_sql = "DROP INDEX IF EXISTS swiftide_pgvector_test_embedding_idx";
|
||||
|
||||
if let Ok(pool) = pgv_storage.get_pool().await {
|
||||
sqlx::query(drop_table_sql).execute(pool).await?;
|
||||
sqlx::query(drop_index_sql).execute(pool).await?;
|
||||
} else {
|
||||
return Err("Failed to get database connection pool".into());
|
||||
}
|
||||
|
||||
tracing::info!("Starting indexing pipeline");
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(test_dataset_path).with_extensions(&["md"]))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(llm_client.clone()))
|
||||
.then_in_batch(Embed::new(fastembed.clone()).with_batch_size(100))
|
||||
.then_store_with(pgv_storage.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
tracing::info!("PgVector Indexing completed successfully");
|
||||
|
||||
let questions: Vec<String> = vec![
|
||||
"What is SwiftIDE? Provide a clear, comprehensive summary in under 50 words.".into(),
|
||||
"How can I use SwiftIDE to connect with the Ethereum blockchain? Please provide a concise, comprehensive summary in less than 50 words.".into(),
|
||||
];
|
||||
|
||||
ask_query(
|
||||
llm_client.clone(),
|
||||
fastembed.clone(),
|
||||
pgv_storage.clone(),
|
||||
questions,
|
||||
)
|
||||
.await?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.for_each(|(i, result)| {
|
||||
tracing::info!("*** Answer Q{} ***", i + 1);
|
||||
tracing::info!("{}", result);
|
||||
tracing::info!("===X===");
|
||||
});
|
||||
|
||||
tracing::info!("PgVector Indexing & retrieval test completed successfully");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! # [Swiftide] Indexing with Ollama
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide codebase itself.
|
||||
//! Note that for it to work correctly you need to have ollama running on the default local port.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Loads the readme from the project
|
||||
//! - Chunk the code into pieces of 10 to 2048 bytes
|
||||
//! - Run metadata QA on each chunk with Ollama; generating questions and answers and adding
|
||||
//! metadata
|
||||
//! - Embed the chunks in batches of 10, Metadata is embedded by default
|
||||
//! - Store the nodes in Memory Storage
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::persist::MemoryStorage,
|
||||
indexing::transformers::{ChunkMarkdown, Embed, MetadataQAText},
|
||||
integrations,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let ollama_client = integrations::ollama::Ollama::default()
|
||||
.with_default_prompt_model("llama3.1")
|
||||
.to_owned();
|
||||
|
||||
let fastembed = integrations::fastembed::FastEmbed::try_default()?;
|
||||
let memory_store = MemoryStorage::default();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md"))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(ollama_client.clone()))
|
||||
.then_in_batch(Embed::new(fastembed).with_batch_size(10))
|
||||
.then_store_with(memory_store.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
println!("Example results:");
|
||||
println!(
|
||||
"{}",
|
||||
memory_store
|
||||
.get_all_values()
|
||||
.await
|
||||
.into_iter()
|
||||
.flat_map(|n| n.metadata.into_values().map(|v| v.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! # [Swiftide] Loading data from Kafka
|
||||
//!
|
||||
//! This example demonstrates how to index data from a Kafka topic and store the data in another
|
||||
//! Kafka topic. Note that for it to work correctly you need to have kafka.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load messages from a Kafka topic
|
||||
//! - Embed the chunks in batches of 10
|
||||
//! - Store the nodes in kafka
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing::{self, transformers::Embed},
|
||||
integrations::{
|
||||
fastembed::FastEmbed,
|
||||
kafka::{ClientConfig, Kafka},
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
static LOADER_TOPIC: &str = "loader";
|
||||
static STORAGE_TOPIC: &str = "storage";
|
||||
|
||||
let mut client_config = ClientConfig::new();
|
||||
client_config.set("bootstrap.servers", "localhost:9092");
|
||||
client_config.set("group.id", "group_id");
|
||||
client_config.set("auto.offset.reset", "earliest");
|
||||
|
||||
let loader = Kafka::builder()
|
||||
.client_config(client_config.clone())
|
||||
.topic(LOADER_TOPIC)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let storage = Kafka::builder()
|
||||
.client_config(client_config)
|
||||
.topic(STORAGE_TOPIC)
|
||||
.create_topic_if_not_exists(true)
|
||||
.batch_size(2usize)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
indexing::Pipeline::from_loader(loader)
|
||||
.then_in_batch(Embed::new(FastEmbed::try_default().unwrap()).with_batch_size(10))
|
||||
.then_store_with(storage)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/// This example demonstrates how to use the LanceDB integration with Swiftide
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self, EmbeddedField,
|
||||
loaders::FileLoader,
|
||||
transformers::{
|
||||
ChunkMarkdown, Embed, MetadataQAText, metadata_qa_text::NAME as METADATA_QA_TEXT_NAME,
|
||||
},
|
||||
},
|
||||
integrations::{self, lancedb::LanceDB},
|
||||
query::{self, answers, query_transformers, response_transformers},
|
||||
};
|
||||
use temp_dir::TempDir;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()?;
|
||||
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
|
||||
// Configure lancedb with a default vector size, a single embedding
|
||||
// and in addition to embedding the text metadata, also store it in a field
|
||||
let lancedb = LanceDB::builder()
|
||||
.uri(tempdir.child("lancedb").to_str().unwrap())
|
||||
.vector_size(1536)
|
||||
.with_vector(EmbeddedField::Combined)
|
||||
.with_metadata(METADATA_QA_TEXT_NAME)
|
||||
.table_name("swiftide_test")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md"))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(openai_client.clone()))
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.then_store_with(lancedb.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
// By default the search strategy is SimilaritySingleEmbedding
|
||||
// which takes the latest query, embeds it, and does a similarity search
|
||||
//
|
||||
// LanceDB will return an error if multiple embeddings are set
|
||||
//
|
||||
// The pipeline generates subquestions to increase semantic coverage, embeds these in a single
|
||||
// embedding, retrieves the default top_k documents, summarizes them and uses that as context
|
||||
// for the final answer.
|
||||
let pipeline = query::Pipeline::default()
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_transform_query(query_transformers::Embed::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_retrieve(lancedb.clone())
|
||||
.then_transform_response(response_transformers::Summary::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_answer(answers::Simple::from_client(openai_client.clone()));
|
||||
|
||||
let result = pipeline
|
||||
.query("What is swiftide? Please provide an elaborate explanation")
|
||||
.await?;
|
||||
|
||||
println!("{:?}", result.answer());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! This is an example of using the langfuse integration with Swiftide.
|
||||
//!
|
||||
//! Langfuse is a platform for tracking and monitoring LLM usage and performance.
|
||||
//!
|
||||
//! When the feature `langfuse` is enabled, Swiftide can report tracing information,
|
||||
//! usage, inputs, and outputs to langfuse.
|
||||
//!
|
||||
//! For this to work, you need to set the LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY
|
||||
//! to the appropriate values. You can also set the LANGFUSE_URL environment variable
|
||||
//! to overwrite the default URL (http://localhost:3000).
|
||||
//!
|
||||
//! You can find more information about langfuse at https://langfuse.com/. On their github they
|
||||
//! also have a handy docker compose setup.
|
||||
//!
|
||||
//! More advanced usage is possible by using the `LangfuseLayer` directly.
|
||||
use anyhow::Result;
|
||||
use swiftide::traits::SimplePrompt;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing_subscriber::{
|
||||
EnvFilter, Layer as _, layer::SubscriberExt as _, util::SubscriberInitExt as _,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
println!("Hello, langfuse!");
|
||||
|
||||
let fmt_layer = tracing_subscriber::fmt::layer()
|
||||
.compact()
|
||||
.with_target(false)
|
||||
.boxed();
|
||||
|
||||
let langfuse_layer = swiftide::langfuse::LangfuseLayer::default()
|
||||
.with_filter(LevelFilter::DEBUG)
|
||||
.boxed();
|
||||
|
||||
let registry = tracing_subscriber::registry()
|
||||
.with(EnvFilter::from_default_env())
|
||||
.with(vec![fmt_layer, langfuse_layer]);
|
||||
|
||||
registry.init();
|
||||
|
||||
prompt_openai().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn prompt_openai() -> Result<()> {
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-5")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let paris = openai
|
||||
.prompt("What is the capital of France?".into())
|
||||
.await?;
|
||||
|
||||
println!("The capital of France is {paris}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self,
|
||||
loaders::FileLoader,
|
||||
transformers::{ChunkMarkdown, Embed, MetadataQAText},
|
||||
},
|
||||
integrations::{self, qdrant::Qdrant},
|
||||
query::{self, answers, query_transformers, response_transformers},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-large")
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()?;
|
||||
|
||||
let qdrant = Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(3072)
|
||||
.collection_name("swiftide-examples")
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md"))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then(MetadataQAText::new(openai_client.clone()))
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.then_store_with(qdrant.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
// By default the search strategy is SimilaritySingleEmbedding
|
||||
// which takes the latest query, embeds it, and does a similarity search
|
||||
let pipeline = query::Pipeline::default()
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_transform_query(query_transformers::Embed::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_retrieve(qdrant.clone())
|
||||
.then_transform_response(response_transformers::Summary::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_answer(answers::Simple::from_client(openai_client.clone()));
|
||||
|
||||
let result = pipeline
|
||||
.query("What is swiftide? Please provide an elaborate explanation")
|
||||
.await?;
|
||||
|
||||
println!("{:?}", result.answer());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/// Demonstrates reranking retrieved documents with fastembed
|
||||
///
|
||||
/// When reranking, many more documents are retrieved than used for the initial query. Maybe
|
||||
/// even from multiple sources.
|
||||
///
|
||||
/// Reranking compares the relevancy of the documents with the initial query, then filters out
|
||||
/// the `top_k` documents.
|
||||
///
|
||||
/// By default the model uses 'bge-reranker-base'.
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self,
|
||||
loaders::FileLoader,
|
||||
transformers::{ChunkMarkdown, Embed},
|
||||
},
|
||||
integrations::{self, fastembed, qdrant::Qdrant},
|
||||
query::{self, answers, query_transformers},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()?;
|
||||
|
||||
let fastembed = fastembed::FastEmbed::builder().batch_size(10).build()?;
|
||||
let reranker = fastembed::Rerank::builder().top_k(5).build()?;
|
||||
|
||||
let qdrant = Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(384)
|
||||
.collection_name("swiftide-reranking")
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("README.md"))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..2048))
|
||||
.then_in_batch(Embed::new(fastembed.clone()))
|
||||
.then_store_with(qdrant.clone())
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
// By default the search strategy is SimilaritySingleEmbedding
|
||||
// which takes the latest query, embeds it, and does a similarity search
|
||||
let pipeline = query::Pipeline::default()
|
||||
.then_transform_query(query_transformers::GenerateSubquestions::from_client(
|
||||
openai_client.clone(),
|
||||
))
|
||||
.then_transform_query(query_transformers::Embed::from_client(fastembed.clone()))
|
||||
.then_retrieve(qdrant.clone())
|
||||
.then_transform_response(reranker)
|
||||
.then_answer(answers::Simple::from_client(openai_client.clone()));
|
||||
|
||||
let result = pipeline
|
||||
.query("What is swiftide? Please provide an elaborate explanation")
|
||||
.await?;
|
||||
|
||||
println!("{:?}", result.answer());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::StreamExt as _;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::Write as _;
|
||||
use swiftide::{
|
||||
chat_completion::{ChatCompletionRequest, ChatMessage, ToolOutput, errors::ToolError},
|
||||
integrations::openai::{OpenAI, Options},
|
||||
traits::{AgentContext, ChatCompletion, SimplePrompt, StructuredPrompt},
|
||||
};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[allow(dead_code)]
|
||||
struct WeatherSummary {
|
||||
description: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct EchoArgs {
|
||||
message: String,
|
||||
}
|
||||
|
||||
/// Minimal echo tool used to demonstrate tool calling with the Responses API.
|
||||
/// The macro implements the `Tool` trait, derives the JSON schema, and generates
|
||||
/// a helper constructor (`echo_tool()`) that returns a boxed tool ready for use.
|
||||
#[swiftide::tool(
|
||||
description = "Echos the provided message back to the caller.",
|
||||
param(name = "payload", description = "Text to echo back")
|
||||
)]
|
||||
async fn echo_tool(
|
||||
_context: &dyn AgentContext,
|
||||
payload: EchoArgs,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
Ok(ToolOutput::text(format!("Echo: {}", payload.message)))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
let openai = OpenAI::builder()
|
||||
.default_prompt_model("gpt-4.1-mini")
|
||||
.default_options(Options::builder().temperature(0.2))
|
||||
.use_responses_api(true)
|
||||
.build()?;
|
||||
|
||||
let greeting = openai
|
||||
.prompt("Say hello in one short sentence".into())
|
||||
.await?;
|
||||
println!("Prompt result: {greeting}");
|
||||
|
||||
let structured: WeatherSummary = openai
|
||||
.structured_prompt("Summarise today's weather in Amsterdam as JSON".into())
|
||||
.await?;
|
||||
println!("Structured result: {structured:?}");
|
||||
|
||||
let chat_request = ChatCompletionRequest::builder()
|
||||
.messages(vec![
|
||||
ChatMessage::new_system("You are a concise assistant."),
|
||||
ChatMessage::new_user("Share one fun fact about Amsterdam."),
|
||||
])
|
||||
.build()?;
|
||||
|
||||
let completion = openai.complete(&chat_request).await?;
|
||||
println!(
|
||||
"Complete result: {}",
|
||||
completion.message().unwrap_or("<no message>")
|
||||
);
|
||||
|
||||
let mut stream = openai.complete_stream(&chat_request).await;
|
||||
print!("Streaming result: ");
|
||||
let mut streamed_message = String::new();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk?;
|
||||
if let Some(delta) = chunk
|
||||
.delta
|
||||
.as_ref()
|
||||
.and_then(|delta| delta.message_chunk.as_deref())
|
||||
{
|
||||
print!("{delta}");
|
||||
std::io::stdout().flush().ok();
|
||||
}
|
||||
|
||||
if let Some(message) = chunk.message() {
|
||||
streamed_message = message.to_string();
|
||||
}
|
||||
}
|
||||
println!();
|
||||
if streamed_message.is_empty() {
|
||||
println!("Full streamed result: <no message>");
|
||||
} else {
|
||||
println!("Full streamed result: {streamed_message}");
|
||||
}
|
||||
|
||||
let tool_request = ChatCompletionRequest::builder()
|
||||
.messages(vec![
|
||||
ChatMessage::new_system(
|
||||
"You are a precise assistant. Use available tools before replying directly.",
|
||||
),
|
||||
ChatMessage::new_user(
|
||||
"Call the echo tool with the phrase \"Hello Responses API\" and then summarise the result.",
|
||||
),
|
||||
])
|
||||
.tool(echo_tool())
|
||||
.build()?;
|
||||
|
||||
let tool_completion = openai.complete(&tool_request).await?;
|
||||
|
||||
if let Some(tool_call) = tool_completion
|
||||
.tool_calls()
|
||||
.and_then(|calls| calls.first())
|
||||
.cloned()
|
||||
{
|
||||
println!(
|
||||
"Assistant requested tool `{}` with arguments {}",
|
||||
tool_call.name(),
|
||||
tool_call.args().unwrap_or("<missing arguments>")
|
||||
);
|
||||
|
||||
let args_json = tool_call
|
||||
.args()
|
||||
.context("echo tool call missing arguments")?;
|
||||
let args: EchoToolArgs = serde_json::from_str(args_json)?;
|
||||
let tool_output = format!("Echo: {}", args.payload.message);
|
||||
|
||||
let mut follow_up_messages = tool_request.messages().to_vec();
|
||||
follow_up_messages.push(ChatMessage::new_assistant(
|
||||
None::<String>,
|
||||
Some(vec![tool_call.clone()]),
|
||||
));
|
||||
follow_up_messages.push(ChatMessage::new_tool_output(
|
||||
tool_call.clone(),
|
||||
ToolOutput::text(tool_output),
|
||||
));
|
||||
|
||||
let follow_up_request = ChatCompletionRequest::builder()
|
||||
.messages(follow_up_messages)
|
||||
.tool(echo_tool())
|
||||
.build()?;
|
||||
|
||||
let final_completion = openai.complete(&follow_up_request).await?;
|
||||
println!(
|
||||
"Final response after tool call: {}",
|
||||
final_completion.message().unwrap_or("<no message>")
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"Assistant responded without tool calls: {}",
|
||||
tool_completion.message().unwrap_or("<no message>")
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Simple agent example that enables reasoning summaries via the Responses API.
|
||||
|
||||
use anyhow::Result;
|
||||
use swiftide::agents::Agent;
|
||||
use swiftide::chat_completion::{ChatMessage, ReasoningItem};
|
||||
use swiftide::integrations::openai::{OpenAI, Options, ReasoningEffort};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
fn reasoning_summary(reasoning: Option<&[ReasoningItem]>) -> Option<String> {
|
||||
let summary = reasoning
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.flat_map(|item| item.summary.iter())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
if summary.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(summary)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
// Reasoning models require the Responses API. Enabling reasoning effort also asks for a
|
||||
// summary and encrypted reasoning content (enabled by default). If your OpenAI org is not
|
||||
// verified for reasoning access, summaries may be absent. Disable with
|
||||
// `reasoning_features(false)` if desired.
|
||||
let openai = OpenAI::builder()
|
||||
.default_prompt_model("o3-mini")
|
||||
.default_options(Options::builder().reasoning_effort(ReasoningEffort::Low))
|
||||
.use_responses_api(true)
|
||||
.build()?;
|
||||
|
||||
let mut agent = Agent::builder()
|
||||
.llm(&openai)
|
||||
.on_new_message(|_, message| {
|
||||
if let ChatMessage::Assistant(content, _) = message
|
||||
&& let Some(content) = content.as_deref()
|
||||
{
|
||||
println!("Assistant: {content}");
|
||||
}
|
||||
Box::pin(async move { Ok(()) })
|
||||
})
|
||||
.after_completion(|_, response| {
|
||||
if let Some(summary) = reasoning_summary(response.reasoning.as_deref()) {
|
||||
println!("Reasoning summary:\n{summary}");
|
||||
}
|
||||
|
||||
let has_encrypted = response
|
||||
.reasoning
|
||||
.as_ref()
|
||||
.is_some_and(|items| items.iter().any(|item| item.encrypted_content.is_some()));
|
||||
println!("Encrypted reasoning content present: {has_encrypted}");
|
||||
Box::pin(async move { Ok(()) })
|
||||
})
|
||||
.build()?;
|
||||
|
||||
agent
|
||||
.query("Explain why the sky is blue in one short paragraph.")
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! # [Swiftide] Indexing the Swiftide README with lots of metadata
|
||||
//!
|
||||
//! This example demonstrates how to index the Swiftide README with lots of metadata.
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Scrape the Bosun website
|
||||
//! - Transform the html to markdown
|
||||
//! - Chunk the markdown into smaller pieces
|
||||
//! - Store the nodes in Memory
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
use spider::website::Website;
|
||||
use swiftide::{
|
||||
indexing,
|
||||
indexing::persist::MemoryStorage,
|
||||
indexing::transformers::ChunkMarkdown,
|
||||
integrations::scraping::{HtmlToMarkdownTransformer, ScrapingLoader},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
indexing::Pipeline::from_loader(ScrapingLoader::from_spider(
|
||||
Website::new("https://www.bosun.ai/")
|
||||
.with_limit(1)
|
||||
.to_owned(),
|
||||
))
|
||||
.then(HtmlToMarkdownTransformer::default())
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(20..2048))
|
||||
.log_all()
|
||||
.then_store_with(MemoryStorage::default())
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Demonstrates how to plug a custom JSON schema into the stop tool for an OpenAI-powered agent.
|
||||
//!
|
||||
//! Set the `OPENAI_API_KEY` environment variable before running the example. The agent guides the
|
||||
//! model to call the `stop` tool with a structured payload that matches the schema defined below.
|
||||
//! The on-stop hook prints the structured payload that made the agent stop.
|
||||
use anyhow::Result;
|
||||
use schemars::{JsonSchema, Schema, schema_for};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::to_string_pretty;
|
||||
use swiftide::agents::tools::control::StopWithArgs;
|
||||
use swiftide::agents::{Agent, StopReason};
|
||||
use swiftide::traits::Tool;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum TaskStatus {
|
||||
Succeeded,
|
||||
Failed,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
struct StopPayload {
|
||||
status: TaskStatus,
|
||||
summary: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
details: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
fn stop_schema() -> Schema {
|
||||
schema_for!(StopPayload)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let schema = stop_schema();
|
||||
let stop_tool = StopWithArgs::with_parameters_schema(schema.clone());
|
||||
|
||||
println!(
|
||||
"stop tool schema:\n{}",
|
||||
to_string_pretty(&stop_tool.tool_spec())?,
|
||||
);
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.build()?;
|
||||
|
||||
let mut builder = Agent::builder();
|
||||
builder
|
||||
.llm(&openai)
|
||||
.without_default_stop_tool()
|
||||
.tools([stop_tool.clone()])
|
||||
.on_stop(|_, reason, _| {
|
||||
Box::pin(async move {
|
||||
if let StopReason::RequestedByTool(_, payload) = reason
|
||||
&& let Some(payload) = payload
|
||||
{
|
||||
println!(
|
||||
"agent stopped with structured payload:\n{}",
|
||||
to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string()),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
|
||||
if let Some(prompt) = builder.system_prompt_mut() {
|
||||
prompt
|
||||
.with_role("Workflow finisher")
|
||||
.with_guidelines([
|
||||
"Summarize the work that was just completed and recommend next actions.",
|
||||
"When you are done, call the `stop` tool using the provided JSON schema.",
|
||||
"Always include the `details` field; use null when there is nothing to add.",
|
||||
])
|
||||
.with_constraints(["Never fabricate task status values outside the schema."]);
|
||||
}
|
||||
|
||||
let mut agent = builder.build()?;
|
||||
|
||||
agent
|
||||
.query_once(
|
||||
"You completed onboarding five merchants today. Prepare a final handoff report and stop.",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! # [Swiftide] Ingesting file with multiple metadata stored as named vectors
|
||||
//!
|
||||
//! This example demonstrates how to ingest a LICENSE file, generate multiple metadata, and store it
|
||||
//! all in Qdrant with individual named vectors
|
||||
//!
|
||||
//! The pipeline will:
|
||||
//! - Load the LICENSE file from the current directory
|
||||
//! - Chunk the file into pieces of 20 to 1024 bytes
|
||||
//! - Generate questions and answers for each chunk
|
||||
//! - Generate a summary for each chunk
|
||||
//! - Generate a title for each chunk
|
||||
//! - Generate keywords for each chunk
|
||||
//! - Embed each chunk
|
||||
//! - Embed each metadata
|
||||
//! - Store the nodes in Qdrant with chunk and metadata embeds as named vectors
|
||||
//!
|
||||
//! [Swiftide]: https://github.com/bosun-ai/swiftide
|
||||
//! [examples]: https://github.com/bosun-ai/swiftide/blob/master/examples
|
||||
|
||||
use swiftide::{
|
||||
indexing::loaders::FileLoader,
|
||||
indexing::transformers::{
|
||||
ChunkMarkdown, Embed, MetadataKeywords, MetadataQAText, MetadataSummary, MetadataTitle,
|
||||
metadata_keywords, metadata_qa_text, metadata_summary, metadata_title,
|
||||
},
|
||||
indexing::{self, EmbedMode, EmbeddedField},
|
||||
integrations::{
|
||||
self,
|
||||
qdrant::{Distance, Qdrant, VectorConfig},
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-4o")
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new("LICENSE"))
|
||||
.with_concurrency(1)
|
||||
.with_embed_mode(EmbedMode::PerField)
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(20..2048))
|
||||
.then(MetadataQAText::new(openai_client.clone()))
|
||||
.then(MetadataSummary::new(openai_client.clone()))
|
||||
.then(MetadataTitle::new(openai_client.clone()))
|
||||
.then(MetadataKeywords::new(openai_client.clone()))
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.log_all()
|
||||
.filter_errors()
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.collection_name("swiftide-multi-vectors")
|
||||
.with_vector(EmbeddedField::Chunk)
|
||||
.with_vector(EmbeddedField::Metadata(metadata_qa_text::NAME.into()))
|
||||
.with_vector(EmbeddedField::Metadata(metadata_summary::NAME.into()))
|
||||
.with_vector(
|
||||
VectorConfig::builder()
|
||||
.embedded_field(EmbeddedField::Metadata(metadata_title::NAME.into()))
|
||||
.distance(Distance::Manhattan)
|
||||
.build()?,
|
||||
)
|
||||
.with_vector(EmbeddedField::Metadata(metadata_keywords::NAME.into()))
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! This example demonstrates how to stream responses from an agent
|
||||
//!
|
||||
//! By default, for convenience the accumulated response is streamed. You can opt-out of this
|
||||
//! behaviour and only receive the delta as well (only with OpenAI-like providers).
|
||||
use anyhow::Result;
|
||||
use swiftide::agents;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embeddings-3-small")
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
// Only streams the delta, leave this out to stream the full response
|
||||
.stream_full(false)
|
||||
.build()?;
|
||||
|
||||
// let anthropic = swiftide::integrations::anthropic::Anthropic::builder()
|
||||
// .default_prompt_model("claude-3-7-sonnet-latest")
|
||||
// .build()?;
|
||||
|
||||
agents::Agent::builder()
|
||||
.llm(&openai)
|
||||
.on_stream(|_agent, response| {
|
||||
// We print the message chunk if it exists. Streamed responses also include
|
||||
// the full response (without tool calls) in `message` and an `id` to map them to
|
||||
// previous chunks for convenience.
|
||||
//
|
||||
// The agent uses the full assembled response at the end of the stream.
|
||||
if let Some(delta) = &response.delta {
|
||||
print!(
|
||||
"{}",
|
||||
delta
|
||||
.message_chunk
|
||||
.as_deref()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_default()
|
||||
);
|
||||
};
|
||||
// If `stream_full` is disabled, response.message() will be the accumulated response
|
||||
// response.message()
|
||||
|
||||
Box::pin(async move { Ok(()) })
|
||||
})
|
||||
// Every message added by the agent will be printed to stdout
|
||||
.on_new_message(move |_, msg| {
|
||||
let msg = msg.to_string();
|
||||
Box::pin(async move {
|
||||
println!("\n---\nFinal message:\n {msg}");
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.limit(5)
|
||||
.build()?
|
||||
.query("Why is the rust programming language so good?")
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use anyhow::Result;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swiftide::{integrations, traits::DynStructuredPrompt, traits::StructuredPrompt as _};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let client = integrations::openai::OpenAI::builder()
|
||||
.default_prompt_model("gpt-5-mini")
|
||||
.build()?;
|
||||
|
||||
// Note that deny unknown fields is required. If you get an error on 'additionalProperties' to
|
||||
// be required, and false, this is what is missing.
|
||||
#[derive(Deserialize, JsonSchema, Serialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct MyResponse {
|
||||
questions: Vec<String>,
|
||||
}
|
||||
|
||||
let response = client
|
||||
.structured_prompt::<MyResponse>(
|
||||
"List three interesting questions about the Rust programming language.".into(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
println!("Response: {:?}", response.questions);
|
||||
|
||||
// Because we use generics, structured_prompt is not dyn safe. However, there is an
|
||||
// alternative:
|
||||
|
||||
let client: Box<dyn DynStructuredPrompt> = Box::new(client);
|
||||
|
||||
let response: serde_json::Value = client
|
||||
.structured_prompt_dyn(
|
||||
"List three interesting questions about the Rust programming language.".into(),
|
||||
schemars::schema_for!(MyResponse),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let parsed: MyResponse = serde_json::from_value(response)?;
|
||||
|
||||
println!("Response: {:?}", parsed);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! This example illustrates how to set up a basic tasks
|
||||
//!
|
||||
//! Tasks follow a graph model where each output of a node must match the input of the next node.
|
||||
//!
|
||||
//! To set up a task, you register nodes that implement the `TaskNode` trait. Most swiftide
|
||||
//! primiteves implement this trait, including agents, prompts, and closures.
|
||||
//!
|
||||
//! Then each node can be connected to the next node using the `register_transition` method. There
|
||||
//! is also a `register_transition_async` method that allows you to register an async transition.
|
||||
//!
|
||||
//! Since running an autonomous agent in a task is subject to taste, there is a basic
|
||||
//! `TaskAgent` that wraps it in an `Arc<Mutex>`, but your own implementation might want to toy
|
||||
//! with the state instead of the task instead.
|
||||
//!
|
||||
//! The API for closures as task nodes is still a bit clunky and subject to change.
|
||||
use anyhow::Result;
|
||||
use swiftide::{
|
||||
agents::{
|
||||
self,
|
||||
tasks::{closures::SyncFn, impls::TaskAgent, task::Task},
|
||||
},
|
||||
prompt::Prompt,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
println!("Hello, agents!");
|
||||
|
||||
let openai = swiftide::integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embeddings-3-small")
|
||||
.default_prompt_model("gpt-4o-mini")
|
||||
.build()?;
|
||||
|
||||
let agent = agents::Agent::builder().llm(&openai).build()?;
|
||||
|
||||
let mut task: Task<Prompt, ()> = Task::new();
|
||||
|
||||
let agent_id = task.register_node(TaskAgent::from(agent));
|
||||
|
||||
let hello_id = task.register_node(SyncFn::new(move |_context: &()| {
|
||||
println!("Hello from a task!");
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
task.starts_with(agent_id);
|
||||
|
||||
// Async is also supported
|
||||
task.register_transition_async(agent_id, move |context| {
|
||||
Box::pin(async move { hello_id.transitions_with(context) })
|
||||
})?;
|
||||
task.register_transition(hello_id, task.transitions_to_done())?;
|
||||
|
||||
task.run("Hello there!").await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use anyhow::Result;
|
||||
use schemars::{JsonSchema, Schema, schema_for};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use swiftide::chat_completion::{Tool, ToolCall, ToolOutput, ToolSpec, errors::ToolError};
|
||||
use swiftide::traits::AgentContext;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WorkflowTool;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[schemars(
|
||||
title = "WorkflowInstruction",
|
||||
description = "Choose a workflow action and optional payload",
|
||||
deny_unknown_fields
|
||||
)]
|
||||
struct WorkflowInstruction {
|
||||
#[schemars(description = "Which workflow action to execute")]
|
||||
action: WorkflowAction,
|
||||
#[schemars(description = "Optional payload forwarded to the workflow engine")]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
payload: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum WorkflowAction {
|
||||
Start,
|
||||
Stop,
|
||||
Status,
|
||||
}
|
||||
|
||||
#[swiftide::reexports::async_trait::async_trait]
|
||||
impl Tool for WorkflowTool {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn AgentContext,
|
||||
_tool_call: &ToolCall,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
Ok(ToolOutput::text(
|
||||
"Workflow execution not implemented in this example",
|
||||
))
|
||||
}
|
||||
|
||||
fn name<'tool>(&'tool self) -> Cow<'tool, str> {
|
||||
Cow::Borrowed("workflow_tool")
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
ToolSpec::builder()
|
||||
.name("workflow_tool")
|
||||
.description("Executes a workflow action with strict input choices")
|
||||
.parameters_schema(workflow_schema())
|
||||
.build()
|
||||
.expect("tool spec should be valid")
|
||||
}
|
||||
}
|
||||
|
||||
fn workflow_schema() -> Schema {
|
||||
schema_for!(WorkflowInstruction)
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let tool = WorkflowTool;
|
||||
let spec = tool.tool_spec();
|
||||
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&spec).expect("tool spec should serialize"),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Swiftide can emit usage metrics using `metrics-rs`.
|
||||
//!
|
||||
//! For metrics to be emitted, the `metrics` feature must be enabled.
|
||||
//!
|
||||
//! `metrics-rs` is a flexibly rust library that allows you to collect and publish metrics
|
||||
//! anywhere. From the user side, you need to provide a recorder and handles. The library itself
|
||||
//! provides several built-in for these, i.e. prometheus.
|
||||
//!
|
||||
//! In this example, we're indexing markdown and logging the usage metrics to stdout. For the
|
||||
//! recording we're using the examples from metric-rs.
|
||||
//!
|
||||
//! Usage metrics are emitted embedding, prompt requests, and chat completions. They always include
|
||||
//! the model used as metadata
|
||||
|
||||
use swiftide::{
|
||||
indexing::{
|
||||
self,
|
||||
loaders::FileLoader,
|
||||
transformers::{ChunkMarkdown, Embed},
|
||||
},
|
||||
integrations::{self, qdrant::Qdrant},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// tracing_subscriber::fmt::init();
|
||||
init_print_logger();
|
||||
|
||||
let metric_metadata = HashMap::from([("example".to_string(), "metadata".to_string())]);
|
||||
let openai_client = integrations::openai::OpenAI::builder()
|
||||
.default_embed_model("text-embedding-3-small")
|
||||
.default_prompt_model("gpt-4.1-nano")
|
||||
// Metadata will be added to every metric
|
||||
.metric_metadata(metric_metadata)
|
||||
.build()?;
|
||||
|
||||
indexing::Pipeline::from_loader(FileLoader::new(".").with_extensions(&["md"]))
|
||||
.then_chunk(ChunkMarkdown::from_chunk_range(10..512))
|
||||
.then_in_batch(Embed::new(openai_client.clone()).with_batch_size(10))
|
||||
.then_store_with(
|
||||
Qdrant::builder()
|
||||
.batch_size(50)
|
||||
.vector_size(1536)
|
||||
.collection_name("swiftide-examples-metrics")
|
||||
.build()?,
|
||||
)
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
// (counter) registered key swiftide.usage.prompt_tokens with unit None and description "token
|
||||
// usage for the prompt" (counter) registered key swiftide.usage.completion_tokens with unit
|
||||
// None and description "token usage for the completion" (counter) registered key
|
||||
// swiftide.usage.total_tokens with unit None and description "total token usage"
|
||||
// counter increment for 'Key(swiftide.usage.prompt_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 356 counter increment for
|
||||
// 'Key(swiftide.usage.completion_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 0 counter increment for 'Key(swiftide.usage.total_tokens,
|
||||
// [example = metadata, model = text-embedding-3-small])': 356 counter increment for
|
||||
// 'Key(swiftide.usage.prompt_tokens, [example = metadata, model = text-embedding-3-small])':
|
||||
// 336 counter increment for 'Key(swiftide.usage.completion_tokens, [example = metadata,
|
||||
// model = text-embedding-3-small])': 0 counter increment for
|
||||
// 'Key(swiftide.usage.total_tokens, [example = metadata, model = text-embedding-3-small])': 336
|
||||
// counter increment for 'Key(swiftide.usage.prompt_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 251 counter increment for
|
||||
// 'Key(swiftide.usage.completion_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 0 counter increment for 'Key(swiftide.usage.total_tokens,
|
||||
// [example = metadata, model = text-embedding-3-small])': 251 counter increment for
|
||||
// 'Key(swiftide.usage.prompt_tokens, [example = metadata, model = text-embedding-3-small])':
|
||||
// 404 counter increment for 'Key(swiftide.usage.completion_tokens, [example = metadata,
|
||||
// model = text-embedding-3-small])': 0 counter increment for
|
||||
// 'Key(swiftide.usage.total_tokens, [example = metadata, model = text-embedding-3-small])': 404
|
||||
// counter increment for 'Key(swiftide.usage.prompt_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 329 counter increment for
|
||||
// 'Key(swiftide.usage.completion_tokens, [example = metadata, model =
|
||||
// text-embedding-3-small])': 0 counter increment for 'Key(swiftide.usage.total_tokens,
|
||||
// [example = metadata, model = text-embedding-3-small])': 329
|
||||
}
|
||||
|
||||
// --- Copied from https://github.com/metrics-rs/metrics/blob/main/metrics/examples/basic.rs
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use metrics::{Counter, CounterFn, Gauge, GaugeFn, Histogram, HistogramFn, Key, Recorder, Unit};
|
||||
use metrics::{KeyName, Metadata, SharedString};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct PrintHandle(Key);
|
||||
|
||||
impl CounterFn for PrintHandle {
|
||||
fn increment(&self, value: u64) {
|
||||
println!("counter increment for '{}': {}", self.0, value);
|
||||
}
|
||||
|
||||
fn absolute(&self, value: u64) {
|
||||
println!("counter absolute for '{}': {}", self.0, value);
|
||||
}
|
||||
}
|
||||
|
||||
impl GaugeFn for PrintHandle {
|
||||
fn increment(&self, value: f64) {
|
||||
println!("gauge increment for '{}': {}", self.0, value);
|
||||
}
|
||||
|
||||
fn decrement(&self, value: f64) {
|
||||
println!("gauge decrement for '{}': {}", self.0, value);
|
||||
}
|
||||
|
||||
fn set(&self, value: f64) {
|
||||
println!("gauge set for '{}': {}", self.0, value);
|
||||
}
|
||||
}
|
||||
|
||||
impl HistogramFn for PrintHandle {
|
||||
fn record(&self, value: f64) {
|
||||
println!("histogram record for '{}': {}", self.0, value);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PrintRecorder;
|
||||
|
||||
impl Recorder for PrintRecorder {
|
||||
fn describe_counter(&self, key_name: KeyName, unit: Option<Unit>, description: SharedString) {
|
||||
println!(
|
||||
"(counter) registered key {} with unit {:?} and description {:?}",
|
||||
key_name.as_str(),
|
||||
unit,
|
||||
description
|
||||
);
|
||||
}
|
||||
|
||||
fn describe_gauge(&self, key_name: KeyName, unit: Option<Unit>, description: SharedString) {
|
||||
println!(
|
||||
"(gauge) registered key {} with unit {:?} and description {:?}",
|
||||
key_name.as_str(),
|
||||
unit,
|
||||
description
|
||||
);
|
||||
}
|
||||
|
||||
fn describe_histogram(&self, key_name: KeyName, unit: Option<Unit>, description: SharedString) {
|
||||
println!(
|
||||
"(histogram) registered key {} with unit {:?} and description {:?}",
|
||||
key_name.as_str(),
|
||||
unit,
|
||||
description
|
||||
);
|
||||
}
|
||||
|
||||
fn register_counter(&self, key: &Key, _metadata: &Metadata<'_>) -> Counter {
|
||||
Counter::from_arc(Arc::new(PrintHandle(key.clone())))
|
||||
}
|
||||
|
||||
fn register_gauge(&self, key: &Key, _metadata: &Metadata<'_>) -> Gauge {
|
||||
Gauge::from_arc(Arc::new(PrintHandle(key.clone())))
|
||||
}
|
||||
|
||||
fn register_histogram(&self, key: &Key, _metadata: &Metadata<'_>) -> Histogram {
|
||||
Histogram::from_arc(Arc::new(PrintHandle(key.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
fn init_print_logger() {
|
||||
metrics::set_global_recorder(PrintRecorder).unwrap()
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 427 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 153 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 40 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 40 KiB |
@@ -0,0 +1,118 @@
|
||||
[workspace]
|
||||
changelog_path = "./CHANGELOG.md"
|
||||
#changelog_config = "cliff.toml"
|
||||
git_tag_name = "v{{ version }}"
|
||||
changelog_update = false
|
||||
git_tag_enable = false
|
||||
git_release_enable = false
|
||||
repo_url = "https://github.com/bosun-ai/swiftide"
|
||||
|
||||
[[package]]
|
||||
name = "swiftide-macros"
|
||||
publish_no_verify = true
|
||||
[[package]]
|
||||
# Only release the main package on github
|
||||
name = "swiftide"
|
||||
git_tag_name = "v{{ version }}"
|
||||
git_tag_enable = true
|
||||
git_release_enable = true
|
||||
changelog_include = [
|
||||
"swiftide-core",
|
||||
"swiftide-indexing",
|
||||
"swiftide-integrations",
|
||||
"swiftide-query",
|
||||
"swiftide-test-utils",
|
||||
"swiftide-agents",
|
||||
"swiftide-macros",
|
||||
]
|
||||
changelog_update = true
|
||||
|
||||
[changelog]
|
||||
commit_parsers = [
|
||||
{ message = "^feat*", group = "<!-- 0 -->New features" },
|
||||
{ message = "^fix*", group = "<!-- 1 -->Bug fixes" },
|
||||
{ message = "^perf*", group = "<!-- 2 -->Performance" },
|
||||
{ message = "^chore*", group = "<!-- 3 -->Miscellaneous" },
|
||||
{ message = "^refactor*", group = "<!-- 3 -->Miscellaneous" },
|
||||
]
|
||||
|
||||
# changelog header
|
||||
header = """
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
"""
|
||||
body = """
|
||||
{%- if not version %}
|
||||
## [unreleased]
|
||||
{% else -%}
|
||||
## [{{ version }}]({{ release_link }}) - {{ timestamp | date(format="%Y-%m-%d") }}
|
||||
{% endif -%}
|
||||
|
||||
{% macro commit(commit) -%}
|
||||
{% if commit.id -%}
|
||||
- [{{ commit.id | truncate(length=7, end="") }}]({{ "https://github.com/bosun-ai/swiftide/commit/" ~ commit.id }}) \
|
||||
{% endif -%}
|
||||
{% if commit.scope %}*({{commit.scope | default(value = "uncategorized") | lower }})* {% endif %}\
|
||||
{%- if commit.breaking %} [**breaking**]{% endif %} \
|
||||
{{ commit.message | upper_first | trim }}\
|
||||
{%- if commit.links %} \
|
||||
in {% for link in commit.links %}[{{link.text}}]({{link.href}}) {% endfor -%}\
|
||||
{% endif %}
|
||||
{%- if commit.breaking_description %}
|
||||
|
||||
**BREAKING CHANGE**: {{ commit.breaking_description }}
|
||||
|
||||
{%- endif %}
|
||||
{% endmacro -%}
|
||||
|
||||
{% for group, commits in commits | group_by(attribute="group") %}
|
||||
### {{ group | striptags | trim | upper_first }}
|
||||
{% for commit in commits | filter(attribute="scope") | sort(attribute="scope") %}
|
||||
{{ self::commit(commit=commit) }}
|
||||
{%- endfor -%}
|
||||
{% for commit in commits %}
|
||||
{%- if not commit.scope %}
|
||||
{{ self::commit(commit=commit) }}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor %}
|
||||
|
||||
{%- if github.contributors -%}
|
||||
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
|
||||
### New Contributors
|
||||
{%- endif %}\
|
||||
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
|
||||
* @{{ contributor.username }} made their first contribution
|
||||
{%- if contributor.pr_number %} in \
|
||||
[#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \
|
||||
{%- endif %}
|
||||
{%- endfor -%}
|
||||
{% endif -%}
|
||||
|
||||
{% if version %}
|
||||
{% if previous.version %}
|
||||
**Full Changelog**: {{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}
|
||||
{% endif %}
|
||||
{% else -%}
|
||||
{% raw %}\n{% endraw %}
|
||||
{% endif %}
|
||||
|
||||
{%- macro remote_url() -%}
|
||||
{%- if remote.github -%}
|
||||
https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }}\
|
||||
{% else -%}
|
||||
https://github.com/bosun-ai/swiftide
|
||||
{%- endif -%}
|
||||
{% endmacro %}
|
||||
""" # template for the changelog body
|
||||
# https://keats.github.io/tera/docs/#introduction
|
||||
# note that the - before / after the % controls whether whitespace is rendered between each line.
|
||||
# Getting this right so that the markdown renders with the correct number of lines between headings
|
||||
# code fences and list items is pretty finicky. Note also that the 4 backticks in the commit macro
|
||||
# is intentional as this escapes any backticks in the commit body.
|
||||
|
||||
|
||||
# remove the leading and trailing whitespace from the template
|
||||
trim = false
|
||||
# changelog footer
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[toolchain]
|
||||
channel = "stable"
|
||||
@@ -0,0 +1,6 @@
|
||||
# docs: https://rust-lang.github.io/rustfmt/
|
||||
|
||||
# Unstable options - to run these, use `cargo +nightly fmt`
|
||||
wrap_comments = true
|
||||
comment_width = 100
|
||||
normalize_comments = true
|
||||
@@ -0,0 +1,66 @@
|
||||
cargo-features = ["edition2024"]
|
||||
|
||||
[package]
|
||||
name = "swiftide-agents"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
description.workspace = true
|
||||
categories.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
swiftide-core = { path = "../swiftide-core", version = "0.32" }
|
||||
swiftide-indexing = { path = "../swiftide-indexing", version = "0.32" }
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
dyn-clone.workspace = true
|
||||
derive_builder.workspace = true
|
||||
indoc.workspace = true
|
||||
tracing.workspace = true
|
||||
tokio.workspace = true
|
||||
# pretty_assertions.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
fs-err = { workspace = true, features = ["tokio"] }
|
||||
thiserror.workspace = true
|
||||
futures-util.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
convert_case.workspace = true
|
||||
schemars = { workspace = true, features = ["derive"] }
|
||||
|
||||
# Mcp
|
||||
rmcp = { workspace = true, optional = true, default-features = false, features = [
|
||||
"base64",
|
||||
"client",
|
||||
"macros",
|
||||
"server",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
swiftide-core = { path = "../swiftide-core", features = ["test-utils"] }
|
||||
mockall.workspace = true
|
||||
test-log.workspace = true
|
||||
temp-dir.workspace = true
|
||||
insta.workspace = true
|
||||
rmcp = { workspace = true, features = ["server"] }
|
||||
schemars = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[features]
|
||||
mcp = ["dep:rmcp"]
|
||||
json-schema = ["swiftide-core/json-schema"]
|
||||
langfuse = []
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,595 @@
|
||||
//! Manages agent history and provides an interface for the external world
|
||||
//!
|
||||
//! This is the default for agents. It is fully async and shareable between agents.
|
||||
//!
|
||||
//! By default uses the `LocalExecutor` for tool execution.
|
||||
//!
|
||||
//! If chat messages include a `ChatMessage::Summary`, all previous messages are ignored except the
|
||||
//! system prompt. This is useful for maintaining focus in long conversations or managing token
|
||||
//! limits.
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use swiftide_core::{
|
||||
AgentContext, Command, CommandError, CommandOutput, MessageHistory, ToolExecutor,
|
||||
};
|
||||
use swiftide_core::{
|
||||
ToolFeedback,
|
||||
chat_completion::{ChatMessage, ToolCall},
|
||||
};
|
||||
|
||||
use crate::tools::local_executor::LocalExecutor;
|
||||
|
||||
// TODO: Remove unit as executor and implement a local executor instead
|
||||
#[derive(Clone)]
|
||||
pub struct DefaultContext {
|
||||
/// Responsible for managing the conversation history
|
||||
///
|
||||
/// By default, this is a `Arc<Mutex<Vec<ChatMessage>>>`.
|
||||
message_history: Arc<dyn MessageHistory>,
|
||||
/// Index in the conversation history where the next completion will start
|
||||
completions_ptr: Arc<AtomicUsize>,
|
||||
|
||||
/// Index in the conversation history where the current completion started
|
||||
/// Allows for retrieving only new messages since the last completion
|
||||
current_completions_ptr: Arc<AtomicUsize>,
|
||||
|
||||
/// The executor used to run tools. I.e. local, remote, docker
|
||||
tool_executor: Arc<dyn ToolExecutor>,
|
||||
|
||||
/// Stop if last message is from the assistant
|
||||
stop_on_assistant: bool,
|
||||
|
||||
feedback_received: Arc<Mutex<HashMap<ToolCall, ToolFeedback>>>,
|
||||
}
|
||||
|
||||
impl Default for DefaultContext {
|
||||
fn default() -> Self {
|
||||
DefaultContext {
|
||||
message_history: Arc::new(Mutex::new(Vec::new())),
|
||||
completions_ptr: Arc::new(AtomicUsize::new(0)),
|
||||
current_completions_ptr: Arc::new(AtomicUsize::new(0)),
|
||||
tool_executor: Arc::new(LocalExecutor::default()) as Arc<dyn ToolExecutor>,
|
||||
stop_on_assistant: true,
|
||||
feedback_received: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DefaultContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DefaultContext")
|
||||
.field("completion_history", &self.message_history)
|
||||
.field("completions_ptr", &self.completions_ptr)
|
||||
.field("current_completions_ptr", &self.current_completions_ptr)
|
||||
.field("tool_executor", &"Arc<dyn ToolExecutor>")
|
||||
.field("stop_on_assistant", &self.stop_on_assistant)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultContext {
|
||||
/// Create a new context with a custom executor
|
||||
pub fn from_executor<T: Into<Arc<dyn ToolExecutor>>>(executor: T) -> DefaultContext {
|
||||
DefaultContext {
|
||||
tool_executor: executor.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// If set to true, the agent will stop if the last message is from the assistant (i.e. no new
|
||||
/// tool calls, summaries or user messages)
|
||||
pub fn with_stop_on_assistant(&mut self, stop: bool) -> &mut Self {
|
||||
self.stop_on_assistant = stop;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_message_history(&mut self, backend: impl MessageHistory + 'static) -> &mut Self {
|
||||
self.message_history = Arc::new(backend) as Arc<dyn MessageHistory>;
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a context from an existing message history
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the message history cannot be extended
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the inner mutex is poisoned
|
||||
pub async fn with_existing_messages<I: IntoIterator<Item = ChatMessage>>(
|
||||
&mut self,
|
||||
message_history: I,
|
||||
) -> Result<&mut Self> {
|
||||
self.message_history
|
||||
.overwrite(message_history.into_iter().collect())
|
||||
.await?;
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Add existing tool feedback to the context
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the inner mutex is poisoned
|
||||
pub fn with_tool_feedback(&mut self, feedback: impl Into<HashMap<ToolCall, ToolFeedback>>) {
|
||||
self.feedback_received
|
||||
.lock()
|
||||
.unwrap()
|
||||
.extend(feedback.into());
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl AgentContext for DefaultContext {
|
||||
/// Retrieve messages for the next completion
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>> {
|
||||
let history = self.message_history.history().await?;
|
||||
|
||||
let mut current = self.completions_ptr.load(Ordering::SeqCst);
|
||||
|
||||
// handle out of bounds; if current > length, reset current to 0
|
||||
// if length is 0, return None
|
||||
if history.is_empty() {
|
||||
tracing::debug!("No messages in history for completion");
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if current > history.len() {
|
||||
tracing::warn!(
|
||||
current,
|
||||
len = history.len(),
|
||||
"Completions index was higher than history length, resetting to 0; this might be a bug"
|
||||
);
|
||||
self.completions_ptr.store(0, Ordering::SeqCst);
|
||||
self.current_completions_ptr.store(0, Ordering::SeqCst);
|
||||
|
||||
current = 0;
|
||||
}
|
||||
|
||||
if history[current..].is_empty()
|
||||
|| (self.stop_on_assistant
|
||||
&& matches!(history.last(), Some(ChatMessage::Assistant(..)))
|
||||
&& self.feedback_received.lock().unwrap().is_empty())
|
||||
{
|
||||
tracing::debug!(?history, "No new messages for completion");
|
||||
Ok(None)
|
||||
} else {
|
||||
let previous = self.completions_ptr.swap(history.len(), Ordering::SeqCst);
|
||||
self.current_completions_ptr
|
||||
.store(previous, Ordering::SeqCst);
|
||||
|
||||
Ok(Some(filter_messages_since_summary(history)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the messages the agent is currently completing on
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
let current = self.current_completions_ptr.load(Ordering::SeqCst);
|
||||
let end = self.completions_ptr.load(Ordering::SeqCst);
|
||||
|
||||
let history = self.message_history.history().await?;
|
||||
|
||||
Ok(filter_messages_since_summary(
|
||||
history[current..end].to_vec(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Retrieve all messages in the conversation history
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
self.message_history.history().await
|
||||
}
|
||||
|
||||
/// Add multiple messages to the conversation history
|
||||
async fn add_messages(&self, messages: Vec<ChatMessage>) -> Result<()> {
|
||||
self.message_history.extend_owned(messages).await
|
||||
}
|
||||
|
||||
/// Add a single message to the conversation history
|
||||
async fn add_message(&self, item: ChatMessage) -> Result<()> {
|
||||
self.message_history.push_owned(item).await
|
||||
}
|
||||
|
||||
/// Execute a command in the tool executor
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
self.tool_executor.exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor> {
|
||||
&self.tool_executor
|
||||
}
|
||||
|
||||
/// Pops the last messages up until the previous completion
|
||||
///
|
||||
/// LLMs failing completion for various reasons is unfortunately a common occurrence
|
||||
/// This gives a way to redrive the last completion in a generic way
|
||||
async fn redrive(&self) -> Result<()> {
|
||||
let mut history = self.message_history.history().await?;
|
||||
let previous = self.current_completions_ptr.load(Ordering::SeqCst);
|
||||
let redrive_ptr = self.completions_ptr.swap(previous, Ordering::SeqCst);
|
||||
|
||||
// delete everything after the last completion
|
||||
history.truncate(redrive_ptr);
|
||||
|
||||
self.message_history.overwrite(history).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn has_received_feedback(&self, tool_call: &ToolCall) -> Option<ToolFeedback> {
|
||||
// If feedback is present, return true with the optional payload,
|
||||
// and remove it
|
||||
// otherwise return false
|
||||
let mut lock = self.feedback_received.lock().unwrap();
|
||||
lock.remove(tool_call)
|
||||
}
|
||||
|
||||
async fn feedback_received(&self, tool_call: &ToolCall, feedback: &ToolFeedback) -> Result<()> {
|
||||
let mut lock = self.feedback_received.lock().unwrap();
|
||||
// Set the message counter one back so that on a next try, the agent can resume by
|
||||
// trying the tool calls first. Only does this if there are no other approvals
|
||||
if lock.is_empty() {
|
||||
let previous = self.current_completions_ptr.load(Ordering::SeqCst);
|
||||
self.completions_ptr.swap(previous, Ordering::SeqCst);
|
||||
}
|
||||
tracing::debug!(?tool_call, context = ?self, "feedback received");
|
||||
lock.insert(tool_call.clone(), feedback.clone());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace the entire conversation history
|
||||
async fn replace_history(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
self.message_history.overwrite(items).await?;
|
||||
self.completions_ptr.store(0, Ordering::SeqCst);
|
||||
self.current_completions_ptr.store(0, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_messages_since_summary(messages: Vec<ChatMessage>) -> Vec<ChatMessage> {
|
||||
let mut summary_found = false;
|
||||
let mut messages = messages
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter(|m| {
|
||||
if summary_found {
|
||||
return matches!(m, ChatMessage::System(_));
|
||||
}
|
||||
if let ChatMessage::Summary(_) = m {
|
||||
summary_found = true;
|
||||
}
|
||||
true
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
messages.reverse();
|
||||
|
||||
messages
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{assistant, tool_output, user};
|
||||
|
||||
use super::*;
|
||||
use swiftide_core::chat_completion::{ChatMessage, ToolCall};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_iteration_tracking() {
|
||||
let mut context = DefaultContext::default();
|
||||
|
||||
// Record initial chat messages
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::System("You are awesome".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
context
|
||||
.add_messages(vec![assistant!("Hey?"), user!("How are you?")])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 4);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
// If the last message is from the assistant, we should not get any more completions
|
||||
context
|
||||
.add_messages(vec![assistant!("I am fine")])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
context.with_stop_on_assistant(false);
|
||||
|
||||
assert!(context.next_completion().await.unwrap().is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_should_complete_after_tool_call() {
|
||||
let context = DefaultContext::default();
|
||||
// Record initial chat messages
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::System("You are awesome".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert_eq!(context.current_new_messages().await.unwrap().len(), 2);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
context
|
||||
.add_messages(vec![
|
||||
assistant!("Hey?", ["test"]),
|
||||
tool_output!("test", "Hoi"),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(context.current_new_messages().await.unwrap().len(), 2);
|
||||
assert_eq!(messages.len(), 4);
|
||||
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_filters_messages_before_summary() {
|
||||
let messages = vec![
|
||||
ChatMessage::System("System message".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
ChatMessage::new_assistant(Some("Hello there"), None),
|
||||
ChatMessage::Summary("Summary message".into()),
|
||||
ChatMessage::User("This should be ignored".into()),
|
||||
];
|
||||
let context = DefaultContext::default();
|
||||
// Record initial chat messages
|
||||
context.add_messages(messages).await.unwrap();
|
||||
|
||||
let new_messages = context.next_completion().await.unwrap().unwrap();
|
||||
|
||||
assert_eq!(new_messages.len(), 3);
|
||||
assert!(matches!(new_messages[0], ChatMessage::System(_)));
|
||||
assert!(matches!(new_messages[1], ChatMessage::Summary(_)));
|
||||
assert!(matches!(new_messages[2], ChatMessage::User(_)));
|
||||
|
||||
let current_new_messages = context.current_new_messages().await.unwrap();
|
||||
assert_eq!(current_new_messages.len(), 3);
|
||||
assert!(matches!(current_new_messages[0], ChatMessage::System(_)));
|
||||
assert!(matches!(current_new_messages[1], ChatMessage::Summary(_)));
|
||||
assert!(matches!(current_new_messages[2], ChatMessage::User(_)));
|
||||
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_filters_messages_before_summary_with_assistant_last() {
|
||||
let messages = vec![
|
||||
ChatMessage::System("System message".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
ChatMessage::new_assistant(Some("Hello there"), None),
|
||||
];
|
||||
let mut context = DefaultContext::default();
|
||||
context.with_stop_on_assistant(false);
|
||||
// Record initial chat messages
|
||||
context.add_messages(messages).await.unwrap();
|
||||
|
||||
let new_messages = context.next_completion().await.unwrap().unwrap();
|
||||
|
||||
assert_eq!(new_messages.len(), 3);
|
||||
assert!(matches!(new_messages[0], ChatMessage::System(_)));
|
||||
assert!(matches!(new_messages[1], ChatMessage::User(_)));
|
||||
assert!(matches!(new_messages[2], ChatMessage::Assistant(..)));
|
||||
|
||||
context
|
||||
.add_message(ChatMessage::Summary("Summary message 1".into()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let new_messages = context.next_completion().await.unwrap().unwrap();
|
||||
dbg!(&new_messages);
|
||||
assert_eq!(new_messages.len(), 2);
|
||||
assert!(matches!(new_messages[0], ChatMessage::System(_)));
|
||||
assert_eq!(
|
||||
new_messages[1],
|
||||
ChatMessage::Summary("Summary message 1".into())
|
||||
);
|
||||
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
let messages = vec![
|
||||
ChatMessage::User("Hello again".into()),
|
||||
ChatMessage::new_assistant(Some("Hello there again"), None),
|
||||
];
|
||||
|
||||
context.add_messages(messages).await.unwrap();
|
||||
|
||||
let new_messages = context.next_completion().await.unwrap().unwrap();
|
||||
|
||||
assert!(matches!(new_messages[0], ChatMessage::System(_)));
|
||||
assert_eq!(
|
||||
new_messages[1],
|
||||
ChatMessage::Summary("Summary message 1".into())
|
||||
);
|
||||
assert_eq!(new_messages[2], ChatMessage::User("Hello again".into()));
|
||||
assert_eq!(
|
||||
new_messages[3],
|
||||
ChatMessage::new_assistant(Some("Hello there again".to_string()), None)
|
||||
);
|
||||
|
||||
context
|
||||
.add_message(ChatMessage::Summary("Summary message 2".into()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let new_messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(new_messages.len(), 2);
|
||||
|
||||
assert!(matches!(new_messages[0], ChatMessage::System(_)));
|
||||
assert_eq!(
|
||||
new_messages[1],
|
||||
ChatMessage::Summary("Summary message 2".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_redrive() {
|
||||
let context = DefaultContext::default();
|
||||
|
||||
// Record initial chat messages
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::System("System message".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
context.redrive().await.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 2);
|
||||
|
||||
context
|
||||
.add_messages(vec![ChatMessage::User("Hey?".into())])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 3);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
context.redrive().await.unwrap();
|
||||
|
||||
// Add more messages
|
||||
context
|
||||
.add_messages(vec![ChatMessage::User("How are you?".into())])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 4);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
// Redrive should remove the last set of messages
|
||||
dbg!(&context);
|
||||
context.redrive().await.unwrap();
|
||||
dbg!(&context);
|
||||
|
||||
// We just redrove with the same messages
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 4);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
// Add more messages
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::User("How are you really?".into()),
|
||||
ChatMessage::User("How are you really?".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// This should remove any additional messages
|
||||
context.redrive().await.unwrap();
|
||||
|
||||
// We just redrove with the same messages
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 4);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
// Redrive again
|
||||
context.redrive().await.unwrap();
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 4);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_next_completion_empty_history() {
|
||||
let context = DefaultContext::default();
|
||||
let next = context.next_completion().await;
|
||||
assert!(next.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_next_completion_out_of_bounds_ptr() {
|
||||
let context = DefaultContext::default();
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::System("System".into()),
|
||||
ChatMessage::User("Hi".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Set completions_ptr beyond the length of messages
|
||||
context
|
||||
.completions_ptr
|
||||
.store(10, std::sync::atomic::Ordering::SeqCst);
|
||||
|
||||
// Should reset the pointer and return the full messages
|
||||
let messages = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(messages.len(), 2);
|
||||
|
||||
// Second call should be empty again
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_replace_history_replaces_and_resets_pointers() {
|
||||
let mut context = DefaultContext::default();
|
||||
context.with_stop_on_assistant(false);
|
||||
|
||||
// Add some initial messages
|
||||
context
|
||||
.add_messages(vec![
|
||||
ChatMessage::System("Initial".into()),
|
||||
ChatMessage::User("Hello".into()),
|
||||
ChatMessage::new_assistant(Some("Hi."), None),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Consume the messages so pointers are moved
|
||||
let orig = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(orig.len(), 3);
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
|
||||
// Replace history with a new set
|
||||
let new_msgs = vec![
|
||||
ChatMessage::System("System2".into()),
|
||||
ChatMessage::User("User2".into()),
|
||||
];
|
||||
context.replace_history(new_msgs.clone()).await.unwrap();
|
||||
|
||||
// After replacement, next_completion should return only the new messages
|
||||
let replaced = context.next_completion().await.unwrap().unwrap();
|
||||
assert_eq!(replaced, new_msgs);
|
||||
|
||||
// Next call should yield None again
|
||||
assert!(context.next_completion().await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use swiftide_core::chat_completion::{
|
||||
ChatCompletionRequestBuilderError,
|
||||
errors::{LanguageModelError, ToolError},
|
||||
};
|
||||
use thiserror::Error;
|
||||
use tokio::task::JoinError;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AgentError {
|
||||
#[error("Agent is already running")]
|
||||
AlreadyRunning,
|
||||
|
||||
#[error("Failed to render system prompt {0:#}")]
|
||||
FailedToRenderSystemPrompt(anyhow::Error),
|
||||
|
||||
#[error("Failed to build chat completion request {0:#}")]
|
||||
FailedToBuildRequest(ChatCompletionRequestBuilderError),
|
||||
|
||||
#[error("Error from LLM when running completions {0:#}")]
|
||||
CompletionsFailed(LanguageModelError),
|
||||
|
||||
#[error(transparent)]
|
||||
ToolError(#[from] ToolError),
|
||||
|
||||
#[error("Failed waiting for tool to finish {0:?}")]
|
||||
ToolFailedToJoin(String, JoinError),
|
||||
|
||||
#[error("Failed to load tools from toolbox {0:#}")]
|
||||
ToolBoxFailedToLoad(anyhow::Error),
|
||||
|
||||
#[error("Chat completion stream was empty")]
|
||||
EmptyStream,
|
||||
|
||||
#[error("Failed to render prompt {0:#}")]
|
||||
FailedToRenderPrompt(anyhow::Error),
|
||||
|
||||
#[error("Error with message history {0:#}")]
|
||||
MessageHistoryError(anyhow::Error),
|
||||
|
||||
#[error("Unfulfilled tool calls remain after invocation")]
|
||||
UnfulfilledToolCalls,
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Hooks are functions that are called at specific points in the agent lifecycle.
|
||||
//!
|
||||
//!
|
||||
//! Since rust does not have async closures, hooks have to return a boxed, pinned async block
|
||||
//! themselves.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # use swiftide_core::{AgentContext, chat_completion::ChatMessage};
|
||||
//! # use swiftide_agents::Agent;
|
||||
//! # fn test() {
|
||||
//! # let mut agent = swiftide_agents::Agent::builder();
|
||||
//! agent.before_all(move |agent: &Agent| {
|
||||
//! Box::pin(async move {
|
||||
//! agent.context().add_message(ChatMessage::new_user("Hello, world")).await;
|
||||
//! Ok(())
|
||||
//! })
|
||||
//! });
|
||||
//! # }
|
||||
//! ```
|
||||
//! Rust has a long outstanding issue where it captures outer lifetimes when returning an impl
|
||||
//! that also has lifetimes, see [this issue](https://github.com/rust-lang/rust/issues/42940)
|
||||
//!
|
||||
//! This can happen if you write a method like `fn return_hook(&self) -> impl HookFn`, where the
|
||||
//! owner also has a lifetime.
|
||||
//! The trick is to set an explicit lifetime on self, and hook, where self must outlive the hook.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # use swiftide_core::{AgentContext};
|
||||
//! # use swiftide_agents::hooks::BeforeAllFn;
|
||||
//! # use swiftide_agents::Agent;
|
||||
//! struct SomeHook<'thing> {
|
||||
//! thing: &'thing str
|
||||
//! }
|
||||
//!
|
||||
//! impl<'thing> SomeHook<'thing> {
|
||||
//! fn return_hook<'tool>(&'thing self) -> impl BeforeAllFn + 'tool where 'thing: 'tool {
|
||||
//! move |_: &Agent| {
|
||||
//! Box::pin(async move {{ Ok(())}})
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
use anyhow::Result;
|
||||
use std::{future::Future, pin::Pin};
|
||||
|
||||
use dyn_clone::DynClone;
|
||||
use swiftide_core::chat_completion::{
|
||||
ChatCompletionRequest, ChatCompletionResponse, ChatMessage, ToolCall, ToolOutput,
|
||||
errors::ToolError,
|
||||
};
|
||||
|
||||
use crate::{Agent, errors::AgentError, state::StopReason};
|
||||
|
||||
pub trait BeforeAllFn:
|
||||
for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(BeforeAllFn);
|
||||
|
||||
pub trait AfterEachFn:
|
||||
for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(AfterEachFn);
|
||||
|
||||
pub trait BeforeCompletionFn:
|
||||
for<'a> Fn(
|
||||
&'a Agent,
|
||||
&mut ChatCompletionRequest<'_>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(BeforeCompletionFn);
|
||||
|
||||
pub trait AfterCompletionFn:
|
||||
for<'a> Fn(
|
||||
&'a Agent,
|
||||
&mut ChatCompletionResponse,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(AfterCompletionFn);
|
||||
|
||||
/// Hooks that are called after each tool
|
||||
pub trait AfterToolFn:
|
||||
for<'tool> Fn(
|
||||
&'tool Agent,
|
||||
&ToolCall,
|
||||
&'tool mut Result<ToolOutput, ToolError>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'tool>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(AfterToolFn);
|
||||
|
||||
/// Hooks that are called before each tool
|
||||
pub trait BeforeToolFn:
|
||||
for<'a> Fn(&'a Agent, &ToolCall) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(BeforeToolFn);
|
||||
|
||||
/// Hooks that are called when a new message is added to the `AgentContext`
|
||||
pub trait MessageHookFn:
|
||||
for<'a> Fn(&'a Agent, &mut ChatMessage) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(MessageHookFn);
|
||||
|
||||
/// Hooks that are called when the agent starts, either from pending or stopped
|
||||
pub trait OnStartFn:
|
||||
for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(OnStartFn);
|
||||
|
||||
/// Hooks that are called when the agent stop
|
||||
pub trait OnStopFn:
|
||||
for<'a> Fn(
|
||||
&'a Agent,
|
||||
StopReason,
|
||||
Option<&AgentError>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(OnStopFn);
|
||||
|
||||
pub trait OnStreamFn:
|
||||
for<'a> Fn(
|
||||
&'a Agent,
|
||||
&ChatCompletionResponse,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(OnStreamFn);
|
||||
|
||||
/// Wrapper around the different types of hooks
|
||||
#[derive(Clone, strum_macros::EnumDiscriminants, strum_macros::Display)]
|
||||
#[strum_discriminants(name(HookTypes), derive(strum_macros::Display))]
|
||||
pub enum Hook {
|
||||
/// Runs only once for the agent when it starts
|
||||
BeforeAll(Box<dyn BeforeAllFn>),
|
||||
/// Runs before every completion, yielding a mutable reference to the completion request
|
||||
BeforeCompletion(Box<dyn BeforeCompletionFn>),
|
||||
/// Runs after every completion, yielding a mutable reference to the completion response
|
||||
AfterCompletion(Box<dyn AfterCompletionFn>),
|
||||
/// Runs before every tool call, yielding a reference to the tool call
|
||||
BeforeTool(Box<dyn BeforeToolFn>),
|
||||
/// Runs after every tool call, yielding a reference to the tool call and a mutable result
|
||||
AfterTool(Box<dyn AfterToolFn>),
|
||||
/// Runs after all tools have completed and a single completion has been made
|
||||
AfterEach(Box<dyn AfterEachFn>),
|
||||
/// Runs when a new message is added to the `AgentContext`, yielding a mutable reference to the
|
||||
/// message. This is only triggered when the message is added by the agent.
|
||||
OnNewMessage(Box<dyn MessageHookFn>),
|
||||
/// Runs when the agent starts, either from pending or stopped
|
||||
OnStart(Box<dyn OnStartFn>),
|
||||
/// Runs when the agent stops
|
||||
OnStop(Box<dyn OnStopFn>),
|
||||
/// Runs when the agent streams a response
|
||||
OnStream(Box<dyn OnStreamFn>),
|
||||
}
|
||||
|
||||
impl<F> BeforeAllFn for F where
|
||||
F: for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> AfterEachFn for F where
|
||||
F: for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> BeforeCompletionFn for F where
|
||||
F: for<'a> Fn(
|
||||
&'a Agent,
|
||||
&mut ChatCompletionRequest<'_>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> AfterCompletionFn for F where
|
||||
F: for<'a> Fn(
|
||||
&'a Agent,
|
||||
&mut ChatCompletionResponse,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> BeforeToolFn for F where
|
||||
F: for<'a> Fn(&'a Agent, &ToolCall) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
impl<F> AfterToolFn for F where
|
||||
F: for<'tool> Fn(
|
||||
&'tool Agent,
|
||||
&ToolCall,
|
||||
&'tool mut Result<ToolOutput, ToolError>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'tool>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> MessageHookFn for F where
|
||||
F: for<'a> Fn(
|
||||
&'a Agent,
|
||||
&mut ChatMessage,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> OnStartFn for F where
|
||||
F: for<'a> Fn(&'a Agent) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> OnStopFn for F where
|
||||
F: for<'a> Fn(
|
||||
&'a Agent,
|
||||
StopReason,
|
||||
Option<&AgentError>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
impl<F> OnStreamFn for F where
|
||||
F: for<'a> Fn(
|
||||
&'a Agent,
|
||||
&ChatCompletionResponse,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ DynClone
|
||||
{
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::Agent;
|
||||
|
||||
#[test]
|
||||
fn test_hooks_compile_sync_and_async() {
|
||||
Agent::builder()
|
||||
.before_all(|_| Box::pin(async { Ok(()) }))
|
||||
.on_start(|_| Box::pin(async { Ok(()) }))
|
||||
.before_completion(|_, _| Box::pin(async { Ok(()) }))
|
||||
.before_tool(|_, _| Box::pin(async { Ok(()) }))
|
||||
.after_tool(|_, _, _| Box::pin(async { Ok(()) }))
|
||||
.after_completion(|_, _| Box::pin(async { Ok(()) }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// show feature flags in the generated documentation
|
||||
// https://doc.rust-lang.org/rustdoc/unstable-features.html#extensions-to-the-doc-attribute
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(docsrs, doc(auto_cfg))]
|
||||
#![doc(html_logo_url = "https://github.com/bosun-ai/swiftide/raw/master/images/logo.png")]
|
||||
|
||||
//! Swiftide agents are a flexible way to build fast and reliable AI agents.
|
||||
//!
|
||||
//! # Features
|
||||
//!
|
||||
//! * **Tools**: Tools can be defined as functions using the `#[tool]` attribute macro, the `Tool`
|
||||
//! derive macro, or manually implementing the `Tool` trait.
|
||||
//! * **Hooks**: At various stages of the agent lifecycle, hooks can be defined to run custom logic.
|
||||
//! These are defined when building the agent, and each take a closure.
|
||||
//! * **Context**: Agents operate in an `AgentContext`, which is a shared state between tools and
|
||||
//! hooks. The context is responsible for managing the completions and interacting with the
|
||||
//! outside world.
|
||||
//! * **Tool Execution**: A context takes a tool executor (local by default) to execute its tools
|
||||
//! on. This enables tools to be run i.e. in containers, remote, etc.
|
||||
//! * **System prompt defaults**: `SystemPrompt` provides a default, customizable prompt for the
|
||||
//! agent. If you want to provider your own prompt, the builder takes anything that converts into
|
||||
//! a `Prompt`, including strings.
|
||||
//! * **Open Telemetry**: Agents are fully instrumented with open telemetry.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```ignore
|
||||
//! # use swiftide_agents::Agent;
|
||||
//! # use swiftide_integrations as integrations;
|
||||
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let openai = integrations::openai::OpenAI::builder()
|
||||
//! .default_prompt_model("gpt-4o-mini")
|
||||
//! .build()?;
|
||||
//!
|
||||
//! Agent::builder()
|
||||
//! .llm(&openai)
|
||||
//! .before_completion(move |_,_|
|
||||
//! Box::pin(async move {
|
||||
//! println!("Before each tool");
|
||||
//! Ok(())
|
||||
//! })
|
||||
//! )
|
||||
//! .build()?
|
||||
//! .query("What is the meaning of life?")
|
||||
//! .await?;
|
||||
//! # return Ok(());
|
||||
//!
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Agents run in a loop as long as they have new messages to process.
|
||||
mod agent;
|
||||
mod default_context;
|
||||
pub mod errors;
|
||||
pub mod hooks;
|
||||
mod state;
|
||||
pub mod system_prompt;
|
||||
pub mod tasks;
|
||||
pub mod tools;
|
||||
mod util;
|
||||
|
||||
pub use agent::{Agent, AgentBuilder, AgentBuilderError};
|
||||
pub use default_context::DefaultContext;
|
||||
pub use state::{State, StopReason};
|
||||
|
||||
#[cfg(any(test, debug_assertions))]
|
||||
pub mod test_utils;
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: swiftide-agents/src/system_prompt.rs
|
||||
expression: rendered
|
||||
---
|
||||
# Your role
|
||||
|
||||
special role
|
||||
# Guidelines you need to follow
|
||||
|
||||
- Try to understand how to complete the task well before completing it.
|
||||
- special guideline
|
||||
|
||||
|
||||
# Constraints that must be adhered to
|
||||
|
||||
- Think step by step
|
||||
- Think before you act; respond with your thoughts before calling tools
|
||||
- Do not make up any assumptions, use tools to get the information you need
|
||||
- Use the provided tools to interact with the system and accomplish the task
|
||||
- If you are stuck, or otherwise cannot complete the task, respond with your thoughts and call `stop`.
|
||||
- If the task is completed, or otherwise cannot continue, like requiring user feedback, call `stop`.
|
||||
- special constraint
|
||||
|
||||
|
||||
# Response Format
|
||||
|
||||
- Always respond with your thoughts and reasoning for your actions in one or two sentences. Even when calling tools.
|
||||
- Once the goal is achieved, call the `stop` tool
|
||||
|
||||
some additional info
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
source: swiftide-agents/src/system_prompt.rs
|
||||
expression: rendered
|
||||
---
|
||||
# Your role
|
||||
|
||||
special role
|
||||
# Guidelines you need to follow
|
||||
|
||||
- Try to understand how to complete the task well before completing it.
|
||||
- special guideline
|
||||
|
||||
|
||||
# Constraints that must be adhered to
|
||||
|
||||
- Think step by step
|
||||
- Think before you act; respond with your thoughts before calling tools
|
||||
- Do not make up any assumptions, use tools to get the information you need
|
||||
- Use the provided tools to interact with the system and accomplish the task
|
||||
- If you are stuck, or otherwise cannot complete the task, respond with your thoughts and call `stop`.
|
||||
- If the task is completed, or otherwise cannot continue, like requiring user feedback, call `stop`.
|
||||
- special constraint
|
||||
|
||||
|
||||
# Response Format
|
||||
|
||||
- Always respond with your thoughts and reasoning for your actions in one or two sentences. Even when calling tools.
|
||||
- Once the goal is achieved, call the `stop` tool
|
||||
|
||||
some additional info
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Internal state of the agent
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use swiftide_core::chat_completion::ToolCall;
|
||||
|
||||
#[derive(Clone, Debug, Default, strum_macros::EnumDiscriminants, strum_macros::EnumIs)]
|
||||
pub enum State {
|
||||
#[default]
|
||||
Pending,
|
||||
Running,
|
||||
Stopped(StopReason),
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn stop_reason(&self) -> Option<&StopReason> {
|
||||
match self {
|
||||
State::Stopped(reason) => Some(reason),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason the agent stopped
|
||||
///
|
||||
/// `StopReason::Other` has some convenience methods to convert from any `AsRef<str>`
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Debug, strum_macros::EnumIs, PartialEq, Serialize, Deserialize)]
|
||||
pub enum StopReason {
|
||||
/// A tool called stop
|
||||
RequestedByTool(ToolCall, Option<Value>),
|
||||
|
||||
/// Agent failed to complete with optional message
|
||||
AgentFailed(Option<Value>),
|
||||
|
||||
/// A tool repeatedly failed
|
||||
ToolCallsOverLimit(ToolCall),
|
||||
|
||||
/// A tool requires feedback before it will continue
|
||||
FeedbackRequired {
|
||||
tool_call: ToolCall,
|
||||
payload: Option<serde_json::Value>,
|
||||
},
|
||||
/// There was an error
|
||||
Error,
|
||||
|
||||
/// No new messages; stopping completions
|
||||
NoNewMessages,
|
||||
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl StopReason {
|
||||
pub fn as_requested_by_tool(&self) -> Option<(&ToolCall, Option<&Value>)> {
|
||||
if let StopReason::RequestedByTool(t, message) = self {
|
||||
Some((t, message.as_ref()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_tool_calls_over_limit(&self) -> Option<&ToolCall> {
|
||||
if let StopReason::ToolCallsOverLimit(t) = self {
|
||||
Some(t)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_feedback_required(&self) -> Option<(&ToolCall, Option<&serde_json::Value>)> {
|
||||
if let StopReason::FeedbackRequired { tool_call, payload } = self {
|
||||
Some((tool_call, payload.as_ref()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_error(&self) -> Option<()> {
|
||||
if matches!(self, StopReason::Error) {
|
||||
Some(())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_no_new_messages(&self) -> Option<()> {
|
||||
if matches!(self, StopReason::NoNewMessages) {
|
||||
Some(())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_other(&self) -> Option<&str> {
|
||||
if let StopReason::Other(s) = self {
|
||||
Some(s)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for StopReason {
|
||||
fn default() -> Self {
|
||||
StopReason::Other("No reason provided".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: AsRef<str>> From<S> for StopReason {
|
||||
fn from(value: S) -> Self {
|
||||
StopReason::Other(value.as_ref().to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
//! The system prompt is the initial role and constraint defining message the LLM will receive for
|
||||
//! completion.
|
||||
//!
|
||||
//! By default, the system prompt is setup as a general-purpose chain-of-thought reasoning prompt
|
||||
//! with the role, guidelines, and constraints left empty for customization.
|
||||
//!
|
||||
//! You can override the the template entirely by providing your own `Prompt`. Optionally, you can
|
||||
//! still use the builder values by referencing them in your template.
|
||||
//!
|
||||
//! The builder provides an accessible way to build a system prompt.
|
||||
//!
|
||||
//! The agent will convert the system prompt into a prompt, adding it to the messages list the
|
||||
//! first time it is called.
|
||||
//!
|
||||
//! For customization, either the builder can be used to profit from defaults, or an override can
|
||||
//! be provided on the agent level.
|
||||
|
||||
use derive_builder::Builder;
|
||||
use swiftide_core::prompt::Prompt;
|
||||
|
||||
#[derive(Clone, Debug, Builder)]
|
||||
#[builder(setter(into, strip_option))]
|
||||
pub struct SystemPrompt {
|
||||
/// The role the agent is expected to fulfil.
|
||||
#[builder(default)]
|
||||
role: Option<String>,
|
||||
|
||||
/// Additional guidelines for the agent to follow
|
||||
#[builder(default, setter(custom))]
|
||||
guidelines: Vec<String>,
|
||||
/// Additional constraints
|
||||
#[builder(default, setter(custom))]
|
||||
constraints: Vec<String>,
|
||||
|
||||
/// Optional additional raw markdown to append to the prompt
|
||||
///
|
||||
/// For instance, if you would like to support an AGENTS.md file, add it here.
|
||||
#[builder(default)]
|
||||
additional: Option<String>,
|
||||
|
||||
/// The template to use for the system prompt
|
||||
#[builder(default = default_prompt_template())]
|
||||
template: Prompt,
|
||||
}
|
||||
|
||||
impl SystemPrompt {
|
||||
pub fn builder() -> SystemPromptBuilder {
|
||||
SystemPromptBuilder::default()
|
||||
}
|
||||
|
||||
pub fn to_prompt(&self) -> Prompt {
|
||||
self.clone().into()
|
||||
}
|
||||
|
||||
/// Adds a guideline to the guidelines list.
|
||||
pub fn with_added_guideline(&mut self, guideline: impl AsRef<str>) -> &mut Self {
|
||||
self.guidelines.push(guideline.as_ref().to_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a constraint to the constraints list.
|
||||
pub fn with_added_constraint(&mut self, constraint: impl AsRef<str>) -> &mut Self {
|
||||
self.constraints.push(constraint.as_ref().to_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// Overwrites all guidelines.
|
||||
pub fn with_guidelines<T: IntoIterator<Item = S>, S: AsRef<str>>(
|
||||
&mut self,
|
||||
guidelines: T,
|
||||
) -> &mut Self {
|
||||
self.guidelines = guidelines
|
||||
.into_iter()
|
||||
.map(|s| s.as_ref().to_string())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Overwrites all constraints.
|
||||
pub fn with_constraints<T: IntoIterator<Item = S>, S: AsRef<str>>(
|
||||
&mut self,
|
||||
constraints: T,
|
||||
) -> &mut Self {
|
||||
self.constraints = constraints
|
||||
.into_iter()
|
||||
.map(|s| s.as_ref().to_string())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Changes the role.
|
||||
pub fn with_role(&mut self, role: impl Into<String>) -> &mut Self {
|
||||
self.role = Some(role.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the additional markdown field.
|
||||
pub fn with_additional(&mut self, additional: impl Into<String>) -> &mut Self {
|
||||
self.additional = Some(additional.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the template.
|
||||
pub fn with_template(&mut self, template: impl Into<Prompt>) -> &mut Self {
|
||||
self.template = template.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for SystemPrompt {
|
||||
fn from(text: String) -> Self {
|
||||
SystemPrompt {
|
||||
role: None,
|
||||
guidelines: Vec::new(),
|
||||
constraints: Vec::new(),
|
||||
additional: None,
|
||||
template: text.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for SystemPrompt {
|
||||
fn from(text: &'static str) -> Self {
|
||||
SystemPrompt {
|
||||
role: None,
|
||||
guidelines: Vec::new(),
|
||||
constraints: Vec::new(),
|
||||
additional: None,
|
||||
template: text.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SystemPrompt> for SystemPromptBuilder {
|
||||
fn from(val: SystemPrompt) -> Self {
|
||||
SystemPromptBuilder {
|
||||
role: Some(val.role),
|
||||
guidelines: Some(val.guidelines),
|
||||
constraints: Some(val.constraints),
|
||||
additional: Some(val.additional),
|
||||
template: Some(val.template),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Prompt> for SystemPrompt {
|
||||
fn from(prompt: Prompt) -> Self {
|
||||
SystemPrompt {
|
||||
role: None,
|
||||
guidelines: Vec::new(),
|
||||
constraints: Vec::new(),
|
||||
additional: None,
|
||||
template: prompt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SystemPrompt {
|
||||
fn default() -> Self {
|
||||
SystemPrompt {
|
||||
role: None,
|
||||
guidelines: Vec::new(),
|
||||
constraints: Vec::new(),
|
||||
additional: None,
|
||||
template: default_prompt_template(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SystemPromptBuilder {
|
||||
pub fn add_guideline(&mut self, guideline: &str) -> &mut Self {
|
||||
self.guidelines
|
||||
.get_or_insert_with(Vec::new)
|
||||
.push(guideline.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_constraint(&mut self, constraint: &str) -> &mut Self {
|
||||
self.constraints
|
||||
.get_or_insert_with(Vec::new)
|
||||
.push(constraint.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn guidelines<T: IntoIterator<Item = S>, S: AsRef<str>>(
|
||||
&mut self,
|
||||
guidelines: T,
|
||||
) -> &mut Self {
|
||||
self.guidelines = Some(
|
||||
guidelines
|
||||
.into_iter()
|
||||
.map(|s| s.as_ref().to_string())
|
||||
.collect(),
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn constraints<T: IntoIterator<Item = S>, S: AsRef<str>>(
|
||||
&mut self,
|
||||
constraints: T,
|
||||
) -> &mut Self {
|
||||
self.constraints = Some(
|
||||
constraints
|
||||
.into_iter()
|
||||
.map(|s| s.as_ref().to_string())
|
||||
.collect(),
|
||||
);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn default_prompt_template() -> Prompt {
|
||||
include_str!("system_prompt_template.md").into()
|
||||
}
|
||||
|
||||
#[allow(clippy::from_over_into)]
|
||||
impl Into<Prompt> for SystemPrompt {
|
||||
fn into(self) -> Prompt {
|
||||
let SystemPrompt {
|
||||
role,
|
||||
guidelines,
|
||||
constraints,
|
||||
template,
|
||||
additional,
|
||||
} = self;
|
||||
|
||||
template
|
||||
.with_context_value("role", role)
|
||||
.with_context_value("guidelines", guidelines)
|
||||
.with_context_value("constraints", constraints)
|
||||
.with_context_value("additional", additional)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_customization() {
|
||||
let prompt = SystemPrompt::builder()
|
||||
.role("special role")
|
||||
.guidelines(["special guideline"])
|
||||
.constraints(vec!["special constraint".to_string()])
|
||||
.additional("some additional info")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let prompt: Prompt = prompt.into();
|
||||
|
||||
let rendered = prompt.render().unwrap();
|
||||
|
||||
assert!(rendered.contains("special role"), "error: {rendered}");
|
||||
assert!(rendered.contains("special guideline"), "error: {rendered}");
|
||||
assert!(rendered.contains("special constraint"), "error: {rendered}");
|
||||
assert!(
|
||||
rendered.contains("some additional info"),
|
||||
"error: {rendered}"
|
||||
);
|
||||
|
||||
insta::assert_snapshot!(rendered);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_to_prompt() {
|
||||
let prompt = SystemPrompt::builder()
|
||||
.role("special role")
|
||||
.guidelines(["special guideline"])
|
||||
.constraints(vec!["special constraint".to_string()])
|
||||
.additional("some additional info")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let prompt: Prompt = prompt.to_prompt();
|
||||
|
||||
let rendered = prompt.render().unwrap();
|
||||
|
||||
assert!(rendered.contains("special role"), "error: {rendered}");
|
||||
assert!(rendered.contains("special guideline"), "error: {rendered}");
|
||||
assert!(rendered.contains("special constraint"), "error: {rendered}");
|
||||
assert!(
|
||||
rendered.contains("some additional info"),
|
||||
"error: {rendered}"
|
||||
);
|
||||
|
||||
insta::assert_snapshot!(rendered);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_system_prompt_to_builder() {
|
||||
let sp = SystemPrompt {
|
||||
role: Some("Assistant".to_string()),
|
||||
guidelines: vec!["Be concise".to_string()],
|
||||
constraints: vec!["No personal opinions".to_string()],
|
||||
additional: None,
|
||||
template: "Hello, {{role}}! Guidelines: {{guidelines}}, Constraints: {{constraints}}"
|
||||
.into(),
|
||||
};
|
||||
|
||||
let builder = SystemPromptBuilder::from(sp.clone());
|
||||
|
||||
assert_eq!(builder.role, Some(Some("Assistant".to_string())));
|
||||
assert_eq!(builder.guidelines, Some(vec!["Be concise".to_string()]));
|
||||
assert_eq!(
|
||||
builder.constraints,
|
||||
Some(vec!["No personal opinions".to_string()])
|
||||
);
|
||||
// For template, compare the rendered string
|
||||
assert_eq!(
|
||||
builder.template.as_ref().unwrap().render().unwrap(),
|
||||
sp.template.render().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_added_guideline_and_constraint() {
|
||||
let mut sp = SystemPrompt::default();
|
||||
sp.with_added_guideline("Stay polite")
|
||||
.with_added_guideline("Use Markdown")
|
||||
.with_added_constraint("No personal info")
|
||||
.with_added_constraint("Short responses");
|
||||
|
||||
assert_eq!(sp.guidelines, vec!["Stay polite", "Use Markdown"]);
|
||||
assert_eq!(sp.constraints, vec!["No personal info", "Short responses"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_guidelines_and_constraints_overwrites() {
|
||||
let mut sp = SystemPrompt::default();
|
||||
sp.with_guidelines(["A", "B", "C"])
|
||||
.with_constraints(vec!["X", "Y"]);
|
||||
|
||||
assert_eq!(sp.guidelines, vec!["A", "B", "C"]);
|
||||
assert_eq!(sp.constraints, vec!["X", "Y"]);
|
||||
|
||||
// Overwrite with different contents
|
||||
sp.with_guidelines(vec!["Z"]);
|
||||
sp.with_constraints(["P", "Q"]);
|
||||
assert_eq!(sp.guidelines, vec!["Z"]);
|
||||
assert_eq!(sp.constraints, vec!["P", "Q"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_role_and_additional_and_template() {
|
||||
let mut sp = SystemPrompt::default();
|
||||
sp.with_role("explainer")
|
||||
.with_additional("AGENTS.md here")
|
||||
.with_template("Template: {{role}}");
|
||||
|
||||
assert_eq!(sp.role.as_deref(), Some("explainer"));
|
||||
assert_eq!(sp.additional.as_deref(), Some("AGENTS.md here"));
|
||||
assert_eq!(sp.template.render().unwrap(), "Template: {{role}}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{% if role -%}
|
||||
|
||||
# Your role
|
||||
|
||||
{{role}}
|
||||
{% endif -%}
|
||||
|
||||
# Guidelines you need to follow
|
||||
|
||||
{# Guidelines provide soft rules and best practices to complete a task well -#}
|
||||
|
||||
- Try to understand how to complete the task well before completing it.
|
||||
{% for item in guidelines -%}
|
||||
- {{item}}
|
||||
{% endfor %}
|
||||
|
||||
# Constraints that must be adhered to
|
||||
|
||||
{# Constraints are hard limitations that an agent must follow -#}
|
||||
|
||||
- Think step by step
|
||||
- Think before you act; respond with your thoughts before calling tools
|
||||
- Do not make up any assumptions, use tools to get the information you need
|
||||
- Use the provided tools to interact with the system and accomplish the task
|
||||
- If you are stuck, or otherwise cannot complete the task, respond with your thoughts and call `stop`.
|
||||
- If the task is completed, or otherwise cannot continue, like requiring user feedback, call `stop`.
|
||||
{% for item in constraints -%}
|
||||
- {{item}}
|
||||
{% endfor %}
|
||||
|
||||
# Response Format
|
||||
|
||||
{# Instruct the agent to always respond with their thoughts (chain-of-thought) -#}
|
||||
|
||||
- Always respond with your thoughts and reasoning for your actions in one or two sentences. Even when calling tools.
|
||||
- Once the goal is achieved, call the `stop` tool
|
||||
|
||||
{{additional}}
|
||||
@@ -0,0 +1,132 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{
|
||||
errors::NodeError,
|
||||
node::{NodeArg, NodeId, TaskNode},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SyncFn<F, I, O>
|
||||
where
|
||||
F: Fn(&I) -> Result<O, NodeError> + Send + Sync + Clone + 'static,
|
||||
{
|
||||
pub f: F,
|
||||
_phantom: std::marker::PhantomData<(I, O)>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AsyncFn<F, I, O>
|
||||
where
|
||||
F: for<'a> Fn(&'a I) -> Pin<Box<dyn Future<Output = Result<O, NodeError>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
pub f: F,
|
||||
_phantom: std::marker::PhantomData<(I, O)>,
|
||||
}
|
||||
|
||||
impl<F, I, O> SyncFn<F, I, O>
|
||||
where
|
||||
F: Fn(&I) -> Result<O, NodeError> + Send + Sync + Clone + 'static,
|
||||
I: NodeArg + Clone,
|
||||
O: NodeArg + Clone,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
SyncFn {
|
||||
f,
|
||||
_phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, I, O> AsyncFn<F, I, O>
|
||||
where
|
||||
F: for<'a> Fn(&'a I) -> Pin<Box<dyn Future<Output = Result<O, NodeError>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Clone
|
||||
+ 'static,
|
||||
I: NodeArg + Clone,
|
||||
O: NodeArg + Clone,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
AsyncFn {
|
||||
f,
|
||||
_phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> From<F> for SyncFn<F, (), ()>
|
||||
where
|
||||
F: Fn(&()) -> Result<(), NodeError> + Send + Sync + Clone + 'static,
|
||||
{
|
||||
fn from(f: F) -> Self {
|
||||
SyncFn::new(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> From<F> for AsyncFn<F, (), ()>
|
||||
where
|
||||
F: for<'a> Fn(&'a ()) -> Pin<Box<dyn Future<Output = Result<(), NodeError>> + Send + 'a>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fn from(f: F) -> Self {
|
||||
AsyncFn::new(f)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<F, I, O> TaskNode for SyncFn<F, I, O>
|
||||
where
|
||||
F: Fn(&I) -> Result<O, NodeError> + Clone + Send + Sync + 'static,
|
||||
I: NodeArg + Clone,
|
||||
O: NodeArg + Clone,
|
||||
{
|
||||
type Input = I;
|
||||
type Output = O;
|
||||
type Error = NodeError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
(self.f)(input)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<F, I, O> TaskNode for AsyncFn<F, I, O>
|
||||
where
|
||||
F: for<'a> Fn(&'a I) -> Pin<Box<dyn Future<Output = Result<O, NodeError>> + Send + 'a>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
I: NodeArg + Clone,
|
||||
O: NodeArg + Clone,
|
||||
{
|
||||
type Input = I;
|
||||
type Output = O;
|
||||
type Error = NodeError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
(self.f)(input).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use std::{any::Any, sync::Arc};
|
||||
|
||||
use super::transition::TransitionPayload;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum TaskError {
|
||||
#[error(transparent)]
|
||||
NodeError(#[from] NodeError),
|
||||
|
||||
#[error("MissingTransition: {0}")]
|
||||
MissingTransition(String),
|
||||
|
||||
#[error("MissingNode: {0}")]
|
||||
MissingNode(String),
|
||||
|
||||
#[error("Task failed with wrong output")]
|
||||
TypeError(String),
|
||||
|
||||
#[error("MissingInput: {0}")]
|
||||
MissingInput(String),
|
||||
|
||||
#[error("MissingOutput: {0}")]
|
||||
MissingOutput(String),
|
||||
|
||||
#[error("Task is missing steps")]
|
||||
NoSteps,
|
||||
}
|
||||
|
||||
impl TaskError {
|
||||
pub fn missing_transition(node_id: usize) -> Self {
|
||||
TaskError::MissingTransition(format!("Node {node_id} is missing a transition"))
|
||||
}
|
||||
|
||||
pub fn missing_node(node_id: usize) -> Self {
|
||||
TaskError::MissingNode(format!("Node {node_id} is missing"))
|
||||
}
|
||||
|
||||
pub fn missing_input(node_id: usize) -> Self {
|
||||
TaskError::MissingInput(format!("Node {node_id} is missing input"))
|
||||
}
|
||||
|
||||
pub fn missing_output(node_id: usize) -> Self {
|
||||
TaskError::MissingOutput(format!("Node {node_id} is missing output"))
|
||||
}
|
||||
|
||||
pub fn type_error<T: Any + Send>(output: &T) -> Self {
|
||||
let message = format!(
|
||||
"Expected output of type {}, but got {:?}",
|
||||
std::any::type_name::<T>(),
|
||||
output.type_id()
|
||||
);
|
||||
TaskError::TypeError(message)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub struct NodeError {
|
||||
pub node_error: Box<dyn std::error::Error + Send + Sync>,
|
||||
pub transition_payload: Option<Arc<TransitionPayload>>,
|
||||
pub node_id: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NodeError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Node error in node {}: {:?}",
|
||||
self.node_id, self.node_error
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeError {
|
||||
pub fn new(
|
||||
node_error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
|
||||
node_id: usize,
|
||||
transition_payload: Option<TransitionPayload>,
|
||||
) -> Self {
|
||||
Self {
|
||||
node_error: node_error.into(),
|
||||
transition_payload: transition_payload.map(Arc::new),
|
||||
node_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use swiftide_core::{
|
||||
ChatCompletion, Command, CommandError, CommandOutput, SimplePrompt, ToolExecutor,
|
||||
chat_completion::{ChatCompletionRequest, ChatCompletionResponse, errors::LanguageModelError},
|
||||
prompt::Prompt,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{Agent, errors::AgentError};
|
||||
|
||||
use super::node::{NodeArg, NodeId, TaskNode};
|
||||
|
||||
/// An example of wrapping an Agent as a `TaskNode`
|
||||
///
|
||||
/// For more control you can always roll your own
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TaskAgent(Arc<Mutex<Agent>>);
|
||||
|
||||
impl From<Agent> for TaskAgent {
|
||||
fn from(agent: Agent) -> Self {
|
||||
TaskAgent(Arc::new(Mutex::new(agent)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A 'default' implementation for an agent where there is no output
|
||||
#[async_trait]
|
||||
impl TaskNode for TaskAgent {
|
||||
type Input = Prompt;
|
||||
|
||||
type Output = ();
|
||||
|
||||
type Error = AgentError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.0.lock().await.query(input.clone()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Box<dyn SimplePrompt> {
|
||||
type Input = Prompt;
|
||||
|
||||
type Output = String;
|
||||
|
||||
type Error = LanguageModelError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
// TODO: Prompt should be borrowed
|
||||
self.prompt(input.clone()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Arc<dyn SimplePrompt> {
|
||||
type Input = Prompt;
|
||||
|
||||
type Output = String;
|
||||
|
||||
type Error = LanguageModelError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
// TODO: Prompt should be borrowed
|
||||
self.prompt(input.clone()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Box<dyn ChatCompletion> {
|
||||
type Input = ChatCompletionRequest<'static>;
|
||||
|
||||
type Output = ChatCompletionResponse;
|
||||
|
||||
type Error = LanguageModelError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.complete(input).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Arc<dyn ChatCompletion> {
|
||||
type Input = ChatCompletionRequest<'static>;
|
||||
|
||||
type Output = ChatCompletionResponse;
|
||||
|
||||
type Error = LanguageModelError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.complete(input).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Box<dyn ToolExecutor> {
|
||||
type Input = Command;
|
||||
|
||||
type Output = CommandOutput;
|
||||
|
||||
type Error = CommandError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.exec_cmd(input).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskNode for Arc<dyn ToolExecutor> {
|
||||
type Input = Command;
|
||||
|
||||
type Output = CommandOutput;
|
||||
|
||||
type Error = CommandError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.exec_cmd(input).await
|
||||
}
|
||||
}
|
||||
|
||||
// Note: This only works for function pointers, not closures.
|
||||
#[async_trait]
|
||||
impl<I: NodeArg, O: NodeArg, E: std::error::Error + Send + Sync + 'static> TaskNode
|
||||
for fn(&I) -> Result<O, E>
|
||||
{
|
||||
type Input = I;
|
||||
|
||||
type Output = O;
|
||||
|
||||
type Error = E;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
(self)(input)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod closures;
|
||||
pub mod errors;
|
||||
pub mod impls;
|
||||
pub mod node;
|
||||
pub mod task;
|
||||
pub mod transition;
|
||||
@@ -0,0 +1,160 @@
|
||||
use std::any::Any;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use dyn_clone::DynClone;
|
||||
|
||||
use super::{
|
||||
errors::NodeError,
|
||||
transition::{MarkedTransitionPayload, TransitionPayload},
|
||||
};
|
||||
|
||||
pub trait NodeArg: Send + Sync + DynClone + 'static {}
|
||||
|
||||
impl<T: Send + Sync + std::fmt::Debug + 'static + Clone> NodeArg for T {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NoopNode<Context: NodeArg> {
|
||||
_marker: std::marker::PhantomData<(Context, Box<dyn std::error::Error + Send + Sync>)>,
|
||||
}
|
||||
|
||||
impl<Context> Default for NoopNode<Context>
|
||||
where
|
||||
Context: NodeArg,
|
||||
{
|
||||
fn default() -> Self {
|
||||
NoopNode {
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Context: NodeArg + Clone> TaskNode for NoopNode<Context> {
|
||||
type Output = ();
|
||||
type Input = Context;
|
||||
type Error = NodeError;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &DynNodeId<Self>,
|
||||
_context: &Context,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TaskNode: Send + Sync + DynClone + Any {
|
||||
type Input: NodeArg;
|
||||
type Output: NodeArg;
|
||||
type Error: std::error::Error + Send + Sync + 'static;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
node_id: &DynNodeId<Self>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error>;
|
||||
}
|
||||
|
||||
pub type DynNodeId<T> = NodeId<
|
||||
dyn TaskNode<
|
||||
Input = <T as TaskNode>::Input,
|
||||
Output = <T as TaskNode>::Output,
|
||||
Error = <T as TaskNode>::Error,
|
||||
>,
|
||||
>;
|
||||
|
||||
dyn_clone::clone_trait_object!(
|
||||
TaskNode<
|
||||
Input = dyn NodeArg,
|
||||
Output = dyn NodeArg,
|
||||
Error = dyn std::error::Error + Send + Sync,
|
||||
>
|
||||
);
|
||||
|
||||
#[async_trait]
|
||||
impl<Input: NodeArg, Output: NodeArg, Error: std::error::Error + Send + Sync + 'static> TaskNode
|
||||
for Box<dyn TaskNode<Input = Input, Output = Output, Error = Error>>
|
||||
{
|
||||
type Input = Input;
|
||||
type Output = Output;
|
||||
type Error = Error;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
self.as_ref().evaluate(node_id, input).await
|
||||
}
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(<Input, Output, Error> TaskNode<Input = Input, Output = Output, Error = Error>);
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub struct NodeId<T: TaskNode + ?Sized> {
|
||||
pub id: usize,
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: TaskNode + ?Sized> std::fmt::Debug for NodeId<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let type_name = std::any::type_name::<T>();
|
||||
|
||||
write!(f, "NodeId<{type_name}>({})", self.id)
|
||||
}
|
||||
}
|
||||
|
||||
pub type AnyNodeId = usize;
|
||||
|
||||
impl<T: TaskNode + ?Sized> NodeId<T> {
|
||||
pub fn id(&self) -> usize {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// Returns a closure that can be used as a transition function
|
||||
pub fn as_transition(&self) -> impl Fn(T::Input) -> MarkedTransitionPayload<T> + 'static {
|
||||
let node_id = *self;
|
||||
|
||||
Box::new(move |context| node_id.transitions_with(context))
|
||||
}
|
||||
|
||||
/// Returns a transition payload suitable for inside a task transition
|
||||
///
|
||||
/// You can also get the closure version with `as_transition`
|
||||
pub fn transitions_with(&self, context: T::Input) -> MarkedTransitionPayload<T> {
|
||||
MarkedTransitionPayload::new(TransitionPayload::next_node(self, context))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TaskNode + 'static + ?Sized> NodeId<T> {
|
||||
pub fn new(id: usize, _node: &T) -> Self {
|
||||
NodeId {
|
||||
id,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the internal id of the node without the type information.
|
||||
pub fn as_any(&self) -> AnyNodeId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn as_dyn(
|
||||
self,
|
||||
) -> NodeId<dyn TaskNode<Input = T::Input, Output = T::Output, Error = T::Error>> {
|
||||
NodeId {
|
||||
id: self.id,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TaskNode + ?Sized> Clone for NodeId<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl<T: TaskNode + ?Sized> Copy for NodeId<T> {}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Tasks enable you to to define a graph of interacting nodes
|
||||
//!
|
||||
//! The nodes can be any type that implements the `TaskNode` trait, which defines how the node
|
||||
//! will be evaluated with its input and output.
|
||||
//!
|
||||
//! Most swiftide primitives implement `TaskNode`, and it's easy to implement your own. Since how
|
||||
//! agents interact is subject to taste, we recommend implementing your own.
|
||||
//!
|
||||
//! WARN: Here be dragons! This api is not stable yet. We are using it in production, and is
|
||||
//! subject to rapid change. However, do not hesitate to open an issue if you find anything.
|
||||
use std::{any::Any, pin::Pin, sync::Arc};
|
||||
|
||||
use tracing::Instrument as _;
|
||||
|
||||
use crate::tasks::{errors::NodeError, transition::TransitionFn};
|
||||
|
||||
use super::{
|
||||
errors::TaskError,
|
||||
node::{NodeArg, NodeId, NoopNode, TaskNode},
|
||||
transition::{AnyNodeTransition, MarkedTransitionPayload, Transition, TransitionPayload},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Task<Input: NodeArg, Output: NodeArg> {
|
||||
nodes: Vec<Box<dyn AnyNodeTransition>>,
|
||||
current_node: usize,
|
||||
start_node: usize,
|
||||
current_context: Option<Arc<dyn Any + Send + Sync>>,
|
||||
_marker: std::marker::PhantomData<(Input, Output)>,
|
||||
}
|
||||
|
||||
impl<Input: NodeArg, Output: NodeArg> Clone for Task<Input, Output> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
nodes: self.nodes.clone(),
|
||||
current_node: 0,
|
||||
start_node: self.start_node,
|
||||
current_context: None,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input: NodeArg + Clone, Output: NodeArg + Clone> Default for Task<Input, Output> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input: NodeArg + Clone, Output: NodeArg + Clone> Task<Input, Output> {
|
||||
pub fn new() -> Self {
|
||||
let noop = NoopNode::<Output>::default();
|
||||
|
||||
let node_id = NodeId::new(0, &noop).as_dyn();
|
||||
|
||||
let noop_executor = Box::new(Transition {
|
||||
node: Box::new(noop),
|
||||
node_id: Box::new(node_id),
|
||||
r#fn: Arc::new(|_output| {
|
||||
Box::pin(async { unreachable!("Done node should never be evaluated.") })
|
||||
}),
|
||||
is_set: false,
|
||||
});
|
||||
Self {
|
||||
nodes: vec![noop_executor],
|
||||
current_node: 0,
|
||||
start_node: 0,
|
||||
current_context: None,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the current context as the input type, if it matches
|
||||
pub fn current_input(&self) -> Option<&Input> {
|
||||
let input = self.current_context.as_ref()?;
|
||||
|
||||
input.downcast_ref::<Input>()
|
||||
}
|
||||
|
||||
/// Returns the current context as the output type, if it matches
|
||||
pub fn current_output(&self) -> Option<&Output> {
|
||||
let input = self.current_context.as_ref()?;
|
||||
|
||||
input.downcast_ref::<Output>()
|
||||
}
|
||||
|
||||
/// Returns the `done` node for this task
|
||||
pub fn done(&self) -> NodeId<NoopNode<Output>> {
|
||||
NodeId::new(0, &NoopNode::default())
|
||||
}
|
||||
|
||||
/// Creates a transition to the done node
|
||||
pub fn transitions_to_done(
|
||||
&self,
|
||||
) -> impl Fn(Output) -> MarkedTransitionPayload<NoopNode<Output>> + Send + Sync + 'static {
|
||||
let done = self.done();
|
||||
move |context| done.transitions_with(context)
|
||||
}
|
||||
|
||||
/// Defines the start node of the task
|
||||
pub fn starts_with<T: TaskNode<Input = Input> + Clone + 'static>(
|
||||
&mut self,
|
||||
node_id: NodeId<T>,
|
||||
) {
|
||||
self.current_node = node_id.id;
|
||||
self.start_node = node_id.id;
|
||||
}
|
||||
|
||||
/// Validates that all nodes have transitions set
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if a node is missing a transition
|
||||
pub fn validate_transitions(&self) -> Result<(), TaskError> {
|
||||
// TODO: Validate that the task can complete
|
||||
for node_executor in &self.nodes {
|
||||
// Skip the done node (index 0)
|
||||
if node_executor.node_id() == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !node_executor.transition_is_set() {
|
||||
return Err(TaskError::missing_transition(node_executor.node_id()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs the task with the given input
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the task fails
|
||||
#[tracing::instrument(skip(self, input), name = "task.run", err)]
|
||||
pub async fn run(&mut self, input: impl Into<Input>) -> Result<Option<Output>, TaskError> {
|
||||
self.validate_transitions()?;
|
||||
|
||||
self.current_context = Some(Arc::new(input.into()) as Arc<dyn Any + Send + Sync>);
|
||||
|
||||
self.start_task().await
|
||||
}
|
||||
|
||||
/// Resets the task to the start node
|
||||
///
|
||||
/// WARN: This **will** lead to a type mismatch if the previous context is not the same as the
|
||||
/// input of the start node
|
||||
pub fn reset(&mut self) {
|
||||
self.current_node = self.start_node;
|
||||
}
|
||||
|
||||
/// Resumes the task from the current node
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the task fails
|
||||
#[tracing::instrument(skip(self), name = "task.resume", err)]
|
||||
pub async fn resume(&mut self) -> Result<Option<Output>, TaskError> {
|
||||
self.start_task().await
|
||||
}
|
||||
|
||||
async fn start_task(&mut self) -> Result<Option<Output>, TaskError> {
|
||||
self.validate_transitions()?;
|
||||
|
||||
let mut span = tracing::info_span!("task.step", node = self.current_node);
|
||||
loop {
|
||||
if self.current_node == 0 {
|
||||
break;
|
||||
}
|
||||
let node_transition = self
|
||||
.nodes
|
||||
.get(self.current_node)
|
||||
.ok_or_else(|| TaskError::missing_node(self.current_node))?;
|
||||
|
||||
let input = self
|
||||
.current_context
|
||||
.clone()
|
||||
.ok_or_else(|| TaskError::missing_input(self.current_node))?;
|
||||
|
||||
tracing::debug!("Running node {}", self.current_node);
|
||||
|
||||
let span_id = span.id().clone();
|
||||
let transition_payload = node_transition
|
||||
.evaluate_next(input)
|
||||
.instrument(span.or_current())
|
||||
.await?;
|
||||
|
||||
match transition_payload {
|
||||
TransitionPayload::Pause => {
|
||||
tracing::info!("Task paused at node {}", self.current_node);
|
||||
return Ok(None);
|
||||
}
|
||||
TransitionPayload::NextNode(transition_payload) => {
|
||||
self.current_node = transition_payload.node_id;
|
||||
self.current_context = Some(transition_payload.context);
|
||||
}
|
||||
TransitionPayload::Error(error) => {
|
||||
return Err(TaskError::NodeError(NodeError::new(
|
||||
error,
|
||||
self.current_node,
|
||||
None,
|
||||
)));
|
||||
}
|
||||
}
|
||||
if self.current_node == 0 {
|
||||
tracing::debug!("Task completed at node {}", self.current_node);
|
||||
break;
|
||||
}
|
||||
|
||||
span = tracing::info_span!("task.step", node = self.current_node).or_current();
|
||||
span.follows_from(span_id);
|
||||
}
|
||||
|
||||
let output = self
|
||||
.current_context
|
||||
.clone()
|
||||
.ok_or_else(|| TaskError::missing_output(self.current_node))?;
|
||||
let output = output
|
||||
.downcast::<Output>()
|
||||
.map_err(|e| TaskError::type_error(&e))?
|
||||
.as_ref()
|
||||
.clone();
|
||||
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
||||
/// Gets the current node of the task
|
||||
pub fn current_node<T: TaskNode + 'static>(&self) -> Option<&T> {
|
||||
self.node_at_index(self.current_node)
|
||||
}
|
||||
|
||||
/// Gets the node at the given `NodeId`
|
||||
pub fn node_at<T: TaskNode + 'static>(&self, node_id: NodeId<T>) -> Option<&T> {
|
||||
self.node_at_index(node_id.id)
|
||||
}
|
||||
|
||||
/// Gets the node at the given index
|
||||
pub fn node_at_index<T: TaskNode + 'static>(&self, index: usize) -> Option<&T> {
|
||||
let transition = self.transition_at_index::<T>(index)?;
|
||||
|
||||
let node = &*transition.node;
|
||||
|
||||
(node as &dyn Any).downcast_ref::<T>()
|
||||
}
|
||||
|
||||
/// Gets the current transition of the task
|
||||
#[allow(dead_code)]
|
||||
fn current_transition<T: TaskNode + 'static>(
|
||||
&self,
|
||||
) -> Option<&Transition<T::Input, T::Output, T::Error>> {
|
||||
self.transition_at_index::<T>(self.current_node)
|
||||
}
|
||||
|
||||
/// Gets the transition at the given `NodeId`
|
||||
fn transition_at_index<T: TaskNode + 'static>(
|
||||
&self,
|
||||
index: usize,
|
||||
) -> Option<&Transition<T::Input, T::Output, T::Error>> {
|
||||
tracing::debug!("Getting transition at index {}", index);
|
||||
let transition = self.nodes.get(index)?;
|
||||
|
||||
dbg!(&transition);
|
||||
|
||||
(&**transition as &dyn Any).downcast_ref::<Transition<T::Input, T::Output, T::Error>>()
|
||||
}
|
||||
|
||||
/// Registers a new node in the task
|
||||
pub fn register_node<T>(&mut self, node: T) -> NodeId<T>
|
||||
where
|
||||
T: TaskNode + 'static + Clone,
|
||||
<T as TaskNode>::Input: Clone,
|
||||
<T as TaskNode>::Output: Clone,
|
||||
{
|
||||
let id = self.nodes.len();
|
||||
let node_id = NodeId::new(id, &node);
|
||||
let node_executor = Box::new(Transition::<T::Input, T::Output, T::Error> {
|
||||
node_id: Box::new(node_id.as_dyn()),
|
||||
node: Box::new(node),
|
||||
r#fn: Arc::new(move |_output| unreachable!("No transition for node {}.", node_id.id)),
|
||||
is_set: false,
|
||||
});
|
||||
// Debug the type name
|
||||
tracing::debug!(node_id = ?node_id, type_name = std::any::type_name_of_val(&node_executor), "Registering node");
|
||||
|
||||
self.nodes.push(node_executor);
|
||||
|
||||
node_id
|
||||
}
|
||||
|
||||
/// Registers a transition from one node to another
|
||||
///
|
||||
/// Note that there are various helpers and conversions for the `MarkedTransitionPayload`
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the node does not exist
|
||||
pub fn register_transition<'a, From, To, F>(
|
||||
&mut self,
|
||||
from: NodeId<From>,
|
||||
transition: F,
|
||||
) -> Result<(), TaskError>
|
||||
where
|
||||
From: TaskNode + 'static + ?Sized,
|
||||
To: TaskNode<Input = From::Output> + 'a + ?Sized,
|
||||
F: Fn(To::Input) -> MarkedTransitionPayload<To> + Send + Sync + 'static,
|
||||
{
|
||||
let node_executor = self
|
||||
.nodes
|
||||
.get_mut(from.id)
|
||||
.ok_or_else(|| TaskError::missing_node(from.id))?;
|
||||
|
||||
let any_executor: &mut dyn Any = node_executor.as_mut();
|
||||
|
||||
let Some(exec) =
|
||||
any_executor.downcast_mut::<Transition<From::Input, From::Output, From::Error>>()
|
||||
else {
|
||||
let expected =
|
||||
std::any::type_name::<Transition<From::Input, From::Output, From::Error>>();
|
||||
let actual = std::any::type_name_of_val(node_executor);
|
||||
|
||||
unreachable!(
|
||||
"Transition at index {:?} is not a {expected:?}; Mismatched types, should not never happen. Actual: {actual:?}",
|
||||
from.id
|
||||
);
|
||||
};
|
||||
let transition = Arc::new(transition);
|
||||
let wrapped: Arc<dyn TransitionFn<From::Output>> = Arc::new(move |output: From::Output| {
|
||||
let transition = transition.clone();
|
||||
Box::pin(async move {
|
||||
let output = transition(output);
|
||||
output.into_inner()
|
||||
})
|
||||
});
|
||||
|
||||
exec.r#fn = wrapped;
|
||||
exec.is_set = true;
|
||||
// set function as before
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Registers a transition from one node to another asynchronously
|
||||
///
|
||||
/// Note that there are various helpers and conversions for the `MarkedTransitionPayload`
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the node does not exist
|
||||
///
|
||||
/// NOTE: `AsyncFn` traits' returned future are not 'Send' and the inner type is unstable.
|
||||
/// When they are, we can update Fn to `AsyncFn`
|
||||
pub fn register_transition_async<'a, From, To, F>(
|
||||
&mut self,
|
||||
from: NodeId<From>,
|
||||
transition: F,
|
||||
) -> Result<(), TaskError>
|
||||
where
|
||||
From: TaskNode + 'static + ?Sized,
|
||||
To: TaskNode<Input = From::Output> + 'a + ?Sized,
|
||||
F: Fn(To::Input) -> Pin<Box<dyn Future<Output = MarkedTransitionPayload<To>> + Send>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
let node_executor = self
|
||||
.nodes
|
||||
.get_mut(from.id)
|
||||
.ok_or_else(|| TaskError::missing_node(from.id))?;
|
||||
|
||||
let any_executor: &mut dyn Any = node_executor.as_mut();
|
||||
|
||||
let Some(exec) =
|
||||
any_executor.downcast_mut::<Transition<From::Input, From::Output, From::Error>>()
|
||||
else {
|
||||
let expected =
|
||||
std::any::type_name::<Transition<From::Input, From::Output, From::Error>>();
|
||||
let actual = std::any::type_name_of_val(node_executor);
|
||||
|
||||
unreachable!(
|
||||
"Transition at index {:?} is not a {expected:?}; Mismatched types, should not never happen. Actual: {actual:?}",
|
||||
from.id
|
||||
);
|
||||
};
|
||||
let transition = Arc::new(transition);
|
||||
let wrapped: Arc<dyn TransitionFn<From::Output>> = Arc::new(move |output: From::Output| {
|
||||
let transition = transition.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
let output = transition(output).await;
|
||||
output.into_inner()
|
||||
})
|
||||
});
|
||||
|
||||
exec.r#fn = wrapped;
|
||||
exec.is_set = true;
|
||||
// set function as before
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
struct Error(String);
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Debug)]
|
||||
struct IntNode;
|
||||
#[async_trait]
|
||||
impl TaskNode for IntNode {
|
||||
type Input = i32;
|
||||
type Output = i32;
|
||||
type Error = Error;
|
||||
|
||||
async fn evaluate(
|
||||
&self,
|
||||
_node_id: &NodeId<
|
||||
dyn TaskNode<Input = Self::Input, Output = Self::Output, Error = Self::Error>,
|
||||
>,
|
||||
input: &Self::Input,
|
||||
) -> Result<Self::Output, Self::Error> {
|
||||
Ok(input + 1)
|
||||
}
|
||||
}
|
||||
// Implement other required traits if necessary...
|
||||
|
||||
#[test_log::test(tokio::test)]
|
||||
async fn sequential_3_node_task_reset_works() {
|
||||
let mut task: Task<i32, i32> = Task::new();
|
||||
|
||||
// Register three nodes
|
||||
let node1 = task.register_node(IntNode);
|
||||
let node2 = task.register_node(IntNode);
|
||||
let node3 = task.register_node(IntNode);
|
||||
|
||||
// Set start node
|
||||
task.starts_with(node1);
|
||||
|
||||
// Register transitions (node1 → node2 → node3 → done)
|
||||
task.register_transition::<_, _, _>(node1, move |input| node2.transitions_with(input))
|
||||
.unwrap();
|
||||
task.register_transition::<_, _, _>(node2, move |input| node3.transitions_with(input))
|
||||
.unwrap();
|
||||
task.register_transition::<_, _, _>(node3, task.transitions_to_done())
|
||||
.unwrap();
|
||||
|
||||
// Run the task to completion
|
||||
let res = task.run(1).await.unwrap();
|
||||
assert_eq!(res, Some(4)); // 1 + 1 + 1 + 1
|
||||
|
||||
// Reset the task
|
||||
task.reset();
|
||||
|
||||
// Assert current_node returns the correct node (node1)
|
||||
dbg!(&task);
|
||||
let n1_transition = task.transition_at_index::<IntNode>(1);
|
||||
|
||||
assert!(n1_transition.is_some());
|
||||
|
||||
let n1_transition = task.current_transition::<IntNode>();
|
||||
assert!(n1_transition.is_some());
|
||||
|
||||
let n1_ref = task.current_node::<IntNode>();
|
||||
assert!(n1_ref.is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
use std::{any::Any, pin::Pin, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use dyn_clone::DynClone;
|
||||
|
||||
use super::{
|
||||
errors::NodeError,
|
||||
node::{NodeArg, NodeId, TaskNode},
|
||||
};
|
||||
|
||||
pub trait TransitionFn<Input: Send + Sync>:
|
||||
for<'a> Fn(Input) -> Pin<Box<dyn Future<Output = TransitionPayload> + Send>> + Send + Sync
|
||||
{
|
||||
}
|
||||
|
||||
// dyn_clone::clone_trait_object!(<Input> TransitionFn<Input>);
|
||||
|
||||
impl<Input: Send + Sync, F> TransitionFn<Input> for F where
|
||||
F: for<'a> Fn(Input) -> Pin<Box<dyn Future<Output = TransitionPayload> + Send>> + Send + Sync
|
||||
{
|
||||
}
|
||||
|
||||
pub(crate) struct Transition<
|
||||
Input: NodeArg,
|
||||
Output: NodeArg,
|
||||
Error: std::error::Error + Send + Sync + 'static,
|
||||
> {
|
||||
pub(crate) node: Box<dyn TaskNode<Input = Input, Output = Output, Error = Error> + Send + Sync>,
|
||||
pub(crate) node_id: Box<NodeId<dyn TaskNode<Input = Input, Output = Output, Error = Error>>>,
|
||||
// pub(crate) r#fn: Arc<dyn Fn(Output) -> TransitionPayload + Send + Sync>,
|
||||
pub(crate) r#fn: Arc<dyn TransitionFn<Output> + Send>,
|
||||
pub(crate) is_set: bool,
|
||||
}
|
||||
|
||||
impl<Input, Output, Error> Clone for Transition<Input, Output, Error>
|
||||
where
|
||||
Input: NodeArg,
|
||||
Output: NodeArg,
|
||||
Error: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Transition {
|
||||
node: self.node.clone(),
|
||||
node_id: self.node_id.clone(),
|
||||
r#fn: self.r#fn.clone(),
|
||||
is_set: self.is_set,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input: NodeArg, Output: NodeArg, Error: std::error::Error + Send + Sync + 'static>
|
||||
std::fmt::Debug for Transition<Input, Output, Error>
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Transition")
|
||||
.field("node_id", &self.node_id.id)
|
||||
.field("is_set", &self.is_set)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NextNode {
|
||||
// If we make this an enum instead, we can support spawning many nodes as well
|
||||
pub(crate) node_id: usize,
|
||||
pub(crate) context: Arc<dyn Any + Send + Sync>,
|
||||
}
|
||||
|
||||
impl NextNode {
|
||||
pub fn new<T: TaskNode + ?Sized>(node_id: NodeId<T>, context: T::Input) -> Self
|
||||
where
|
||||
<T as TaskNode>::Input: 'static,
|
||||
{
|
||||
let context = Arc::new(context) as Arc<dyn Any + Send + Sync>;
|
||||
|
||||
NextNode {
|
||||
node_id: node_id.id,
|
||||
context,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<NextNode> for TransitionPayload {
|
||||
fn from(next_node: NextNode) -> Self {
|
||||
TransitionPayload::NextNode(next_node)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TransitionPayload {
|
||||
NextNode(NextNode),
|
||||
Pause,
|
||||
Error(Box<dyn std::error::Error + Send + Sync>),
|
||||
}
|
||||
|
||||
impl TransitionPayload {
|
||||
pub fn next_node<T: TaskNode + ?Sized>(node_id: &NodeId<T>, context: T::Input) -> Self {
|
||||
NextNode::new(*node_id, context).into()
|
||||
}
|
||||
|
||||
pub fn pause() -> Self {
|
||||
TransitionPayload::Pause
|
||||
}
|
||||
|
||||
pub fn error(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
|
||||
TransitionPayload::Error(error.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MarkedTransitionPayload<To: TaskNode + ?Sized>(
|
||||
TransitionPayload,
|
||||
std::marker::PhantomData<To>,
|
||||
);
|
||||
|
||||
impl<To: TaskNode + ?Sized> MarkedTransitionPayload<To> {
|
||||
pub fn new(payload: TransitionPayload) -> Self {
|
||||
MarkedTransitionPayload(payload, std::marker::PhantomData)
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> TransitionPayload {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: TaskNode> std::ops::Deref for MarkedTransitionPayload<T> {
|
||||
type Target = TransitionPayload;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub(crate) trait AnyNodeTransition: Any + Send + Sync + std::fmt::Debug + DynClone {
|
||||
fn transition_is_set(&self) -> bool;
|
||||
|
||||
async fn evaluate_next(
|
||||
&self,
|
||||
context: Arc<dyn Any + Send + Sync>,
|
||||
) -> Result<TransitionPayload, NodeError>;
|
||||
|
||||
fn node_id(&self) -> usize;
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(AnyNodeTransition);
|
||||
|
||||
#[async_trait]
|
||||
impl<Input: NodeArg, Output: NodeArg, Error: std::error::Error + Send + Sync + 'static>
|
||||
AnyNodeTransition for Transition<Input, Output, Error>
|
||||
{
|
||||
async fn evaluate_next(
|
||||
&self,
|
||||
context: Arc<dyn Any + Send + Sync>,
|
||||
) -> Result<TransitionPayload, NodeError> {
|
||||
let context = context.downcast::<Input>().unwrap();
|
||||
|
||||
match self.node.evaluate(&self.node_id.as_dyn(), &context).await {
|
||||
Ok(output) => Ok((self.r#fn)(output).await),
|
||||
Err(error) => Err(NodeError::new(error, self.node_id.id, None)), /* node_id will be
|
||||
* set by caller */
|
||||
}
|
||||
}
|
||||
|
||||
fn transition_is_set(&self) -> bool {
|
||||
self.is_set
|
||||
}
|
||||
|
||||
fn node_id(&self) -> usize {
|
||||
self.node_id.id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
use std::borrow::Cow;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use swiftide_core::chat_completion::ToolCall;
|
||||
use swiftide_core::chat_completion::{Tool, ToolOutput, ToolSpec, errors::ToolError};
|
||||
|
||||
use swiftide_core::AgentContext;
|
||||
|
||||
use crate::Agent;
|
||||
use crate::hooks::{
|
||||
AfterCompletionFn, AfterToolFn, BeforeAllFn, BeforeCompletionFn, BeforeToolFn, MessageHookFn,
|
||||
OnStartFn, OnStopFn, OnStreamFn,
|
||||
};
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! chat_request {
|
||||
($($message:expr),+; tools = [$($tool:expr),*]) => {{
|
||||
let mut builder = swiftide_core::chat_completion::ChatCompletionRequest::builder();
|
||||
builder.messages(vec![$($message),*]);
|
||||
|
||||
let mut tool_specs = Vec::new();
|
||||
$(tool_specs.push({
|
||||
let tool = $tool;
|
||||
tool.tool_spec()
|
||||
});)*
|
||||
|
||||
tool_specs.extend(Agent::default_tools().into_iter().map(|tool| tool.tool_spec()));
|
||||
|
||||
builder.tool_specs(tool_specs);
|
||||
|
||||
builder.build().unwrap()
|
||||
}};
|
||||
($($message:expr),+; tool_specs = [$($tool:expr),*]) => {{
|
||||
let mut builder = swiftide_core::chat_completion::ChatCompletionRequest::builder();
|
||||
builder.messages(vec![$($message),*]);
|
||||
|
||||
let mut tool_specs = Vec::new();
|
||||
$(tool_specs.push($tool);)*
|
||||
tool_specs.extend(Agent::default_tools().into_iter().map(|tool| tool.tool_spec()));
|
||||
|
||||
builder.tool_specs(tool_specs);
|
||||
|
||||
builder.build().unwrap()
|
||||
}}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! user {
|
||||
($message:expr) => {
|
||||
swiftide_core::chat_completion::ChatMessage::new_user($message)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! system {
|
||||
($message:expr) => {
|
||||
swiftide_core::chat_completion::ChatMessage::new_system($message)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! summary {
|
||||
($message:expr) => {
|
||||
swiftide_core::chat_completion::ChatMessage::new_summary($message)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! assistant {
|
||||
($message:expr) => {
|
||||
swiftide_core::chat_completion::ChatMessage::new_assistant(
|
||||
Some($message.to_string()),
|
||||
None,
|
||||
)
|
||||
};
|
||||
($message:expr, [$($tool_call_name:expr),*]) => {{
|
||||
let tool_calls = vec![
|
||||
$(
|
||||
ToolCall::builder()
|
||||
.name($tool_call_name)
|
||||
.id("1")
|
||||
.build()
|
||||
.unwrap()
|
||||
),*
|
||||
];
|
||||
|
||||
ChatMessage::new_assistant(Some($message.to_string()), Some(tool_calls))
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! tool_output {
|
||||
($tool_name:expr, $message:expr) => {{
|
||||
ChatMessage::ToolOutput(
|
||||
ToolCall::builder()
|
||||
.name($tool_name)
|
||||
.id("1")
|
||||
.build()
|
||||
.unwrap(),
|
||||
$message.into(),
|
||||
)
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! tool_failed {
|
||||
($tool_name:expr, $message:expr) => {{
|
||||
ChatMessage::ToolOutput(
|
||||
ToolCall::builder()
|
||||
.name($tool_name)
|
||||
.id("1")
|
||||
.build()
|
||||
.unwrap(),
|
||||
ToolOutput::fail($message),
|
||||
)
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! chat_response {
|
||||
($message:expr; tool_calls = [$($tool_name:expr),*]) => {{
|
||||
|
||||
let tool_calls = vec![
|
||||
$(ToolCall::builder().name($tool_name).id("1").build().unwrap()),*
|
||||
];
|
||||
|
||||
ChatCompletionResponse::builder()
|
||||
.message($message)
|
||||
.tool_calls(tool_calls)
|
||||
.build()
|
||||
.unwrap()
|
||||
}};
|
||||
(tool_calls = [$($tool_name:expr),*]) => {{
|
||||
|
||||
let tool_calls = vec![
|
||||
$(ToolCall::builder().name($tool_name).id("1").build().unwrap()),*
|
||||
];
|
||||
|
||||
ChatCompletionResponse::builder()
|
||||
.tool_calls(tool_calls)
|
||||
.build()
|
||||
.unwrap()
|
||||
}};
|
||||
}
|
||||
|
||||
type Expectations = Arc<Mutex<Vec<(Result<ToolOutput, ToolError>, Option<&'static str>)>>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MockTool {
|
||||
expectations: Expectations,
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
impl MockTool {
|
||||
#[allow(clippy::should_implement_trait)]
|
||||
pub fn default() -> Self {
|
||||
Self::new("mock_tool")
|
||||
}
|
||||
pub fn new(name: &'static str) -> Self {
|
||||
Self {
|
||||
expectations: Arc::new(Mutex::new(Vec::new())),
|
||||
name,
|
||||
}
|
||||
}
|
||||
pub fn expect_invoke_ok(
|
||||
&self,
|
||||
expected_result: ToolOutput,
|
||||
expected_args: Option<&'static str>,
|
||||
) {
|
||||
self.expect_invoke(Ok(expected_result), expected_args);
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn expect_invoke(
|
||||
&self,
|
||||
expected_result: Result<ToolOutput, ToolError>,
|
||||
expected_args: Option<&'static str>,
|
||||
) {
|
||||
self.expectations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((expected_result, expected_args));
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for MockTool {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn AgentContext,
|
||||
tool_call: &ToolCall,
|
||||
) -> std::result::Result<ToolOutput, ToolError> {
|
||||
tracing::debug!(
|
||||
"[MockTool] Invoked `{}` with args: {:?}",
|
||||
self.name,
|
||||
tool_call
|
||||
);
|
||||
let expectation = self
|
||||
.expectations
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pop()
|
||||
.unwrap_or_else(|| panic!("[MockTool] No expectations left for `{}`", self.name));
|
||||
|
||||
assert_eq!(expectation.1, tool_call.args());
|
||||
|
||||
expectation.0
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
self.name.into()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
ToolSpec::builder()
|
||||
.name(self.name().as_ref())
|
||||
.description("A fake tool for testing purposes")
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MockTool> for Box<dyn Tool> {
|
||||
fn from(val: MockTool) -> Self {
|
||||
Box::new(val) as Box<dyn Tool>
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MockTool {
|
||||
fn drop(&mut self) {
|
||||
// Mock still borrowed elsewhere and expectations still be invoked
|
||||
if Arc::strong_count(&self.expectations) > 1 {
|
||||
return;
|
||||
}
|
||||
if self.expectations.lock().is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
let name = self.name;
|
||||
if self.expectations.lock().unwrap().is_empty() {
|
||||
tracing::debug!("[MockTool] All expectations were met for `{name}`");
|
||||
} else {
|
||||
panic!(
|
||||
"[MockTool] Not all expectations were met for `{name}: {:?}",
|
||||
*self.expectations.lock().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MockHook {
|
||||
name: &'static str,
|
||||
called: Arc<Mutex<usize>>,
|
||||
expected_calls: usize,
|
||||
}
|
||||
|
||||
impl MockHook {
|
||||
pub fn new(name: &'static str) -> Self {
|
||||
Self {
|
||||
name,
|
||||
called: Arc::new(Mutex::new(0)),
|
||||
expected_calls: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expect_calls(&mut self, expected_calls: usize) -> &mut Self {
|
||||
self.expected_calls = expected_calls;
|
||||
self
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn hook_fn(&self) -> impl BeforeAllFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn on_start_fn(&self) -> impl OnStartFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn before_completion_fn(&self) -> impl BeforeCompletionFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn after_completion_fn(&self) -> impl AfterCompletionFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn after_tool_fn(&self) -> impl AfterToolFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn before_tool_fn(&self) -> impl BeforeToolFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn message_hook_fn(&self) -> impl MessageHookFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn stop_hook_fn(&self) -> impl OnStopFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_panics_doc)]
|
||||
pub fn on_stream_fn(&self) -> impl OnStreamFn + use<> {
|
||||
let called = Arc::clone(&self.called);
|
||||
move |_: &Agent, _| {
|
||||
let called = Arc::clone(&called);
|
||||
Box::pin(async move {
|
||||
let mut called = called.lock().unwrap();
|
||||
*called += 1;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MockHook {
|
||||
fn drop(&mut self) {
|
||||
if Arc::strong_count(&self.called) > 1 {
|
||||
return;
|
||||
}
|
||||
let Ok(called) = self.called.lock() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if *called == self.expected_calls {
|
||||
tracing::debug!(
|
||||
"[MockHook] `{}` all expectations met; called {} times",
|
||||
self.name,
|
||||
*called
|
||||
);
|
||||
} else {
|
||||
panic!(
|
||||
"[MockHook] `{}` was called {} times but expected {}",
|
||||
self.name, *called, self.expected_calls
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use swiftide_core::chat_completion::ToolCall;
|
||||
|
||||
/// Preprocesses arguments for tool calls and tries to fix common errors
|
||||
/// This must be infallible and the result is always forwarded to the tool
|
||||
pub struct ArgPreprocessor;
|
||||
|
||||
impl ArgPreprocessor {
|
||||
pub fn preprocess_tool_calls(tool_calls: &mut [ToolCall]) {
|
||||
for tool_call in tool_calls.iter_mut() {
|
||||
let args = Self::preprocess(tool_call.args());
|
||||
|
||||
if args.as_ref().is_some_and(|a| match a {
|
||||
Cow::Borrowed(_) => false,
|
||||
Cow::Owned(_) => true,
|
||||
}) {
|
||||
tool_call.with_args(args.map(|a| a.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn preprocess(value: Option<&str>) -> Option<Cow<'_, str>> {
|
||||
Some(take_first_occurrence_in_object(value?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Strips duplicate keys from JSON objects
|
||||
fn take_first_occurrence_in_object(value: &str) -> Cow<'_, str> {
|
||||
let Ok(parsed) = &serde_json::from_str(value) else {
|
||||
return Cow::Borrowed(value);
|
||||
};
|
||||
if let Value::Object(obj) = parsed {
|
||||
let mut new_map = Map::with_capacity(obj.len());
|
||||
for (k, v) in obj {
|
||||
// Only insert if we haven't seen this key yet.
|
||||
new_map.entry(k).or_insert(v.clone());
|
||||
}
|
||||
Cow::Owned(Value::Object(new_map).to_string())
|
||||
} else {
|
||||
// If the top-level isn't even an object, just pass it as is,
|
||||
// or decide how you want to handle that situation.
|
||||
Cow::Borrowed(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_preprocess_regular_json() {
|
||||
let input = json!({
|
||||
"key1": "value1",
|
||||
"key2": "value2"
|
||||
})
|
||||
.to_string();
|
||||
let expected = json!({
|
||||
"key1": "value1",
|
||||
"key2": "value2"
|
||||
});
|
||||
let result = ArgPreprocessor::preprocess(Some(&input));
|
||||
assert_eq!(result.as_deref(), Some(expected.to_string().as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_preprocess_json_with_duplicate_keys() {
|
||||
let input = json!({
|
||||
"key1": "value1",
|
||||
"key1": "value2"
|
||||
})
|
||||
.to_string();
|
||||
let expected = json!({
|
||||
"key1": "value2"
|
||||
});
|
||||
let result = ArgPreprocessor::preprocess(Some(&input));
|
||||
assert_eq!(result.as_deref(), Some(expected.to_string().as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_preprocess_invalid_json() {
|
||||
let input = "invalid json";
|
||||
let result = ArgPreprocessor::preprocess(Some(input));
|
||||
assert_eq!(result.as_deref(), Some(input));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_input() {
|
||||
let result = ArgPreprocessor::preprocess(None);
|
||||
assert_eq!(result, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
//! Control tools manage control flow during agent's lifecycle.
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use schemars::{Schema, schema_for};
|
||||
use std::borrow::Cow;
|
||||
use swiftide_core::{
|
||||
AgentContext, ToolFeedback,
|
||||
chat_completion::{Tool, ToolCall, ToolOutput, ToolSpec, errors::ToolError},
|
||||
};
|
||||
|
||||
/// `Stop` tool is a default tool used by agents to stop
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Stop {}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for Stop {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn AgentContext,
|
||||
_tool_call: &ToolCall,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
Ok(ToolOutput::stop())
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
"stop".into()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
ToolSpec::builder()
|
||||
.name("stop")
|
||||
.description("When you have completed, or cannot complete, your task, call this")
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Stop> for Box<dyn Tool> {
|
||||
fn from(val: Stop) -> Self {
|
||||
Box::new(val)
|
||||
}
|
||||
}
|
||||
|
||||
/// `StopWithArgs` is an alternative stop tool that takes arguments
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StopWithArgs {
|
||||
parameters_schema: Option<Schema>,
|
||||
expects_output_field: bool,
|
||||
}
|
||||
|
||||
impl Default for StopWithArgs {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
parameters_schema: Some(schema_for!(DefaultStopWithArgsSpec)),
|
||||
expects_output_field: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StopWithArgs {
|
||||
/// Create a new `StopWithArgs` tool with a custom parameters schema.
|
||||
///
|
||||
/// When providing a custom schema the full argument payload will be forwarded to the
|
||||
/// stop output without requiring an `output` field wrapper.
|
||||
pub fn with_parameters_schema(schema: Schema) -> Self {
|
||||
Self {
|
||||
parameters_schema: Some(schema),
|
||||
expects_output_field: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn parameters_schema(&self) -> Schema {
|
||||
self.parameters_schema
|
||||
.clone()
|
||||
.unwrap_or_else(|| schema_for!(DefaultStopWithArgsSpec))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
|
||||
struct DefaultStopWithArgsSpec {
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for StopWithArgs {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn AgentContext,
|
||||
tool_call: &ToolCall,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let raw_args = tool_call
|
||||
.args()
|
||||
.ok_or_else(|| ToolError::missing_arguments("arguments"))?;
|
||||
|
||||
let json: serde_json::Value = serde_json::from_str(raw_args)?;
|
||||
|
||||
let output = if self.expects_output_field {
|
||||
json.get("output")
|
||||
.cloned()
|
||||
.ok_or_else(|| ToolError::missing_arguments("output"))?
|
||||
} else {
|
||||
json
|
||||
};
|
||||
|
||||
Ok(ToolOutput::stop_with_args(output))
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
"stop".into()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
let schema = self.parameters_schema();
|
||||
|
||||
ToolSpec::builder()
|
||||
.name("stop")
|
||||
.description("When you have completed, your task, call this with your expected output")
|
||||
.parameters_schema(schema)
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StopWithArgs> for Box<dyn Tool> {
|
||||
fn from(val: StopWithArgs) -> Self {
|
||||
Box::new(val)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
|
||||
struct AgentFailedArgsSpec {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// A utility tool that can be used to let an agent decide it failed
|
||||
///
|
||||
/// This will _NOT_ have the agent return an error, instead, look at the stop reason of the agent.
|
||||
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct AgentCanFail {
|
||||
parameters_schema: Option<Schema>,
|
||||
expects_reason_field: bool,
|
||||
}
|
||||
|
||||
impl Default for AgentCanFail {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
parameters_schema: Some(schema_for!(AgentFailedArgsSpec)),
|
||||
expects_reason_field: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentCanFail {
|
||||
/// Create a new `AgentCanFail` tool with a custom parameters schema.
|
||||
///
|
||||
/// When providing a custom schema the full argument payload will be forwarded to the failure
|
||||
/// reason without requiring a `reason` field wrapper.
|
||||
pub fn with_parameters_schema(schema: Schema) -> Self {
|
||||
Self {
|
||||
parameters_schema: Some(schema),
|
||||
expects_reason_field: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn parameters_schema(&self) -> Schema {
|
||||
self.parameters_schema
|
||||
.clone()
|
||||
.unwrap_or_else(|| schema_for!(AgentFailedArgsSpec))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for AgentCanFail {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn AgentContext,
|
||||
tool_call: &ToolCall,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
let raw_args = tool_call.args().ok_or_else(|| {
|
||||
if self.expects_reason_field {
|
||||
ToolError::missing_arguments("reason")
|
||||
} else {
|
||||
ToolError::missing_arguments("arguments")
|
||||
}
|
||||
})?;
|
||||
|
||||
let reason = if self.expects_reason_field {
|
||||
let args: AgentFailedArgsSpec = serde_json::from_str(raw_args)?;
|
||||
args.reason
|
||||
} else {
|
||||
let json: serde_json::Value = serde_json::from_str(raw_args)?;
|
||||
json.to_string()
|
||||
};
|
||||
|
||||
Ok(ToolOutput::agent_failed(reason))
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
"task_failed".into()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
let schema = self.parameters_schema();
|
||||
|
||||
ToolSpec::builder()
|
||||
.name("task_failed")
|
||||
.description("If you cannot complete your task, or have otherwise failed, call this with your reason for failure")
|
||||
.parameters_schema(schema)
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AgentCanFail> for Box<dyn Tool> {
|
||||
fn from(val: AgentCanFail) -> Self {
|
||||
Box::new(val)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
/// Wraps a tool and requires approval before it can be used
|
||||
pub struct ApprovalRequired(pub Box<dyn Tool>);
|
||||
|
||||
impl ApprovalRequired {
|
||||
/// Creates a new `ApprovalRequired` tool
|
||||
pub fn new(tool: impl Tool + 'static) -> Self {
|
||||
Self(Box::new(tool))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for ApprovalRequired {
|
||||
async fn invoke(
|
||||
&self,
|
||||
context: &dyn AgentContext,
|
||||
tool_call: &ToolCall,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
if let Some(feedback) = context.has_received_feedback(tool_call).await {
|
||||
match feedback {
|
||||
ToolFeedback::Approved { .. } => return self.0.invoke(context, tool_call).await,
|
||||
ToolFeedback::Refused { .. } => {
|
||||
return Ok(ToolOutput::text("This tool call was refused"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ToolOutput::FeedbackRequired(None))
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
self.0.name()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
self.0.tool_spec()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ApprovalRequired> for Box<dyn Tool> {
|
||||
fn from(val: ApprovalRequired) -> Self {
|
||||
Box::new(val)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use schemars::schema_for;
|
||||
use serde_json::json;
|
||||
|
||||
fn dummy_tool_call(name: &str, args: Option<&str>) -> ToolCall {
|
||||
let mut builder = ToolCall::builder().name(name).id("1").to_owned();
|
||||
if let Some(args) = args {
|
||||
builder.args(args.to_string());
|
||||
}
|
||||
builder.build().unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_stop_tool() {
|
||||
let stop = Stop::default();
|
||||
let ctx = ();
|
||||
let tool_call = dummy_tool_call("stop", None);
|
||||
let out = stop.invoke(&ctx, &tool_call).await.unwrap();
|
||||
assert_eq!(out, ToolOutput::stop());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_stop_with_args_tool() {
|
||||
let tool = StopWithArgs::default();
|
||||
let ctx = ();
|
||||
let args = r#"{"output":"expected result"}"#;
|
||||
let tool_call = dummy_tool_call("stop", Some(args));
|
||||
let out = tool.invoke(&ctx, &tool_call).await.unwrap();
|
||||
assert_eq!(out, ToolOutput::stop_with_args("expected result"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_agent_can_fail_tool() {
|
||||
let tool = AgentCanFail::default();
|
||||
let ctx = ();
|
||||
let args = r#"{"reason":"something went wrong"}"#;
|
||||
let tool_call = dummy_tool_call("task_failed", Some(args));
|
||||
let out = tool.invoke(&ctx, &tool_call).await.unwrap();
|
||||
assert_eq!(out, ToolOutput::agent_failed("something went wrong"));
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
|
||||
struct CustomFailArgs {
|
||||
code: i32,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_agent_can_fail_custom_schema_in_spec() {
|
||||
let schema = schema_for!(CustomFailArgs);
|
||||
let tool = AgentCanFail::with_parameters_schema(schema.clone());
|
||||
let spec = tool.tool_spec();
|
||||
assert_eq!(spec.parameters_schema, Some(schema));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_agent_can_fail_custom_schema_forwards_payload() {
|
||||
let schema = schema_for!(CustomFailArgs);
|
||||
let tool = AgentCanFail::with_parameters_schema(schema);
|
||||
let ctx = ();
|
||||
let args = r#"{"code":7,"message":"error"}"#;
|
||||
let tool_call = dummy_tool_call("task_failed", Some(args));
|
||||
let out = tool.invoke(&ctx, &tool_call).await.unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
ToolOutput::agent_failed(json!({"code":7,"message":"error"}).to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_agent_can_fail_default_schema_matches_previous() {
|
||||
let tool = AgentCanFail::default();
|
||||
let spec = tool.tool_spec();
|
||||
let expected = schema_for!(AgentFailedArgsSpec);
|
||||
assert_eq!(spec.parameters_schema, Some(expected));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_approval_required_feedback_required() {
|
||||
let stop = Stop::default();
|
||||
let tool = ApprovalRequired::new(stop);
|
||||
let ctx = ();
|
||||
let tool_call = dummy_tool_call("stop", None);
|
||||
let out = tool.invoke(&ctx, &tool_call).await.unwrap();
|
||||
|
||||
// On unit; existing feedback is always present
|
||||
assert_eq!(out, ToolOutput::Stop(None));
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
|
||||
struct CustomStopArgs {
|
||||
value: i32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_with_args_custom_schema_in_spec() {
|
||||
let schema = schema_for!(CustomStopArgs);
|
||||
let tool = StopWithArgs::with_parameters_schema(schema.clone());
|
||||
let spec = tool.tool_spec();
|
||||
assert_eq!(spec.parameters_schema, Some(schema));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_stop_with_args_custom_schema_forwards_payload() {
|
||||
let schema = schema_for!(CustomStopArgs);
|
||||
let tool = StopWithArgs::with_parameters_schema(schema);
|
||||
let ctx = ();
|
||||
let args = r#"{"value":42}"#;
|
||||
let tool_call = dummy_tool_call("stop", Some(args));
|
||||
let out = tool.invoke(&ctx, &tool_call).await.unwrap();
|
||||
assert_eq!(out, ToolOutput::stop_with_args(json!({"value": 42})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_with_args_default_schema_matches_previous() {
|
||||
let tool = StopWithArgs::default();
|
||||
let spec = tool.tool_spec();
|
||||
let expected = schema_for!(DefaultStopWithArgsSpec);
|
||||
assert_eq!(spec.parameters_schema, Some(expected));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,875 @@
|
||||
//! Local executor for running tools on the local machine.
|
||||
//!
|
||||
//! By default will use the current directory as the working directory.
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use async_trait::async_trait;
|
||||
use derive_builder::Builder;
|
||||
use swiftide_core::{Command, CommandError, CommandOutput, Loader, ToolExecutor};
|
||||
use swiftide_indexing::loaders::FileLoader;
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt as _, AsyncWriteExt as _},
|
||||
task::JoinHandle,
|
||||
time,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Builder)]
|
||||
pub struct LocalExecutor {
|
||||
#[builder(default = ".".into(), setter(into))]
|
||||
workdir: PathBuf,
|
||||
|
||||
#[builder(default)]
|
||||
default_timeout: Option<Duration>,
|
||||
|
||||
/// Clears env variables before executing commands.
|
||||
#[builder(default)]
|
||||
pub(crate) env_clear: bool,
|
||||
/// Remove these environment variables before executing commands.
|
||||
#[builder(default, setter(into))]
|
||||
pub(crate) env_remove: Vec<String>,
|
||||
/// Set these environment variables before executing commands.
|
||||
#[builder(default, setter(into))]
|
||||
pub(crate) envs: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Default for LocalExecutor {
|
||||
fn default() -> Self {
|
||||
LocalExecutor {
|
||||
workdir: ".".into(),
|
||||
default_timeout: None,
|
||||
env_clear: false,
|
||||
env_remove: Vec::new(),
|
||||
envs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalExecutor {
|
||||
pub fn new(workdir: impl Into<PathBuf>) -> Self {
|
||||
LocalExecutor {
|
||||
workdir: workdir.into(),
|
||||
default_timeout: None,
|
||||
env_clear: false,
|
||||
env_remove: Vec::new(),
|
||||
envs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn builder() -> LocalExecutorBuilder {
|
||||
LocalExecutorBuilder::default()
|
||||
}
|
||||
|
||||
fn resolve_workdir(&self, cmd: &Command) -> PathBuf {
|
||||
match cmd.current_dir_path() {
|
||||
Some(path) if path.is_absolute() => path.to_path_buf(),
|
||||
Some(path) => self.workdir.join(path),
|
||||
None => self.workdir.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_timeout(&self, cmd: &Command) -> Option<Duration> {
|
||||
cmd.timeout_duration().copied().or(self.default_timeout)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
async fn exec_shell(
|
||||
&self,
|
||||
cmd: &str,
|
||||
workdir: &Path,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<CommandOutput, CommandError> {
|
||||
let lines: Vec<&str> = cmd.lines().collect();
|
||||
let mut child = if let Some(first_line) = lines.first()
|
||||
&& first_line.starts_with("#!")
|
||||
{
|
||||
let interpreter = first_line.trim_start_matches("#!/usr/bin/env ").trim();
|
||||
tracing::info!(interpreter, "detected shebang; running as script");
|
||||
|
||||
let mut command = tokio::process::Command::new(interpreter);
|
||||
|
||||
if self.env_clear {
|
||||
tracing::info!("clearing environment variables");
|
||||
command.env_clear();
|
||||
}
|
||||
|
||||
for var in &self.env_remove {
|
||||
tracing::info!(var, "clearing environment variable");
|
||||
command.env_remove(var);
|
||||
}
|
||||
|
||||
for (key, value) in &self.envs {
|
||||
tracing::info!(key, "setting environment variable");
|
||||
command.env(key, value);
|
||||
}
|
||||
|
||||
let mut child = command
|
||||
.current_dir(workdir)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let body = lines[1..].join("\n");
|
||||
stdin.write_all(body.as_bytes()).await?;
|
||||
}
|
||||
|
||||
child
|
||||
} else {
|
||||
tracing::info!("no shebang detected; running as command");
|
||||
|
||||
let mut command = tokio::process::Command::new("sh");
|
||||
|
||||
// Treat as shell command
|
||||
command.arg("-c").arg(cmd).current_dir(workdir);
|
||||
|
||||
if self.env_clear {
|
||||
tracing::info!("clearing environment variables");
|
||||
command.env_clear();
|
||||
}
|
||||
|
||||
for var in &self.env_remove {
|
||||
tracing::info!(var, "clearing environment variable");
|
||||
command.env_remove(var);
|
||||
}
|
||||
|
||||
for (key, value) in &self.envs {
|
||||
tracing::info!(key, "setting environment variable");
|
||||
command.env(key, value);
|
||||
}
|
||||
command
|
||||
.current_dir(workdir)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?
|
||||
};
|
||||
|
||||
let stdout_task = if let Some(stdout) = child.stdout.take() {
|
||||
Some(tokio::spawn(async move {
|
||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||
let mut out = Vec::new();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
out.push(line);
|
||||
}
|
||||
out
|
||||
}))
|
||||
} else {
|
||||
tracing::warn!("Command has no stdout");
|
||||
None
|
||||
};
|
||||
|
||||
let stderr_task = if let Some(stderr) = child.stderr.take() {
|
||||
Some(tokio::spawn(async move {
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
let mut out = Vec::new();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
out.push(line);
|
||||
}
|
||||
out
|
||||
}))
|
||||
} else {
|
||||
tracing::warn!("Command has no stderr");
|
||||
None
|
||||
};
|
||||
|
||||
let status = match timeout {
|
||||
Some(limit) => {
|
||||
if let Ok(result) = time::timeout(limit, child.wait()).await {
|
||||
result.map_err(|err| CommandError::ExecutorError(err.into()))?
|
||||
} else {
|
||||
tracing::warn!(?limit, "command exceeded timeout; terminating");
|
||||
if let Err(err) = child.start_kill() {
|
||||
tracing::warn!(?err, "failed to start kill on timed out command");
|
||||
}
|
||||
if let Err(err) = child.wait().await {
|
||||
tracing::warn!(?err, "failed to reap command after timeout");
|
||||
}
|
||||
|
||||
let (stdout, stderr) =
|
||||
Self::collect_process_output(stdout_task, stderr_task).await;
|
||||
let cmd_output = Self::command_output(&stdout, &stderr);
|
||||
|
||||
return Err(CommandError::TimedOut {
|
||||
timeout: limit,
|
||||
output: cmd_output,
|
||||
});
|
||||
}
|
||||
}
|
||||
None => child
|
||||
.wait()
|
||||
.await
|
||||
.map_err(|err| CommandError::ExecutorError(err.into()))?,
|
||||
};
|
||||
|
||||
let (stdout, stderr) = Self::collect_process_output(stdout_task, stderr_task).await;
|
||||
let cmd_output = Self::command_output(&stdout, &stderr);
|
||||
|
||||
if status.success() {
|
||||
Ok(cmd_output)
|
||||
} else {
|
||||
Err(CommandError::NonZeroExit(cmd_output))
|
||||
}
|
||||
}
|
||||
|
||||
async fn exec_read_file(
|
||||
&self,
|
||||
workdir: &Path,
|
||||
path: &Path,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<CommandOutput, CommandError> {
|
||||
let path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
workdir.join(path)
|
||||
};
|
||||
let read_future = fs_err::tokio::read(&path);
|
||||
let output = match timeout {
|
||||
Some(limit) => match time::timeout(limit, read_future).await {
|
||||
Ok(result) => result?,
|
||||
Err(_) => {
|
||||
return Err(CommandError::TimedOut {
|
||||
timeout: limit,
|
||||
output: CommandOutput::empty(),
|
||||
});
|
||||
}
|
||||
},
|
||||
None => read_future.await?,
|
||||
};
|
||||
|
||||
Ok(String::from_utf8(output)
|
||||
.context("Failed to parse read file output")?
|
||||
.into())
|
||||
}
|
||||
|
||||
async fn exec_write_file(
|
||||
&self,
|
||||
workdir: &Path,
|
||||
path: &Path,
|
||||
content: &str,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<CommandOutput, CommandError> {
|
||||
let path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
workdir.join(path)
|
||||
};
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = fs_err::tokio::create_dir_all(parent).await;
|
||||
}
|
||||
let write_future = fs_err::tokio::write(&path, content);
|
||||
match timeout {
|
||||
Some(limit) => match time::timeout(limit, write_future).await {
|
||||
Ok(result) => result?,
|
||||
Err(_) => {
|
||||
return Err(CommandError::TimedOut {
|
||||
timeout: limit,
|
||||
output: CommandOutput::empty(),
|
||||
});
|
||||
}
|
||||
},
|
||||
None => write_future.await?,
|
||||
}
|
||||
|
||||
Ok(CommandOutput::empty())
|
||||
}
|
||||
|
||||
async fn collect_process_output(
|
||||
stdout_task: Option<JoinHandle<Vec<String>>>,
|
||||
stderr_task: Option<JoinHandle<Vec<String>>>,
|
||||
) -> (Vec<String>, Vec<String>) {
|
||||
let stdout = match stdout_task {
|
||||
Some(task) => match task.await {
|
||||
Ok(lines) => lines,
|
||||
Err(err) => {
|
||||
tracing::warn!(?err, "failed to collect stdout from command");
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
let stderr = match stderr_task {
|
||||
Some(task) => match task.await {
|
||||
Ok(lines) => lines,
|
||||
Err(err) => {
|
||||
tracing::warn!(?err, "failed to collect stderr from command");
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
(stdout, stderr)
|
||||
}
|
||||
|
||||
fn command_output(stdout: &[String], stderr: &[String]) -> CommandOutput {
|
||||
CommandOutput::from_parts(stdout.join("\n"), stderr.join("\n"))
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl ToolExecutor for LocalExecutor {
|
||||
/// Execute a `Command` on the local machine
|
||||
#[tracing::instrument(skip_self)]
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<swiftide_core::CommandOutput, CommandError> {
|
||||
let workdir = __self.resolve_workdir(cmd);
|
||||
let timeout = __self.resolve_timeout(cmd);
|
||||
match cmd {
|
||||
Command::Shell { command, .. } => __self.exec_shell(command, &workdir, timeout).await,
|
||||
Command::ReadFile { path, .. } => __self.exec_read_file(&workdir, path, timeout).await,
|
||||
Command::WriteFile { path, content, .. } => {
|
||||
__self
|
||||
.exec_write_file(&workdir, path, content, timeout)
|
||||
.await
|
||||
}
|
||||
_ => unimplemented!("Unsupported command: {cmd:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<swiftide_core::indexing::IndexingStream<String>> {
|
||||
let mut loader = FileLoader::new(path);
|
||||
|
||||
if let Some(extensions) = extensions {
|
||||
loader = loader.with_extensions(&extensions);
|
||||
}
|
||||
|
||||
Ok(loader.into_stream())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures_util::StreamExt as _;
|
||||
use indoc::indoc;
|
||||
use std::{path::Path, sync::Arc, time::Duration};
|
||||
use swiftide_core::{Command, ExecutorExt, ToolExecutor};
|
||||
use temp_dir::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_write_and_read_file() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the file path and content
|
||||
let file_path = temp_path.join("test_file.txt");
|
||||
let file_content = "Hello, world!";
|
||||
|
||||
// Write a shell command to create a file with the specified content
|
||||
let write_cmd =
|
||||
Command::shell(format!("echo '{}' > {}", file_content, file_path.display()));
|
||||
|
||||
// Execute the write command
|
||||
executor.exec_cmd(&write_cmd).await?;
|
||||
|
||||
// Verify that the file was created successfully
|
||||
assert!(file_path.exists());
|
||||
|
||||
// Write a shell command to read the file's content
|
||||
let read_cmd = Command::shell(format!("cat {}", file_path.display()));
|
||||
|
||||
// Execute the read command
|
||||
let output = executor.exec_cmd(&read_cmd).await?;
|
||||
|
||||
// Verify that the content read from the file matches the expected content
|
||||
assert_eq!(output.to_string(), format!("{file_content}"));
|
||||
|
||||
let output = executor
|
||||
.exec_cmd(&Command::read_file(&file_path))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(output.to_string(), format!("{file_content}\n"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_echo_hello_world() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the echo command
|
||||
let echo_cmd = Command::shell("echo 'hello world'");
|
||||
|
||||
// Execute the echo command
|
||||
let output = executor.exec_cmd(&echo_cmd).await?;
|
||||
|
||||
// Verify that the output matches the expected content
|
||||
assert_eq!(output.to_string().trim(), "hello world");
|
||||
assert!(output.stderr.is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_preserves_stdout_and_stderr() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let output = executor
|
||||
.exec_cmd(&Command::shell(
|
||||
"printf 'hello stdout'; printf 'hello stderr' >&2",
|
||||
))
|
||||
.await?;
|
||||
|
||||
assert_eq!(output.stdout, "hello stdout");
|
||||
assert_eq!(output.stderr, "hello stderr");
|
||||
assert_eq!(output.to_string(), "hello stdout");
|
||||
assert!(format!("{output:?}").contains("hello stderr"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_keeps_display_empty_when_stdout_is_empty() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match executor
|
||||
.exec_cmd(&Command::shell("printf 'boom' >&2; exit 1"))
|
||||
.await
|
||||
{
|
||||
Err(CommandError::NonZeroExit(output)) => {
|
||||
assert!(output.stdout.is_empty());
|
||||
assert_eq!(output.stderr, "boom");
|
||||
assert_eq!(output.to_string(), "");
|
||||
assert_eq!(output.as_ref(), "");
|
||||
}
|
||||
other => anyhow::bail!("expected non-zero exit, got {other:?}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_shell_timeout() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut cmd = Command::shell("echo ready && sleep 1 && echo done");
|
||||
cmd.timeout(Duration::from_millis(100));
|
||||
|
||||
match executor.exec_cmd(&cmd).await {
|
||||
Err(CommandError::TimedOut { timeout, output }) => {
|
||||
assert_eq!(timeout, Duration::from_millis(100));
|
||||
assert!(output.to_string().contains("ready"));
|
||||
}
|
||||
other => anyhow::bail!("expected timeout error, got {other:?}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_default_timeout_applies() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutorBuilder::default()
|
||||
.workdir(temp_path.to_path_buf())
|
||||
.default_timeout(Some(Duration::from_millis(100)))
|
||||
.build()?;
|
||||
|
||||
match executor.exec_cmd(&Command::shell("sleep 1")).await {
|
||||
Err(CommandError::TimedOut { timeout, output }) => {
|
||||
assert_eq!(timeout, Duration::from_millis(100));
|
||||
assert!(output.to_string().is_empty());
|
||||
assert!(output.stderr.is_empty());
|
||||
}
|
||||
other => anyhow::bail!("expected default timeout, got {other:?}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_clear_env() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
env_clear: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the echo command
|
||||
let echo_cmd = Command::shell("printenv");
|
||||
|
||||
// Execute the echo command
|
||||
let output = executor.exec_cmd(&echo_cmd).await?.to_string();
|
||||
|
||||
// Verify that the output matches the expected content
|
||||
// assert_eq!(output.to_string().trim(), "");
|
||||
assert!(!output.contains("CARGO_PKG_VERSION"), "{output}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_add_env() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
envs: HashMap::from([("TEST_ENV".to_string(), "HELLO".to_string())]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the echo command
|
||||
let echo_cmd = Command::shell("printenv");
|
||||
|
||||
// Execute the echo command
|
||||
let output = executor.exec_cmd(&echo_cmd).await?.to_string();
|
||||
|
||||
// Verify that the output matches the expected content
|
||||
// assert_eq!(output.to_string().trim(), "");
|
||||
assert!(output.contains("TEST_ENV=HELLO"), "{output}");
|
||||
// Double tap its included by default
|
||||
assert!(output.contains("CARGO_PKG_VERSION"), "{output}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_env_remove() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
env_remove: vec!["CARGO_PKG_VERSION".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the echo command
|
||||
let echo_cmd = Command::shell("printenv");
|
||||
|
||||
// Execute the echo command
|
||||
let output = executor.exec_cmd(&echo_cmd).await?.to_string();
|
||||
|
||||
// Verify that the output matches the expected content
|
||||
// assert_eq!(output.to_string().trim(), "");
|
||||
assert!(!output.contains("CARGO_PKG_VERSION="), "{output}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_run_shebang() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let script = r#"#!/usr/bin/env python3
|
||||
print("hello from python")
|
||||
print(1 + 2)"#;
|
||||
|
||||
// Execute the echo command
|
||||
let output = executor
|
||||
.exec_cmd(&Command::shell(script))
|
||||
.await?
|
||||
.to_string();
|
||||
|
||||
// Verify that the output matches the expected content
|
||||
assert!(output.contains("hello from python"));
|
||||
assert!(output.contains('3'));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_multiline_with_quotes() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the file path and content
|
||||
let file_path = "test_file2.txt";
|
||||
let file_content = indoc! {r#"
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
"#};
|
||||
|
||||
// Write a shell command to create a file with the specified content
|
||||
let write_cmd = Command::shell(format!("echo '{file_content}' > {file_path}"));
|
||||
|
||||
// Execute the write command
|
||||
executor.exec_cmd(&write_cmd).await?;
|
||||
|
||||
// Write a shell command to read the file's content
|
||||
let read_cmd = Command::shell(format!("cat {file_path}"));
|
||||
|
||||
// Execute the read command
|
||||
let output = executor.exec_cmd(&read_cmd).await?;
|
||||
|
||||
// Verify that the content read from the file matches the expected content
|
||||
assert_eq!(output.to_string(), format!("{file_content}"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_write_and_read_file_commands() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Define the file path and content
|
||||
let file_path = temp_path.join("test_file.txt");
|
||||
let file_content = "Hello, world!";
|
||||
|
||||
// Assert that the file does not exist and it gives the correct error
|
||||
let cmd = Command::read_file(file_path.clone());
|
||||
let result = executor.exec_cmd(&cmd).await;
|
||||
|
||||
if let Err(err) = result {
|
||||
assert!(matches!(err, CommandError::NonZeroExit(..)));
|
||||
} else {
|
||||
panic!("Expected error but got {result:?}");
|
||||
}
|
||||
|
||||
// Create a write command
|
||||
let write_cmd = Command::write_file(file_path.clone(), file_content.to_string());
|
||||
|
||||
// Execute the write command
|
||||
executor.exec_cmd(&write_cmd).await?;
|
||||
|
||||
// Verify that the file was created successfully
|
||||
assert!(file_path.exists());
|
||||
|
||||
// Create a read command
|
||||
let read_cmd = Command::read_file(file_path.clone());
|
||||
|
||||
// Execute the read command
|
||||
let output = executor.exec_cmd(&read_cmd).await?.stdout;
|
||||
|
||||
// Verify that the content read from the file matches the expected content
|
||||
assert_eq!(output, file_content);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_stream_files() -> anyhow::Result<()> {
|
||||
// Create a temporary directory
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Create some test files in the temporary directory
|
||||
fs_err::write(temp_path.join("file1.txt"), "Content of file 1")?;
|
||||
fs_err::write(temp_path.join("file2.txt"), "Content of file 2")?;
|
||||
fs_err::write(temp_path.join("file3.rs"), "Content of file 3")?;
|
||||
|
||||
// Instantiate LocalExecutor with the temporary directory as workdir
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Stream files with no extensions filter
|
||||
let stream = executor.stream_files(temp_path, None).await?;
|
||||
let files: Vec<_> = stream.collect().await;
|
||||
|
||||
assert_eq!(files.len(), 3);
|
||||
|
||||
// Stream files with a specific extension filter
|
||||
let stream = executor
|
||||
.stream_files(temp_path, Some(vec!["txt".to_string()]))
|
||||
.await?;
|
||||
let txt_files: Vec<_> = stream.collect().await;
|
||||
|
||||
assert_eq!(txt_files.len(), 2);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_honors_workdir() -> anyhow::Result<()> {
|
||||
use std::fs;
|
||||
use temp_dir::TempDir;
|
||||
|
||||
// 1. Create a temp dir and instantiate executor
|
||||
let temp_dir = TempDir::new()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: temp_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 2. Run a shell command in workdir and check output is workdir
|
||||
let pwd_cmd = Command::shell("pwd");
|
||||
let pwd_output = executor.exec_cmd(&pwd_cmd).await?.to_string();
|
||||
let pwd_path = std::fs::canonicalize(pwd_output.trim())?;
|
||||
let temp_path = std::fs::canonicalize(temp_path)?;
|
||||
assert_eq!(pwd_path, temp_path);
|
||||
|
||||
// 3. Write a file using WriteFile (should land in workdir)
|
||||
let fname = "workdir_check.txt";
|
||||
let write_cmd = Command::write_file(fname, "test123");
|
||||
executor.exec_cmd(&write_cmd).await?;
|
||||
|
||||
// 4. Assert file exists in workdir, not current dir
|
||||
let expected_path = temp_path.join(fname);
|
||||
assert!(expected_path.exists());
|
||||
assert!(!Path::new(fname).exists());
|
||||
|
||||
// 5. Write/read using ReadFile
|
||||
let read_cmd = Command::read_file(fname);
|
||||
let read_output = executor.exec_cmd(&read_cmd).await?.to_string();
|
||||
assert_eq!(read_output.trim(), "test123");
|
||||
|
||||
// 6. Clean up
|
||||
fs::remove_file(&expected_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_command_current_dir() -> anyhow::Result<()> {
|
||||
use std::fs;
|
||||
use temp_dir::TempDir;
|
||||
|
||||
let temp_dir = TempDir::new()?;
|
||||
let base_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: base_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let nested_dir = base_path.join("nested");
|
||||
fs::create_dir_all(&nested_dir)?;
|
||||
|
||||
let mut pwd_cmd = Command::shell("pwd");
|
||||
pwd_cmd.current_dir(Path::new("nested"));
|
||||
let pwd_output = executor.exec_cmd(&pwd_cmd).await?.to_string();
|
||||
let pwd_path = std::fs::canonicalize(pwd_output.trim())?;
|
||||
assert_eq!(pwd_path, std::fs::canonicalize(&nested_dir)?);
|
||||
|
||||
let mut write_cmd = Command::write_file("file.txt", "hello");
|
||||
write_cmd.current_dir(Path::new("nested"));
|
||||
executor.exec_cmd(&write_cmd).await?;
|
||||
|
||||
assert!(!base_path.join("file.txt").exists());
|
||||
assert!(nested_dir.join("file.txt").exists());
|
||||
|
||||
let mut read_cmd = Command::read_file("file.txt");
|
||||
read_cmd.current_dir(Path::new("nested"));
|
||||
let read_output = executor.exec_cmd(&read_cmd).await?.to_string();
|
||||
assert_eq!(read_output.trim(), "hello");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_current_dir() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let base_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: base_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let nested = executor.scoped("nested");
|
||||
nested
|
||||
.exec_cmd(&Command::write_file("file.txt", "hello"))
|
||||
.await?;
|
||||
|
||||
assert!(!base_path.join("file.txt").exists());
|
||||
assert!(base_path.join("nested").join("file.txt").exists());
|
||||
assert_eq!(executor.workdir, base_path);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_local_executor_current_dir_dyn() -> anyhow::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let base_path = temp_dir.path();
|
||||
|
||||
let executor = LocalExecutor {
|
||||
workdir: base_path.to_path_buf(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let dyn_exec: Arc<dyn swiftide_core::ToolExecutor> = Arc::new(executor.clone());
|
||||
let nested = dyn_exec.scoped("nested");
|
||||
|
||||
nested
|
||||
.exec_cmd(&Command::write_file("nested_file.txt", "hello"))
|
||||
.await?;
|
||||
|
||||
assert!(base_path.join("nested").join("nested_file.txt").exists());
|
||||
assert!(!base_path.join("nested_file.txt").exists());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Add tools provided by an MCP server to an agent
|
||||
//!
|
||||
//! Uses the `rmcp` crate to connect to an MCP server and list available tools, and invoke them
|
||||
//!
|
||||
//! Supports any transport that the `rmcp` crate supports
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use async_trait::async_trait;
|
||||
use rmcp::RoleClient;
|
||||
use rmcp::ServiceExt;
|
||||
use rmcp::model::{CallToolRequestParams, ClientInfo, Implementation, InitializeRequestParams};
|
||||
use rmcp::service::RunningService;
|
||||
use rmcp::transport::IntoTransport;
|
||||
use schemars::Schema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swiftide_core::CommandError;
|
||||
use swiftide_core::chat_completion::ToolCall;
|
||||
use swiftide_core::{
|
||||
Tool, ToolBox,
|
||||
chat_completion::{ToolSpec, errors::ToolError},
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// A filter to apply to the available tools
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum ToolFilter {
|
||||
Blacklist(Vec<String>),
|
||||
Whitelist(Vec<String>),
|
||||
}
|
||||
|
||||
/// Connects to an MCP server and provides tools at runtime to the agent.
|
||||
///
|
||||
/// WARN: The rmcp has a quirky feature to serve from `()`. This does not work; serve from
|
||||
/// `ClientInfo` instead, or from the transport and `Swiftide` will handle the rest.
|
||||
#[derive(Clone)]
|
||||
pub struct McpToolbox {
|
||||
service: Arc<RwLock<Option<RunningService<RoleClient, InitializeRequestParams>>>>,
|
||||
|
||||
/// Optional human readable name for the toolbox
|
||||
name: Option<String>,
|
||||
|
||||
filter: Arc<Option<ToolFilter>>,
|
||||
}
|
||||
|
||||
impl McpToolbox {
|
||||
/// Blacklist tools by name, the agent will not be able to use these tools
|
||||
pub fn with_blacklist<ITEM: Into<String>, I: IntoIterator<Item = ITEM>>(
|
||||
&mut self,
|
||||
blacklist: I,
|
||||
) -> &mut Self {
|
||||
let list = blacklist.into_iter().map(Into::into).collect::<Vec<_>>();
|
||||
self.filter = Some(ToolFilter::Blacklist(list)).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Whitelist tools by name, the agent will only be able to use these tools
|
||||
pub fn with_whitelist<ITEM: Into<String>, I: IntoIterator<Item = ITEM>>(
|
||||
&mut self,
|
||||
blacklist: I,
|
||||
) -> &mut Self {
|
||||
let list = blacklist.into_iter().map(Into::into).collect::<Vec<_>>();
|
||||
self.filter = Some(ToolFilter::Whitelist(list)).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Apply a custom filter to the tools
|
||||
pub fn with_filter(&mut self, filter: ToolFilter) -> &mut Self {
|
||||
self.filter = Some(filter).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Apply an optional name to the toolbox
|
||||
pub fn with_name(&mut self, name: impl Into<String>) -> &mut Self {
|
||||
self.name = Some(name.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
self.name.as_deref().unwrap_or("MCP Toolbox")
|
||||
}
|
||||
|
||||
/// Create a new toolbox from a transport
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the transport fails to connect
|
||||
pub async fn try_from_transport<
|
||||
E: std::error::Error + From<std::io::Error> + Send + Sync + 'static,
|
||||
A,
|
||||
>(
|
||||
transport: impl IntoTransport<RoleClient, E, A>,
|
||||
) -> Result<Self> {
|
||||
let info = Self::default_client_info();
|
||||
let service = Arc::new(RwLock::new(Some(info.serve(transport).await?)));
|
||||
|
||||
Ok(Self {
|
||||
service,
|
||||
filter: None.into(),
|
||||
name: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a new toolbox from a running service
|
||||
pub fn from_running_service(
|
||||
service: RunningService<RoleClient, InitializeRequestParams>,
|
||||
) -> Self {
|
||||
Self {
|
||||
service: Arc::new(RwLock::new(Some(service))),
|
||||
filter: None.into(),
|
||||
name: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_client_info() -> ClientInfo {
|
||||
ClientInfo {
|
||||
client_info: Implementation {
|
||||
name: "swiftide".into(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
title: None,
|
||||
description: None,
|
||||
icons: None,
|
||||
website_url: None,
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Disconnects from the MCP server if it is running
|
||||
///
|
||||
/// If it is not running, an Ok is returned and it logs a tracing message
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if the service is running but cannot be stopped
|
||||
pub async fn cancel(&mut self) -> Result<()> {
|
||||
let mut lock = self.service.write().await;
|
||||
let Some(service) = std::mem::take(&mut *lock) else {
|
||||
tracing::warn!("mcp server is not running");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
tracing::debug!(name = self.name(), "Stopping mcp server");
|
||||
|
||||
service
|
||||
.cancel()
|
||||
.await
|
||||
.context("failed to stop mcp server")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ToolBox for McpToolbox {
|
||||
#[tracing::instrument(skip_all)]
|
||||
async fn available_tools(&self) -> Result<Vec<Box<dyn Tool>>> {
|
||||
let Some(service) = &*self.service.read().await else {
|
||||
anyhow::bail!("No service available");
|
||||
};
|
||||
tracing::debug!(name = self.name(), "Connecting to mcp server");
|
||||
let peer_info = service.peer_info();
|
||||
tracing::debug!(?peer_info, name = self.name(), "Connected to mcp server");
|
||||
|
||||
tracing::debug!(name = self.name(), "Listing tools from mcp server");
|
||||
let tools = service
|
||||
.list_all_tools()
|
||||
.await
|
||||
.context("Failed to list tools")?;
|
||||
|
||||
let filter = self.filter.as_ref();
|
||||
let mut server_name = peer_info
|
||||
.map_or("mcp", |info| info.server_info.name.as_str())
|
||||
.trim()
|
||||
.to_owned();
|
||||
if server_name.is_empty() {
|
||||
server_name = "mcp".into();
|
||||
}
|
||||
|
||||
let tools = tools
|
||||
.into_iter()
|
||||
.filter(|tool| match &filter {
|
||||
Some(ToolFilter::Blacklist(blacklist)) => {
|
||||
!blacklist.iter().any(|blocked| blocked == &tool.name)
|
||||
}
|
||||
Some(ToolFilter::Whitelist(whitelist)) => {
|
||||
whitelist.iter().any(|allowed| allowed == &tool.name)
|
||||
}
|
||||
None => true,
|
||||
})
|
||||
.map(|tool| {
|
||||
let schema_value = tool.schema_as_json_value();
|
||||
tracing::trace!(
|
||||
schema = ?schema_value,
|
||||
"Parsing tool input schema for {}",
|
||||
tool.name
|
||||
);
|
||||
|
||||
let mut tool_spec_builder = ToolSpec::builder();
|
||||
|
||||
// Preallocate to avoid repeated string growth.
|
||||
let mut registered_name =
|
||||
String::with_capacity(server_name.len() + tool.name.len() + 1);
|
||||
registered_name.push_str(&server_name);
|
||||
registered_name.push(':');
|
||||
registered_name.push_str(&tool.name);
|
||||
|
||||
tool_spec_builder.name(registered_name.clone());
|
||||
if let Some(description) = tool.description {
|
||||
tool_spec_builder.description(description);
|
||||
}
|
||||
|
||||
match schema_value {
|
||||
serde_json::Value::Null => {}
|
||||
value => {
|
||||
let schema: Schema = serde_json::from_value(value)
|
||||
.context("Failed to parse tool input schema")?;
|
||||
tool_spec_builder.parameters_schema(schema);
|
||||
}
|
||||
}
|
||||
|
||||
let tool_spec = tool_spec_builder
|
||||
.build()
|
||||
.context("Failed to build tool spec")?;
|
||||
Ok(Box::new(McpTool {
|
||||
client: Arc::clone(&self.service),
|
||||
registered_name,
|
||||
server_tool_name: tool.name.into(),
|
||||
tool_spec,
|
||||
}) as Box<dyn Tool>)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.context("Failed to build mcp tool specs")?;
|
||||
Ok(tools)
|
||||
}
|
||||
|
||||
fn name(&self) -> Cow<'_, str> {
|
||||
self.name().into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct McpTool {
|
||||
client: Arc<RwLock<Option<RunningService<RoleClient, InitializeRequestParams>>>>,
|
||||
registered_name: String,
|
||||
server_tool_name: String,
|
||||
tool_spec: ToolSpec,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for McpTool {
|
||||
async fn invoke(
|
||||
&self,
|
||||
_agent_context: &dyn swiftide_core::AgentContext,
|
||||
tool_call: &ToolCall,
|
||||
) -> Result<
|
||||
swiftide_core::chat_completion::ToolOutput,
|
||||
swiftide_core::chat_completion::errors::ToolError,
|
||||
> {
|
||||
let args = match tool_call.args() {
|
||||
Some(args) => Some(serde_json::from_str(args).map_err(ToolError::WrongArguments)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let request = CallToolRequestParams {
|
||||
meta: None,
|
||||
name: self.server_tool_name.clone().into(),
|
||||
arguments: args,
|
||||
task: None,
|
||||
};
|
||||
|
||||
let Some(service) = &*self.client.read().await else {
|
||||
return Err(
|
||||
CommandError::ExecutorError(anyhow::anyhow!("mcp server is not running")).into(),
|
||||
);
|
||||
};
|
||||
|
||||
tracing::debug!(request = ?request, tool = self.name().as_ref(), "Invoking mcp tool");
|
||||
let response = service
|
||||
.call_tool(request)
|
||||
.await
|
||||
.context("Failed to call tool")?;
|
||||
|
||||
tracing::debug!(response = ?response, tool = self.name().as_ref(), "Received response from mcp tool");
|
||||
let rmcp::model::CallToolResult {
|
||||
content,
|
||||
structured_content,
|
||||
is_error,
|
||||
..
|
||||
} = response;
|
||||
|
||||
let content = if content.is_empty() {
|
||||
structured_content.map(|structured| structured.to_string())
|
||||
} else {
|
||||
let mut iter = content.into_iter().filter_map(|c| match c.raw {
|
||||
rmcp::model::RawContent::Text(rmcp::model::RawTextContent { text, .. }) => {
|
||||
Some(text)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
iter.next().map(|first| {
|
||||
let mut joined = first;
|
||||
for part in iter {
|
||||
joined.push('\n');
|
||||
joined.push_str(&part);
|
||||
}
|
||||
joined
|
||||
})
|
||||
};
|
||||
|
||||
if is_error.unwrap_or(false) {
|
||||
let content = content.unwrap_or_else(|| "Unknown error".to_string());
|
||||
return Err(ToolError::Unknown(anyhow::anyhow!(
|
||||
"Failed to execute mcp tool: {content}"
|
||||
)));
|
||||
}
|
||||
|
||||
match content {
|
||||
Some(content) => Ok(content.into()),
|
||||
// Some MCP tools may legitimately return no textual or structured content
|
||||
// while still being successful (e.g. optional echo with null input).
|
||||
None => Ok("Tool executed successfully".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> std::borrow::Cow<'_, str> {
|
||||
self.registered_name.as_str().into()
|
||||
}
|
||||
|
||||
fn tool_spec(&self) -> ToolSpec {
|
||||
self.tool_spec.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use copied_from_rmcp::Calculator;
|
||||
use rmcp::serve_server;
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
|
||||
const SOCKET_PATH: &str = "/tmp/swiftide-mcp.sock";
|
||||
const EXPECTED_PREFIX: &str = "rmcp";
|
||||
|
||||
#[allow(clippy::similar_names)]
|
||||
#[test_log::test(tokio::test(flavor = "multi_thread"))]
|
||||
async fn test_socket() {
|
||||
let _ = std::fs::remove_file(SOCKET_PATH);
|
||||
|
||||
match UnixListener::bind(SOCKET_PATH) {
|
||||
Ok(unix_listener) => {
|
||||
println!("Server successfully listening on {SOCKET_PATH}");
|
||||
tokio::spawn(server(unix_listener));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Unable to bind to {SOCKET_PATH}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
let client = client().await.unwrap();
|
||||
|
||||
let t = client.available_tools().await.unwrap();
|
||||
assert_eq!(client.available_tools().await.unwrap().len(), 3);
|
||||
|
||||
let mut names = t.iter().map(|t| t.name().into_owned()).collect::<Vec<_>>();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
format!("{EXPECTED_PREFIX}:optional"),
|
||||
format!("{EXPECTED_PREFIX}:sub"),
|
||||
format!("{EXPECTED_PREFIX}:sum")
|
||||
]
|
||||
);
|
||||
|
||||
let sum_name = format!("{EXPECTED_PREFIX}:sum");
|
||||
let sum_tool = t.iter().find(|t| t.name().as_ref() == sum_name).unwrap();
|
||||
let mut builder = ToolCall::builder()
|
||||
.id("some")
|
||||
.args(r#"{"b": "hello"}"#)
|
||||
.name("test")
|
||||
.name("test")
|
||||
.to_owned();
|
||||
|
||||
assert_eq!(sum_tool.tool_spec().name, sum_name);
|
||||
|
||||
let tool_call = builder.args(r#"{"a": 10, "b": 20}"#).build().unwrap();
|
||||
|
||||
let result = sum_tool
|
||||
.invoke(&(), &tool_call)
|
||||
.await
|
||||
.unwrap()
|
||||
.content()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(result, "30");
|
||||
|
||||
let sub_name = format!("{EXPECTED_PREFIX}:sub");
|
||||
let sub_tool = t.iter().find(|t| t.name().as_ref() == sub_name).unwrap();
|
||||
assert_eq!(sub_tool.tool_spec().name, sub_name);
|
||||
|
||||
let tool_call = builder.args(r#"{"a": 10, "b": 20}"#).build().unwrap();
|
||||
|
||||
let result = sub_tool
|
||||
.invoke(&(), &tool_call)
|
||||
.await
|
||||
.unwrap()
|
||||
.content()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(result, "-10");
|
||||
|
||||
// The input schema type for the input param is string with null allowed
|
||||
let optional_name = format!("{EXPECTED_PREFIX}:optional");
|
||||
let optional_tool = t
|
||||
.iter()
|
||||
.find(|t| t.name().as_ref() == optional_name)
|
||||
.unwrap();
|
||||
assert_eq!(optional_tool.tool_spec().name, optional_name);
|
||||
let spec = optional_tool.tool_spec();
|
||||
let schema = spec
|
||||
.parameters_schema
|
||||
.expect("optional tool should expose a schema");
|
||||
let schema_json = serde_json::to_value(schema).unwrap();
|
||||
let _text_prop = schema_json
|
||||
.get("properties")
|
||||
.and_then(|props| props.get("text"))
|
||||
.expect("optional tool schema must include `text`");
|
||||
|
||||
let tool_call = builder.args(r#"{"text": "hello"}"#).build().unwrap();
|
||||
|
||||
let result = optional_tool
|
||||
.invoke(&(), &tool_call)
|
||||
.await
|
||||
.unwrap()
|
||||
.content()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(result, "hello");
|
||||
|
||||
let tool_call = builder.args(r#"{"text": null}"#).build().unwrap();
|
||||
let result = optional_tool
|
||||
.invoke(&(), &tool_call)
|
||||
.await
|
||||
.unwrap()
|
||||
.content()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(result, "");
|
||||
|
||||
// Clean up socket file
|
||||
let _ = std::fs::remove_file(SOCKET_PATH);
|
||||
}
|
||||
|
||||
async fn server(unix_listener: UnixListener) -> anyhow::Result<()> {
|
||||
while let Ok((stream, addr)) = unix_listener.accept().await {
|
||||
println!("Client connected: {addr:?}");
|
||||
tokio::spawn(async move {
|
||||
match serve_server(Calculator::new(), stream).await {
|
||||
Ok(server) => {
|
||||
println!("Server initialized successfully");
|
||||
if let Err(e) = server.waiting().await {
|
||||
println!("Error while server waiting: {e:?}");
|
||||
}
|
||||
}
|
||||
Err(e) => println!("Server initialization failed: {e:?}"),
|
||||
}
|
||||
|
||||
anyhow::Ok(())
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client() -> anyhow::Result<McpToolbox> {
|
||||
println!("Client connecting to {SOCKET_PATH}");
|
||||
let stream = UnixStream::connect(SOCKET_PATH).await?;
|
||||
|
||||
// let client = serve_client((), stream).await?;
|
||||
let client = McpToolbox::try_from_transport(stream).await?;
|
||||
println!("Client connected and initialized successfully");
|
||||
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
#[allow(clippy::unused_self)]
|
||||
mod copied_from_rmcp {
|
||||
use rmcp::{
|
||||
ErrorData as McpError, ServerHandler,
|
||||
handler::server::{tool::ToolRouter, wrapper::Parameters},
|
||||
model::{CallToolResult, Content, ServerCapabilities, ServerInfo},
|
||||
schemars, tool, tool_handler,
|
||||
};
|
||||
|
||||
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
|
||||
pub struct Request {
|
||||
pub a: i32,
|
||||
pub b: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
|
||||
pub struct OptRequest {
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Calculator {
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
#[rmcp::tool_router]
|
||||
impl Calculator {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tool_router: Self::tool_router(),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
#[tool(description = "Calculate the sum of two numbers")]
|
||||
fn sum(
|
||||
&self,
|
||||
Parameters(Request { a, b }): Parameters<Request>,
|
||||
) -> Result<CallToolResult, McpError> {
|
||||
Ok(CallToolResult::success(vec![Content::text(
|
||||
(a + b).to_string(),
|
||||
)]))
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
#[tool(description = "Calculate the sum of two numbers")]
|
||||
fn sub(
|
||||
&self,
|
||||
Parameters(Request { a, b }): Parameters<Request>,
|
||||
) -> Result<CallToolResult, McpError> {
|
||||
Ok(CallToolResult::success(vec![Content::text(
|
||||
(a - b).to_string(),
|
||||
)]))
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
#[tool(description = "Optional echo")]
|
||||
fn optional(
|
||||
&self,
|
||||
Parameters(OptRequest { text }): Parameters<OptRequest>,
|
||||
) -> Result<CallToolResult, McpError> {
|
||||
Ok(CallToolResult::success(vec![Content::text(
|
||||
text.unwrap_or_default(),
|
||||
)]))
|
||||
}
|
||||
}
|
||||
|
||||
#[tool_handler]
|
||||
impl ServerHandler for Calculator {
|
||||
fn get_info(&self) -> ServerInfo {
|
||||
ServerInfo {
|
||||
instructions: Some("A simple calculator".into()),
|
||||
capabilities: ServerCapabilities::builder().enable_tools().build(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Default tools and executor for agents
|
||||
pub mod arg_preprocessor;
|
||||
pub mod control;
|
||||
pub mod local_executor;
|
||||
|
||||
/// Add tools from a Model Context Protocol endpoint
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod mcp;
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Internal utility functions and macros for anything agent
|
||||
|
||||
/// Simple macro to consistently call hooks and clean up the code
|
||||
#[macro_export]
|
||||
macro_rules! invoke_hooks {
|
||||
(OnStream, $self_expr:expr $(, $arg:expr)* ) => {{
|
||||
// For streaming we log less and only on the trace level
|
||||
for hook in $self_expr.hooks_by_type(HookTypes::OnStream) {
|
||||
// Downcast to the correct closure variant
|
||||
if let Hook::OnStream(hook_fn) = hook {
|
||||
// Create a tracing span for instrumentation
|
||||
let span = tracing::trace_span!(
|
||||
"hook",
|
||||
"otel.name" = format!("hook.{:?}", HookTypes::OnStream)
|
||||
);
|
||||
|
||||
// Call the hook, instrument, and log on failure
|
||||
if let Err(err) = hook_fn($self_expr $(, $arg)*)
|
||||
.instrument(span.or_current())
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Error in {hooktype} hook: {err}",
|
||||
hooktype = HookTypes::OnStream,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
($hook_type:ident, $self_expr:expr $(, $arg:expr)* ) => {{
|
||||
// Iterate through every hook matching `HookTypes::$hook_type`
|
||||
for hook in $self_expr.hooks_by_type(HookTypes::$hook_type) {
|
||||
// Downcast to the correct closure variant
|
||||
if let Hook::$hook_type(hook_fn) = hook {
|
||||
// Create a tracing span for instrumentation
|
||||
let span = tracing::info_span!(
|
||||
"hook",
|
||||
"otel.name" = format!("hook.{:?}", HookTypes::$hook_type)
|
||||
);
|
||||
tracing::debug!("Calling {} hook", HookTypes::$hook_type);
|
||||
|
||||
// Call the hook, instrument, and log on failure
|
||||
if let Err(err) = hook_fn($self_expr $(, $arg)*)
|
||||
.instrument(span.or_current())
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Error in {hooktype} hook: {err}",
|
||||
hooktype = HookTypes::$hook_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
cargo-features = ["edition2024"]
|
||||
|
||||
[package]
|
||||
name = "swiftide-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
description.workspace = true
|
||||
categories.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
tracing = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
futures-util = { workspace = true }
|
||||
tokio-stream = { workspace = true }
|
||||
itertools = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
strum = { workspace = true }
|
||||
strum_macros = { workspace = true }
|
||||
mockall = { workspace = true, optional = true }
|
||||
lazy_static = { workspace = true }
|
||||
derive_builder = { workspace = true }
|
||||
dyn-clone = { workspace = true }
|
||||
pin-project = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
metrics = { workspace = true, optional = true }
|
||||
schemars = { workspace = true, features = ["derive"] }
|
||||
async-openai = { workspace = true, optional = true, features = ["chat-completion-types", "embedding-types", "response-types"] }
|
||||
|
||||
tera = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4", "v3"] }
|
||||
|
||||
pretty_assertions = { workspace = true, optional = true }
|
||||
|
||||
# Integrations
|
||||
qdrant-client = { workspace = true, optional = true }
|
||||
backoff = { version = "0.4.0", features = ["futures", "tokio"] }
|
||||
|
||||
[dev-dependencies]
|
||||
test-case = { workspace = true }
|
||||
test-log = { workspace = true }
|
||||
tokio = { workspace = true, features = ["time", "test-util"] }
|
||||
tokio-stream = { workspace = true }
|
||||
|
||||
[features]
|
||||
defaults = ["truncate-debug"]
|
||||
test-utils = ["dep:mockall", "dep:pretty_assertions"]
|
||||
qdrant = ["dep:qdrant-client"]
|
||||
# Truncates large debug outputs on pipeline nodes
|
||||
truncate-debug = []
|
||||
metrics = ["dep:metrics"]
|
||||
json-schema = []
|
||||
openai = ["dep:async-openai"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# Swiftide-core
|
||||
|
||||
Core crate includes low level types and traits for swiftide that are used by other crates.
|
||||
@@ -0,0 +1,766 @@
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
chat_completion::{ChatMessage, ToolCall},
|
||||
indexing::IndexingStream,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use dyn_clone::DynClone;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
/// A `ToolExecutor` provides an interface for agents to interact with a system
|
||||
/// in an isolated context.
|
||||
///
|
||||
/// When starting up an agent, it's context expects an executor. For example,
|
||||
/// you might want your coding agent to work with a fresh, isolated set of files,
|
||||
/// separated from the rest of the system.
|
||||
///
|
||||
/// See `swiftide-docker-executor` for an executor that uses Docker. By default
|
||||
/// the executor is a local executor.
|
||||
///
|
||||
/// Additionally, the executor can be used stream files files for indexing.
|
||||
#[async_trait]
|
||||
pub trait ToolExecutor: Send + Sync + DynClone {
|
||||
/// Execute a command in the executor
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError>;
|
||||
|
||||
/// Stream files from the executor
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<IndexingStream<String>>;
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(ToolExecutor);
|
||||
|
||||
/// Lightweight executor wrapper that applies a default working directory to forwarded commands.
|
||||
///
|
||||
/// Most callers should construct this via [`ExecutorExt::scoped`], which borrows the underlying
|
||||
/// executor and only clones commands/paths when the scope actually changes their resolution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScopedExecutor<E> {
|
||||
executor: E,
|
||||
scope: PathBuf,
|
||||
}
|
||||
|
||||
impl<E> ScopedExecutor<E> {
|
||||
/// Build a new wrapper around `executor` that prefixes relative paths with `scope`.
|
||||
pub fn new(executor: E, scope: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
executor,
|
||||
scope: scope.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns either the original command or a scoped clone depending on the current directory.
|
||||
fn apply_scope<'a>(&'a self, cmd: &'a Command) -> Cow<'a, Command> {
|
||||
match cmd.current_dir_path() {
|
||||
Some(path) if path.is_absolute() || self.scope.as_os_str().is_empty() => {
|
||||
Cow::Borrowed(cmd)
|
||||
}
|
||||
Some(path) => {
|
||||
let mut scoped = cmd.clone();
|
||||
scoped.current_dir(self.scope.join(path));
|
||||
Cow::Owned(scoped)
|
||||
}
|
||||
None if self.scope.as_os_str().is_empty() => Cow::Borrowed(cmd),
|
||||
None => {
|
||||
let mut scoped = cmd.clone();
|
||||
scoped.current_dir(self.scope.clone());
|
||||
Cow::Owned(scoped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a path adjusted for the scope when the provided path is relative.
|
||||
fn scoped_path<'a>(&'a self, path: &'a Path) -> Cow<'a, Path> {
|
||||
if path.is_absolute() || self.scope.as_os_str().is_empty() {
|
||||
Cow::Borrowed(path)
|
||||
} else {
|
||||
Cow::Owned(self.scope.join(path))
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the inner executor.
|
||||
pub fn inner(&self) -> &E {
|
||||
&self.executor
|
||||
}
|
||||
|
||||
/// Expose the scope that will be applied to relative paths.
|
||||
pub fn scope(&self) -> &Path {
|
||||
&self.scope
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> ToolExecutor for ScopedExecutor<E>
|
||||
where
|
||||
E: ToolExecutor + Send + Sync + Clone,
|
||||
{
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
let scoped_cmd = self.apply_scope(cmd);
|
||||
self.executor.exec_cmd(scoped_cmd.as_ref()).await
|
||||
}
|
||||
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<IndexingStream<String>> {
|
||||
let scoped_path = self.scoped_path(path);
|
||||
self.executor
|
||||
.stream_files(scoped_path.as_ref(), extensions)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience methods for scoping executors without cloning them.
|
||||
pub trait ExecutorExt {
|
||||
/// Borrow `self` and return a wrapper that resolves relative operations inside `path`.
|
||||
fn scoped(&self, path: impl Into<PathBuf>) -> ScopedExecutor<&Self>;
|
||||
|
||||
fn scoped_owned(self, path: impl Into<PathBuf>) -> ScopedExecutor<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
impl<T> ExecutorExt for T
|
||||
where
|
||||
T: ToolExecutor,
|
||||
{
|
||||
fn scoped(&self, path: impl Into<PathBuf>) -> ScopedExecutor<&Self> {
|
||||
ScopedExecutor::new(self, path)
|
||||
}
|
||||
|
||||
fn scoped_owned(self, path: impl Into<PathBuf>) -> ScopedExecutor<Self> {
|
||||
ScopedExecutor::new(self, path)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T> ToolExecutor for &T
|
||||
where
|
||||
T: ToolExecutor + ?Sized,
|
||||
{
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
(**self).exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<IndexingStream<String>> {
|
||||
(**self).stream_files(path, extensions).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ToolExecutor for Arc<dyn ToolExecutor> {
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
self.as_ref().exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<IndexingStream<String>> {
|
||||
self.as_ref().stream_files(path, extensions).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ToolExecutor for Box<dyn ToolExecutor> {
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
self.as_ref().exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
async fn stream_files(
|
||||
&self,
|
||||
path: &Path,
|
||||
extensions: Option<Vec<String>>,
|
||||
) -> Result<IndexingStream<String>> {
|
||||
self.as_ref().stream_files(path, extensions).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CommandError {
|
||||
/// The executor itself failed
|
||||
#[error("executor error: {0:#}")]
|
||||
ExecutorError(#[from] anyhow::Error),
|
||||
|
||||
/// The command exceeded its allotted time budget
|
||||
#[error("command timed out after {timeout:?}: {output}")]
|
||||
TimedOut {
|
||||
timeout: Duration,
|
||||
output: CommandOutput,
|
||||
},
|
||||
|
||||
/// The command failed, i.e. failing tests with stderr. This error might be handled
|
||||
#[error("command failed with NonZeroExit: {0}")]
|
||||
NonZeroExit(CommandOutput),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CommandError {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
CommandError::NonZeroExit(err.to_string().into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands that can be executed by the executor
|
||||
/// Conceptually, `Shell` allows any kind of input, and other commands enable more optimized
|
||||
/// implementations.
|
||||
///
|
||||
/// There is an ongoing consideration to make this an associated type on the executor
|
||||
///
|
||||
/// TODO: Should be able to borrow everything?
|
||||
///
|
||||
/// Use the constructor helpers (e.g. [`Command::shell`]) and then chain configuration methods
|
||||
/// such as [`Command::with_current_dir`] or [`Command::current_dir`] for builder-style ergonomics.
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub enum Command {
|
||||
Shell {
|
||||
command: String,
|
||||
current_dir: Option<PathBuf>,
|
||||
timeout: Option<Duration>,
|
||||
},
|
||||
ReadFile {
|
||||
path: PathBuf,
|
||||
current_dir: Option<PathBuf>,
|
||||
timeout: Option<Duration>,
|
||||
},
|
||||
WriteFile {
|
||||
path: PathBuf,
|
||||
content: String,
|
||||
current_dir: Option<PathBuf>,
|
||||
timeout: Option<Duration>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn shell<S: Into<String>>(cmd: S) -> Self {
|
||||
Command::Shell {
|
||||
command: cmd.into(),
|
||||
current_dir: None,
|
||||
timeout: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_file<P: Into<PathBuf>>(path: P) -> Self {
|
||||
Command::ReadFile {
|
||||
path: path.into(),
|
||||
current_dir: None,
|
||||
timeout: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_file<P: Into<PathBuf>, S: Into<String>>(path: P, content: S) -> Self {
|
||||
Command::WriteFile {
|
||||
path: path.into(),
|
||||
content: content.into(),
|
||||
current_dir: None,
|
||||
timeout: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Override the working directory used when executing this command.
|
||||
///
|
||||
/// Executors may interpret relative paths in the context of their own
|
||||
/// working directory.
|
||||
#[must_use]
|
||||
pub fn with_current_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
|
||||
self.current_dir(path);
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the working directory using the `std::process::Command`
|
||||
/// builder-lite style API.
|
||||
pub fn current_dir<P: Into<PathBuf>>(&mut self, path: P) -> &mut Self {
|
||||
let dir = Some(path.into());
|
||||
match self {
|
||||
Command::Shell { current_dir, .. }
|
||||
| Command::ReadFile { current_dir, .. }
|
||||
| Command::WriteFile { current_dir, .. } => {
|
||||
*current_dir = dir;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn clear_current_dir(&mut self) -> &mut Self {
|
||||
match self {
|
||||
Command::Shell { current_dir, .. }
|
||||
| Command::ReadFile { current_dir, .. }
|
||||
| Command::WriteFile { current_dir, .. } => {
|
||||
*current_dir = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn current_dir_path(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Command::Shell { current_dir, .. }
|
||||
| Command::ReadFile { current_dir, .. }
|
||||
| Command::WriteFile { current_dir, .. } => current_dir.as_deref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Override the timeout used when executing this command.
|
||||
#[must_use]
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.timeout(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the timeout using the builder-style API.
|
||||
pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
|
||||
match self {
|
||||
Command::Shell { timeout: slot, .. }
|
||||
| Command::ReadFile { timeout: slot, .. }
|
||||
| Command::WriteFile { timeout: slot, .. } => {
|
||||
*slot = Some(timeout);
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Remove any timeout previously configured on this command.
|
||||
pub fn clear_timeout(&mut self) -> &mut Self {
|
||||
match self {
|
||||
Command::Shell { timeout, .. }
|
||||
| Command::ReadFile { timeout, .. }
|
||||
| Command::WriteFile { timeout, .. } => {
|
||||
*timeout = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the timeout associated with this command, if any.
|
||||
pub fn timeout_duration(&self) -> Option<&Duration> {
|
||||
match self {
|
||||
Command::Shell { timeout, .. }
|
||||
| Command::ReadFile { timeout, .. }
|
||||
| Command::WriteFile { timeout, .. } => timeout.as_ref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output from a `Command`
|
||||
///
|
||||
/// String-like accessors such as [`std::fmt::Display`] and [`AsRef<str>`] expose stdout only.
|
||||
/// Use the dedicated fields or accessors when stderr is needed explicitly.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CommandOutput {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
// status_code: i32,
|
||||
// success: bool,
|
||||
}
|
||||
|
||||
impl CommandOutput {
|
||||
pub fn empty() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn new(stdout: impl Into<String>) -> Self {
|
||||
Self {
|
||||
stdout: stdout.into(),
|
||||
stderr: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_parts(stdout: impl Into<String>, stderr: impl Into<String>) -> Self {
|
||||
Self {
|
||||
stdout: stdout.into(),
|
||||
stderr: stderr.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stdout(&self) -> &str {
|
||||
&self.stdout
|
||||
}
|
||||
|
||||
pub fn stderr(&self) -> &str {
|
||||
&self.stderr
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.stdout.is_empty() && self.stderr.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CommandOutput {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.stdout.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<String>> From<T> for CommandOutput {
|
||||
fn from(value: T) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for CommandOutput {
|
||||
fn as_ref(&self) -> &str {
|
||||
&self.stdout
|
||||
}
|
||||
}
|
||||
|
||||
/// Feedback that can be given on a tool, i.e. with a human in the loop
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, strum_macros::EnumIs)]
|
||||
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
|
||||
pub enum ToolFeedback {
|
||||
Approved { payload: Option<serde_json::Value> },
|
||||
Refused { payload: Option<serde_json::Value> },
|
||||
}
|
||||
|
||||
impl ToolFeedback {
|
||||
pub fn approved() -> Self {
|
||||
ToolFeedback::Approved { payload: None }
|
||||
}
|
||||
|
||||
pub fn refused() -> Self {
|
||||
ToolFeedback::Refused { payload: None }
|
||||
}
|
||||
|
||||
pub fn payload(&self) -> Option<&serde_json::Value> {
|
||||
match self {
|
||||
ToolFeedback::Refused { payload } | ToolFeedback::Approved { payload } => {
|
||||
payload.as_ref()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_payload(self, payload: serde_json::Value) -> Self {
|
||||
match self {
|
||||
ToolFeedback::Approved { .. } => ToolFeedback::Approved {
|
||||
payload: Some(payload),
|
||||
},
|
||||
ToolFeedback::Refused { .. } => ToolFeedback::Refused {
|
||||
payload: Some(payload),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Acts as the interface to the external world and manages messages for completion
|
||||
#[async_trait]
|
||||
pub trait AgentContext: Send + Sync {
|
||||
/// List of all messages for this agent
|
||||
///
|
||||
/// Used as main source for the next completion and expects all
|
||||
/// messages to be returned if new messages are present.
|
||||
///
|
||||
/// Once this method has been called, there should not be new messages
|
||||
///
|
||||
/// TODO: Figure out a nice way to return a reference instead while still supporting i.e.
|
||||
/// mutexes
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>>;
|
||||
|
||||
/// Lists only the new messages after calling `new_completion`
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>>;
|
||||
|
||||
/// Add messages for the next completion
|
||||
async fn add_messages(&self, item: Vec<ChatMessage>) -> Result<()>;
|
||||
|
||||
/// Add messages for the next completion
|
||||
async fn add_message(&self, item: ChatMessage) -> Result<()>;
|
||||
|
||||
/// Execute a command if the context supports it
|
||||
///
|
||||
/// Deprecated: use executor instead to access the executor directly
|
||||
#[deprecated(note = "use executor instead")]
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError>;
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor>;
|
||||
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>>;
|
||||
|
||||
/// Replace the entire history with the given items
|
||||
async fn replace_history(&self, items: Vec<ChatMessage>) -> Result<()>;
|
||||
|
||||
/// Pops the last messages up until the last completion
|
||||
///
|
||||
/// LLMs failing completion for various reasons is unfortunately a common occurrence
|
||||
/// This gives a way to redrive the last completion in a generic way
|
||||
async fn redrive(&self) -> Result<()>;
|
||||
|
||||
/// Tools that require feedback or approval (i.e. from a human) can use this to check if the
|
||||
/// feedback is received
|
||||
async fn has_received_feedback(&self, tool_call: &ToolCall) -> Option<ToolFeedback>;
|
||||
|
||||
async fn feedback_received(&self, tool_call: &ToolCall, feedback: &ToolFeedback) -> Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentContext for Box<dyn AgentContext> {
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>> {
|
||||
(**self).next_completion().await
|
||||
}
|
||||
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).current_new_messages().await
|
||||
}
|
||||
|
||||
async fn add_messages(&self, item: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).add_messages(item).await
|
||||
}
|
||||
|
||||
async fn add_message(&self, item: ChatMessage) -> Result<()> {
|
||||
(**self).add_message(item).await
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
(**self).exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor> {
|
||||
(**self).executor()
|
||||
}
|
||||
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).history().await
|
||||
}
|
||||
|
||||
async fn replace_history(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).replace_history(items).await
|
||||
}
|
||||
|
||||
async fn redrive(&self) -> Result<()> {
|
||||
(**self).redrive().await
|
||||
}
|
||||
|
||||
async fn has_received_feedback(&self, tool_call: &ToolCall) -> Option<ToolFeedback> {
|
||||
(**self).has_received_feedback(tool_call).await
|
||||
}
|
||||
|
||||
async fn feedback_received(&self, tool_call: &ToolCall, feedback: &ToolFeedback) -> Result<()> {
|
||||
(**self).feedback_received(tool_call, feedback).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentContext for Arc<dyn AgentContext> {
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>> {
|
||||
(**self).next_completion().await
|
||||
}
|
||||
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).current_new_messages().await
|
||||
}
|
||||
|
||||
async fn add_messages(&self, item: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).add_messages(item).await
|
||||
}
|
||||
|
||||
async fn add_message(&self, item: ChatMessage) -> Result<()> {
|
||||
(**self).add_message(item).await
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
(**self).exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor> {
|
||||
(**self).executor()
|
||||
}
|
||||
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).history().await
|
||||
}
|
||||
|
||||
async fn replace_history(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).replace_history(items).await
|
||||
}
|
||||
|
||||
async fn redrive(&self) -> Result<()> {
|
||||
(**self).redrive().await
|
||||
}
|
||||
|
||||
async fn has_received_feedback(&self, tool_call: &ToolCall) -> Option<ToolFeedback> {
|
||||
(**self).has_received_feedback(tool_call).await
|
||||
}
|
||||
|
||||
async fn feedback_received(&self, tool_call: &ToolCall, feedback: &ToolFeedback) -> Result<()> {
|
||||
(**self).feedback_received(tool_call, feedback).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentContext for &dyn AgentContext {
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>> {
|
||||
(**self).next_completion().await
|
||||
}
|
||||
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).current_new_messages().await
|
||||
}
|
||||
|
||||
async fn add_messages(&self, item: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).add_messages(item).await
|
||||
}
|
||||
|
||||
async fn add_message(&self, item: ChatMessage) -> Result<()> {
|
||||
(**self).add_message(item).await
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
async fn exec_cmd(&self, cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
(**self).exec_cmd(cmd).await
|
||||
}
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor> {
|
||||
(**self).executor()
|
||||
}
|
||||
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
(**self).history().await
|
||||
}
|
||||
|
||||
async fn replace_history(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
(**self).replace_history(items).await
|
||||
}
|
||||
|
||||
async fn redrive(&self) -> Result<()> {
|
||||
(**self).redrive().await
|
||||
}
|
||||
|
||||
async fn has_received_feedback(&self, tool_call: &ToolCall) -> Option<ToolFeedback> {
|
||||
(**self).has_received_feedback(tool_call).await
|
||||
}
|
||||
|
||||
async fn feedback_received(&self, tool_call: &ToolCall, feedback: &ToolFeedback) -> Result<()> {
|
||||
(**self).feedback_received(tool_call, feedback).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience implementation for empty agent context
|
||||
///
|
||||
/// Errors if tools attempt to execute commands
|
||||
#[async_trait]
|
||||
impl AgentContext for () {
|
||||
async fn next_completion(&self) -> Result<Option<Vec<ChatMessage>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn current_new_messages(&self) -> Result<Vec<ChatMessage>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn add_messages(&self, _item: Vec<ChatMessage>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_message(&self, _item: ChatMessage) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_cmd(&self, _cmd: &Command) -> Result<CommandOutput, CommandError> {
|
||||
Err(CommandError::ExecutorError(anyhow::anyhow!(
|
||||
"Empty agent context does not have a tool executor"
|
||||
)))
|
||||
}
|
||||
|
||||
fn executor(&self) -> &Arc<dyn ToolExecutor> {
|
||||
unimplemented!("Empty agent context does not have a tool executor")
|
||||
}
|
||||
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn replace_history(&self, _items: Vec<ChatMessage>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn redrive(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn has_received_feedback(&self, _tool_call: &ToolCall) -> Option<ToolFeedback> {
|
||||
Some(ToolFeedback::Approved { payload: None })
|
||||
}
|
||||
|
||||
async fn feedback_received(
|
||||
&self,
|
||||
_tool_call: &ToolCall,
|
||||
_feedback: &ToolFeedback,
|
||||
) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A backend for the agent context.
|
||||
///
|
||||
/// A default is provided for `Arc<Mutex<Vec<ChatMessage>>>`.
|
||||
///
|
||||
/// If you want to use for instance a database, implement this trait and pass it to the agent
|
||||
/// context when creating it.
|
||||
#[async_trait]
|
||||
pub trait MessageHistory: Send + Sync + std::fmt::Debug {
|
||||
/// Returns the history of messages
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>>;
|
||||
|
||||
/// Add a message to the history
|
||||
async fn push_owned(&self, item: ChatMessage) -> Result<()>;
|
||||
|
||||
/// Overwrite the history with the given items
|
||||
async fn overwrite(&self, items: Vec<ChatMessage>) -> Result<()>;
|
||||
|
||||
/// Add a message to the history.
|
||||
async fn push(&self, item: &ChatMessage) -> Result<()> {
|
||||
self.push_owned(item.to_owned()).await
|
||||
}
|
||||
|
||||
/// Extend the history with the given items.
|
||||
async fn extend(&self, items: &[ChatMessage]) -> Result<()> {
|
||||
self.extend_owned(items.iter().map(ChatMessage::to_owned).collect())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Extend the history with the given items, taking ownership of them
|
||||
async fn extend_owned(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
for item in items {
|
||||
self.push_owned(item).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MessageHistory for Mutex<Vec<ChatMessage>> {
|
||||
async fn history(&self) -> Result<Vec<ChatMessage>> {
|
||||
Ok(self.lock().unwrap().clone())
|
||||
}
|
||||
|
||||
async fn push_owned(&self, item: ChatMessage) -> Result<()> {
|
||||
self.lock().unwrap().push(item);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn overwrite(&self, items: Vec<ChatMessage>) -> Result<()> {
|
||||
let mut lock = self.lock().unwrap();
|
||||
*lock = items;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
use std::{borrow::Cow, collections::BTreeSet};
|
||||
|
||||
use derive_builder::Builder;
|
||||
|
||||
use super::{chat_message::ChatMessage, tools::ToolSpec, traits::Tool};
|
||||
|
||||
/// A chat completion request represents a series of chat messages and tool interactions that can
|
||||
/// be send to any LLM.
|
||||
#[derive(Builder, Clone, PartialEq, Debug)]
|
||||
#[builder(setter(into, strip_option))]
|
||||
pub struct ChatCompletionRequest<'a> {
|
||||
pub messages: Cow<'a, [ChatMessage]>,
|
||||
#[builder(default, setter(custom))]
|
||||
pub tools_spec: BTreeSet<ToolSpec>,
|
||||
}
|
||||
|
||||
impl<'a> ChatCompletionRequest<'a> {
|
||||
pub fn builder() -> ChatCompletionRequestBuilder<'a> {
|
||||
ChatCompletionRequestBuilder::default()
|
||||
}
|
||||
|
||||
/// Returns the chat messages included in the request.
|
||||
pub fn messages(&self) -> &[ChatMessage] {
|
||||
self.messages.as_ref()
|
||||
}
|
||||
|
||||
/// Returns the tool specifications currently attached to the request.
|
||||
pub fn tools_spec(&self) -> &BTreeSet<ToolSpec> {
|
||||
&self.tools_spec
|
||||
}
|
||||
|
||||
/// Returns an owned request with `'static` data.
|
||||
pub fn to_owned(&self) -> ChatCompletionRequest<'static> {
|
||||
ChatCompletionRequest {
|
||||
messages: Cow::Owned(self.messages.iter().map(ChatMessage::to_owned).collect()),
|
||||
tools_spec: self.tools_spec.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<ChatMessage>> for ChatCompletionRequest<'_> {
|
||||
fn from(messages: Vec<ChatMessage>) -> Self {
|
||||
ChatCompletionRequest {
|
||||
messages: Cow::Owned(messages),
|
||||
tools_spec: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a [ChatMessage]> for ChatCompletionRequest<'a> {
|
||||
fn from(messages: &'a [ChatMessage]) -> Self {
|
||||
ChatCompletionRequest {
|
||||
messages: Cow::Borrowed(messages),
|
||||
tools_spec: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatCompletionRequestBuilder<'_> {
|
||||
#[deprecated(note = "Use `tools` with real Tool instances instead")]
|
||||
pub fn tools_spec<I>(&mut self, tools_spec: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = ToolSpec>,
|
||||
{
|
||||
self.tools_spec = Some(tools_spec.into_iter().collect());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds multiple tools by deriving their specs from the provided instances.
|
||||
pub fn tools<I, T>(&mut self, tools: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<Box<dyn Tool>>,
|
||||
{
|
||||
let specs = tools.into_iter().map(|tool| {
|
||||
let boxed: Box<dyn Tool> = tool.into();
|
||||
boxed.tool_spec()
|
||||
});
|
||||
self.tool_specs(specs)
|
||||
}
|
||||
|
||||
/// Adds a single tool instance to the request by deriving its spec.
|
||||
pub fn tool<T>(&mut self, tool: T) -> &mut Self
|
||||
where
|
||||
T: Into<Box<dyn Tool>>,
|
||||
{
|
||||
let boxed: Box<dyn Tool> = tool.into();
|
||||
self.tool_specs(std::iter::once(boxed.tool_spec()))
|
||||
}
|
||||
|
||||
/// Extends the request with additional tool specifications.
|
||||
pub fn tool_specs<I>(&mut self, specs: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = ToolSpec>,
|
||||
{
|
||||
let entry = self.tools_spec.get_or_insert_with(BTreeSet::new);
|
||||
entry.extend(specs);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a single chat message to the request
|
||||
pub fn message(&mut self, message: impl Into<ChatMessage>) -> &mut Self {
|
||||
let mut messages = self
|
||||
.messages
|
||||
.take()
|
||||
.map(Cow::into_owned)
|
||||
.unwrap_or_default();
|
||||
messages.push(message.into());
|
||||
|
||||
self.messages = Some(Cow::Owned(messages));
|
||||
self
|
||||
}
|
||||
|
||||
/// Extends the request with multiple chat messages.
|
||||
pub fn messages_iter<I>(&mut self, messages: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = ChatMessage>,
|
||||
{
|
||||
let mut new_messages = self
|
||||
.messages
|
||||
.take()
|
||||
.map(Cow::into_owned)
|
||||
.unwrap_or_default();
|
||||
new_messages.extend(messages);
|
||||
self.messages = Some(Cow::Owned(new_messages));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ChatCompletionRequest;
|
||||
use crate::chat_completion::{ChatMessage, ToolSpec};
|
||||
use schemars::Schema;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn tool_specs_are_stored_in_deterministic_order() {
|
||||
let zebra = ToolSpec::builder()
|
||||
.name("zebra")
|
||||
.description("later alphabetically")
|
||||
.parameters_schema(schema_from_json(json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"b": { "type": "string" },
|
||||
"a": { "type": "string" }
|
||||
}
|
||||
})))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let alpha = ToolSpec::builder()
|
||||
.name("alpha")
|
||||
.description("earlier alphabetically")
|
||||
.parameters_schema(schema_from_json(json!({
|
||||
"properties": {
|
||||
"z": { "type": "string" },
|
||||
"m": { "type": "string" }
|
||||
},
|
||||
"type": "object"
|
||||
})))
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let request = ChatCompletionRequest::builder()
|
||||
.messages(vec![ChatMessage::User("hi".into())])
|
||||
.tool_specs([zebra, alpha])
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let names = request
|
||||
.tools_spec()
|
||||
.iter()
|
||||
.map(|spec| spec.name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(names, vec!["alpha", "zebra"]);
|
||||
}
|
||||
|
||||
fn schema_from_json(value: serde_json::Value) -> Schema {
|
||||
serde_json::from_value(value).expect("valid schema")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use derive_builder::Builder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{ReasoningItem, ToolCallBuilder, tools::ToolCall};
|
||||
|
||||
/// A generic response from chat completions
|
||||
///
|
||||
/// When streaming, the delta is available. Every response will have the accumulated message if
|
||||
/// present. The final message will also have the final tool calls.
|
||||
#[derive(Clone, Builder, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[builder(setter(strip_option, into), build_fn(error = anyhow::Error))]
|
||||
pub struct ChatCompletionResponse {
|
||||
/// An identifier for the response
|
||||
///
|
||||
/// Useful when streaming to make sure chunks can be mapped to the right response
|
||||
#[builder(private, default = Uuid::new_v4())]
|
||||
pub id: Uuid,
|
||||
|
||||
#[builder(default)]
|
||||
pub message: Option<String>,
|
||||
|
||||
#[builder(default)]
|
||||
pub tool_calls: Option<Vec<ToolCall>>,
|
||||
|
||||
#[builder(default)]
|
||||
pub usage: Option<Usage>,
|
||||
|
||||
#[builder(default)]
|
||||
pub reasoning: Option<Vec<ReasoningItem>>,
|
||||
|
||||
/// Streaming response
|
||||
#[builder(default)]
|
||||
pub delta: Option<ChatCompletionResponseDelta>,
|
||||
}
|
||||
|
||||
impl Default for ChatCompletionResponse {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4(),
|
||||
message: None,
|
||||
tool_calls: None,
|
||||
delta: None,
|
||||
usage: None,
|
||||
reasoning: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Usage statistics for a language model response.
|
||||
#[derive(Clone, Default, Builder, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[allow(clippy::struct_field_names)]
|
||||
pub struct Usage {
|
||||
/// Tokens used in the prompt or input.
|
||||
pub prompt_tokens: u32,
|
||||
/// Tokens generated in the completion or output.
|
||||
pub completion_tokens: u32,
|
||||
/// Total tokens used for the request.
|
||||
pub total_tokens: u32,
|
||||
/// Provider-specific usage breakdowns, when available.
|
||||
#[builder(default)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub details: Option<UsageDetails>,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
pub fn builder() -> UsageBuilder {
|
||||
UsageBuilder::default()
|
||||
}
|
||||
|
||||
/// Returns a normalized view of usage details when available.
|
||||
///
|
||||
/// This keeps the public `Usage` fields intact and derives a consistent input/output breakdown
|
||||
/// across providers (e.g. `OpenAI` chat vs. responses). Missing data is left as `None`.
|
||||
pub fn normalized(&self) -> NormalizedUsage {
|
||||
let details = self.details.as_ref().map(|details| {
|
||||
let input = NormalizedInputUsageDetails {
|
||||
cached_tokens: details
|
||||
.input_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|input| input.cached_tokens)
|
||||
.or_else(|| {
|
||||
details
|
||||
.prompt_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|prompt| prompt.cached_tokens)
|
||||
}),
|
||||
audio_tokens: details
|
||||
.prompt_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|prompt| prompt.audio_tokens),
|
||||
};
|
||||
let output = NormalizedOutputUsageDetails {
|
||||
reasoning_tokens: details
|
||||
.output_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|output| output.reasoning_tokens)
|
||||
.or_else(|| {
|
||||
details
|
||||
.completion_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|completion| completion.reasoning_tokens)
|
||||
}),
|
||||
audio_tokens: details
|
||||
.completion_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|completion| completion.audio_tokens),
|
||||
accepted_prediction_tokens: details
|
||||
.completion_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|completion| completion.accepted_prediction_tokens),
|
||||
rejected_prediction_tokens: details
|
||||
.completion_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|completion| completion.rejected_prediction_tokens),
|
||||
};
|
||||
|
||||
if input.is_empty() && output.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(NormalizedUsageDetails { input, output })
|
||||
}
|
||||
});
|
||||
|
||||
NormalizedUsage {
|
||||
prompt_tokens: self.prompt_tokens,
|
||||
completion_tokens: self.completion_tokens,
|
||||
total_tokens: self.total_tokens,
|
||||
details: details.flatten(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider-specific usage breakdowns for a response.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct UsageDetails {
|
||||
/// Chat-completions style prompt token details.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_tokens_details: Option<PromptTokensDetails>,
|
||||
/// Chat-completions style completion token details.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completion_tokens_details: Option<CompletionTokensDetails>,
|
||||
/// Responses-style input token details.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub input_tokens_details: Option<InputTokenDetails>,
|
||||
/// Responses-style output token details.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_tokens_details: Option<OutputTokenDetails>,
|
||||
}
|
||||
|
||||
/// Normalized usage totals with optional normalized details.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NormalizedUsage {
|
||||
/// Tokens used in the prompt or input.
|
||||
pub prompt_tokens: u32,
|
||||
/// Tokens generated in the completion or output.
|
||||
pub completion_tokens: u32,
|
||||
/// Total tokens used for the request.
|
||||
pub total_tokens: u32,
|
||||
/// Normalized input/output breakdown, when available.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub details: Option<NormalizedUsageDetails>,
|
||||
}
|
||||
|
||||
/// Normalized input/output usage breakdown.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NormalizedUsageDetails {
|
||||
/// Normalized input usage details.
|
||||
pub input: NormalizedInputUsageDetails,
|
||||
/// Normalized output usage details.
|
||||
pub output: NormalizedOutputUsageDetails,
|
||||
}
|
||||
|
||||
/// Normalized input usage details.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NormalizedInputUsageDetails {
|
||||
/// Tokens retrieved from cache, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cached_tokens: Option<u32>,
|
||||
/// Audio tokens in the input, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub audio_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
impl NormalizedInputUsageDetails {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.cached_tokens.is_none() && self.audio_tokens.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalized output usage details.
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct NormalizedOutputUsageDetails {
|
||||
/// Tokens used for reasoning, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_tokens: Option<u32>,
|
||||
/// Audio tokens in the output, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub audio_tokens: Option<u32>,
|
||||
/// Accepted prediction tokens, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub accepted_prediction_tokens: Option<u32>,
|
||||
/// Rejected prediction tokens, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rejected_prediction_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
impl NormalizedOutputUsageDetails {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.reasoning_tokens.is_none()
|
||||
&& self.audio_tokens.is_none()
|
||||
&& self.accepted_prediction_tokens.is_none()
|
||||
&& self.rejected_prediction_tokens.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI-style prompt token details (chat completions).
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PromptTokensDetails {
|
||||
/// Audio input tokens present in the prompt.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub audio_tokens: Option<u32>,
|
||||
/// Cached tokens present in the prompt.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cached_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
impl PromptTokensDetails {
|
||||
/// Returns true when no prompt token detail values are set.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.audio_tokens.is_none() && self.cached_tokens.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI-style completion token details (chat completions).
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct CompletionTokensDetails {
|
||||
/// Tokens accepted from predicted output, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub accepted_prediction_tokens: Option<u32>,
|
||||
/// Audio tokens generated by the model, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub audio_tokens: Option<u32>,
|
||||
/// Tokens generated by the model for reasoning, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_tokens: Option<u32>,
|
||||
/// Tokens rejected from predicted output, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rejected_prediction_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
impl CompletionTokensDetails {
|
||||
/// Returns true when no completion token detail values are set.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.accepted_prediction_tokens.is_none()
|
||||
&& self.audio_tokens.is_none()
|
||||
&& self.reasoning_tokens.is_none()
|
||||
&& self.rejected_prediction_tokens.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI-style input token details (Responses API).
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct InputTokenDetails {
|
||||
/// Tokens retrieved from cache, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cached_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
/// OpenAI-style output token details (Responses API).
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct OutputTokenDetails {
|
||||
/// Tokens used for reasoning, when provided.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "openai")]
|
||||
mod openai_usage {
|
||||
use super::{
|
||||
CompletionTokensDetails, InputTokenDetails, OutputTokenDetails, PromptTokensDetails, Usage,
|
||||
UsageDetails,
|
||||
};
|
||||
use async_openai::types::{
|
||||
chat::CompletionUsage, embeddings::EmbeddingUsage, responses::ResponseUsage,
|
||||
};
|
||||
|
||||
impl From<&CompletionUsage> for Usage {
|
||||
fn from(usage: &CompletionUsage) -> Self {
|
||||
let prompt_details = usage.prompt_tokens_details.as_ref().and_then(|details| {
|
||||
let details = PromptTokensDetails {
|
||||
audio_tokens: details.audio_tokens,
|
||||
cached_tokens: details.cached_tokens,
|
||||
};
|
||||
if details.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(details)
|
||||
}
|
||||
});
|
||||
let completion_details = usage
|
||||
.completion_tokens_details
|
||||
.as_ref()
|
||||
.and_then(|details| {
|
||||
let details = CompletionTokensDetails {
|
||||
accepted_prediction_tokens: details.accepted_prediction_tokens,
|
||||
audio_tokens: details.audio_tokens,
|
||||
reasoning_tokens: details.reasoning_tokens,
|
||||
rejected_prediction_tokens: details.rejected_prediction_tokens,
|
||||
};
|
||||
if details.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(details)
|
||||
}
|
||||
});
|
||||
let details = if prompt_details.is_some() || completion_details.is_some() {
|
||||
Some(UsageDetails {
|
||||
prompt_tokens_details: prompt_details,
|
||||
completion_tokens_details: completion_details,
|
||||
input_tokens_details: None,
|
||||
output_tokens_details: None,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Usage {
|
||||
prompt_tokens: usage.prompt_tokens,
|
||||
completion_tokens: usage.completion_tokens,
|
||||
total_tokens: usage.total_tokens,
|
||||
details,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&ResponseUsage> for Usage {
|
||||
fn from(usage: &ResponseUsage) -> Self {
|
||||
Usage {
|
||||
prompt_tokens: usage.input_tokens,
|
||||
completion_tokens: usage.output_tokens,
|
||||
total_tokens: usage.total_tokens,
|
||||
details: Some(UsageDetails {
|
||||
prompt_tokens_details: None,
|
||||
completion_tokens_details: None,
|
||||
input_tokens_details: Some(InputTokenDetails {
|
||||
cached_tokens: Some(usage.input_tokens_details.cached_tokens),
|
||||
}),
|
||||
output_tokens_details: Some(OutputTokenDetails {
|
||||
reasoning_tokens: Some(usage.output_tokens_details.reasoning_tokens),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&EmbeddingUsage> for Usage {
|
||||
fn from(usage: &EmbeddingUsage) -> Self {
|
||||
Usage {
|
||||
prompt_tokens: usage.prompt_tokens,
|
||||
completion_tokens: 0,
|
||||
total_tokens: usage.total_tokens,
|
||||
details: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Builder, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ChatCompletionResponseDelta {
|
||||
#[builder(default)]
|
||||
pub message_chunk: Option<String>,
|
||||
|
||||
#[builder(default)]
|
||||
pub tool_calls_chunk: Option<HashMap<usize, ToolCallAccum>>,
|
||||
}
|
||||
|
||||
// Accumulator for streamed tool calls
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ToolCallAccum {
|
||||
pub id: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub arguments: Option<String>,
|
||||
}
|
||||
|
||||
impl ChatCompletionResponse {
|
||||
pub fn builder() -> ChatCompletionResponseBuilder {
|
||||
ChatCompletionResponseBuilder::default()
|
||||
}
|
||||
|
||||
pub fn message(&self) -> Option<&str> {
|
||||
self.message.as_deref()
|
||||
}
|
||||
|
||||
pub fn tool_calls(&self) -> Option<&[ToolCall]> {
|
||||
self.tool_calls.as_deref()
|
||||
}
|
||||
|
||||
/// Adds a streaming chunk to the message and also the delta
|
||||
pub fn append_message_delta(&mut self, message_delta: Option<&str>) -> &mut Self {
|
||||
// let message: Option<String> = message;
|
||||
let Some(message_delta) = message_delta else {
|
||||
return self;
|
||||
};
|
||||
|
||||
if let Some(delta) = &mut self.delta {
|
||||
delta.message_chunk = Some(message_delta.to_string());
|
||||
} else {
|
||||
self.delta = Some(ChatCompletionResponseDelta {
|
||||
message_chunk: Some(message_delta.to_string()),
|
||||
tool_calls_chunk: None,
|
||||
});
|
||||
}
|
||||
|
||||
self.message
|
||||
.as_mut()
|
||||
.map(|m| {
|
||||
m.push_str(message_delta);
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
self.message = Some(message_delta.to_string());
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a streaming chunk to the tool calls, if it can be build, the tool call will be build,
|
||||
/// otherwise it will remain in the delta and retried on the next call
|
||||
pub fn append_tool_call_delta(
|
||||
&mut self,
|
||||
index: usize,
|
||||
id: Option<&str>,
|
||||
name: Option<&str>,
|
||||
arguments: Option<&str>,
|
||||
) -> &mut Self {
|
||||
if let Some(delta) = &mut self.delta {
|
||||
let map = delta.tool_calls_chunk.get_or_insert_with(HashMap::new);
|
||||
map.entry(index)
|
||||
.and_modify(|v| {
|
||||
if v.id.is_none() {
|
||||
v.id = id.map(Into::into);
|
||||
}
|
||||
if v.name.is_none() {
|
||||
v.name = name.map(Into::into);
|
||||
}
|
||||
if let Some(v) = v.arguments.as_mut() {
|
||||
if let Some(arguments) = arguments {
|
||||
v.push_str(arguments);
|
||||
}
|
||||
} else {
|
||||
v.arguments = arguments.map(Into::into);
|
||||
}
|
||||
})
|
||||
.or_insert(ToolCallAccum {
|
||||
id: id.map(Into::into),
|
||||
name: name.map(Into::into),
|
||||
arguments: arguments.map(Into::into),
|
||||
});
|
||||
} else {
|
||||
self.delta = Some(ChatCompletionResponseDelta {
|
||||
message_chunk: None,
|
||||
tool_calls_chunk: Some(HashMap::from([(
|
||||
index,
|
||||
ToolCallAccum {
|
||||
id: id.map(Into::into),
|
||||
name: name.map(Into::into),
|
||||
arguments: arguments.map(Into::into),
|
||||
},
|
||||
)])),
|
||||
});
|
||||
}
|
||||
|
||||
// Now let's try to rebuild _every_ tool call and overwrite
|
||||
// Performance wise very meh but it works, in reality it's only a couple of tool calls most
|
||||
self.finalize_tools_from_stream();
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
pub fn append_usage_delta(
|
||||
&mut self,
|
||||
prompt_tokens: u32,
|
||||
completion_tokens: u32,
|
||||
total_tokens: u32,
|
||||
) -> &mut Self {
|
||||
debug_assert!(prompt_tokens + completion_tokens == total_tokens);
|
||||
|
||||
if let Some(usage) = &mut self.usage {
|
||||
usage.prompt_tokens += prompt_tokens;
|
||||
usage.completion_tokens += completion_tokens;
|
||||
usage.total_tokens += total_tokens;
|
||||
} else {
|
||||
self.usage = Some(Usage {
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
total_tokens,
|
||||
details: None,
|
||||
});
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn finalize_tools_from_stream(&mut self) {
|
||||
if let Some(values) = self
|
||||
.delta
|
||||
.as_ref()
|
||||
.and_then(|d| d.tool_calls_chunk.as_ref().map(|t| t.values()))
|
||||
{
|
||||
let maybe_tool_calls = values
|
||||
.filter_map(|maybe_tool_call| {
|
||||
ToolCallBuilder::default()
|
||||
.maybe_id(maybe_tool_call.id.clone())
|
||||
.maybe_name(maybe_tool_call.name.clone())
|
||||
.maybe_args(maybe_tool_call.arguments.clone())
|
||||
.build()
|
||||
.ok()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !maybe_tool_calls.is_empty() {
|
||||
self.tool_calls = Some(maybe_tool_calls);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatCompletionResponseBuilder {
|
||||
pub fn maybe_message<T: Into<Option<String>>>(&mut self, message: T) -> &mut Self {
|
||||
self.message = Some(message.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn maybe_tool_calls<T: Into<Option<Vec<ToolCall>>>>(&mut self, tool_calls: T) -> &mut Self {
|
||||
self.tool_calls = Some(tool_calls.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::tools::{ToolCall, ToolOutput};
|
||||
|
||||
/// Reasoning items returned by chat providers that expose chain-of-thought metadata.
|
||||
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, Default)]
|
||||
pub struct ReasoningItem {
|
||||
/// Unique identifier for this reasoning item
|
||||
pub id: String,
|
||||
/// Reasoning summary content
|
||||
pub summary: Vec<String>,
|
||||
/// Reasoning text content
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub encrypted_content: Option<String>,
|
||||
/// The status of the item. One of `in_progress`, `completed`, or `incomplete`.
|
||||
/// Populated when items are returned via API.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub status: Option<ReasoningStatus>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ReasoningStatus {
|
||||
InProgress,
|
||||
Completed,
|
||||
Incomplete,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ChatMessageContentSource {
|
||||
Url {
|
||||
url: String,
|
||||
},
|
||||
Bytes {
|
||||
data: Vec<u8>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
media_type: Option<String>,
|
||||
},
|
||||
S3 {
|
||||
uri: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
bucket_owner: Option<String>,
|
||||
},
|
||||
FileId {
|
||||
file_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl ChatMessageContentSource {
|
||||
pub fn url(url: impl Into<String>) -> Self {
|
||||
Self::Url { url: url.into() }
|
||||
}
|
||||
|
||||
pub fn bytes<M>(data: impl Into<Vec<u8>>, media_type: Option<M>) -> Self
|
||||
where
|
||||
M: Into<String>,
|
||||
{
|
||||
Self::Bytes {
|
||||
data: data.into(),
|
||||
media_type: media_type.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn s3<O>(uri: impl Into<String>, bucket_owner: Option<O>) -> Self
|
||||
where
|
||||
O: Into<String>,
|
||||
{
|
||||
Self::S3 {
|
||||
uri: uri.into(),
|
||||
bucket_owner: bucket_owner.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_id(file_id: impl Into<String>) -> Self {
|
||||
Self::FileId {
|
||||
file_id: file_id.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ChatMessageContentSource {
|
||||
fn from(value: String) -> Self {
|
||||
Self::Url { url: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for ChatMessageContentSource {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::Url {
|
||||
url: value.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for ChatMessageContentSource {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
Self::Bytes {
|
||||
data: value,
|
||||
media_type: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&[u8]> for ChatMessageContentSource {
|
||||
fn from(value: &[u8]) -> Self {
|
||||
Self::Bytes {
|
||||
data: value.to_vec(),
|
||||
media_type: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ChatMessageContentSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ChatMessageContentSource::Url { url } => f
|
||||
.debug_struct("Url")
|
||||
.field("url", &truncate_data_url(url))
|
||||
.finish(),
|
||||
ChatMessageContentSource::Bytes { data, media_type } => f
|
||||
.debug_struct("Bytes")
|
||||
.field("len", &data.len())
|
||||
.field("media_type", media_type)
|
||||
.finish(),
|
||||
ChatMessageContentSource::S3 { uri, bucket_owner } => f
|
||||
.debug_struct("S3")
|
||||
.field("uri", uri)
|
||||
.field("bucket_owner", bucket_owner)
|
||||
.finish(),
|
||||
ChatMessageContentSource::FileId { file_id } => {
|
||||
f.debug_struct("FileId").field("file_id", file_id).finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ChatMessageContentPart {
|
||||
Text {
|
||||
text: String,
|
||||
},
|
||||
Image {
|
||||
source: ChatMessageContentSource,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format: Option<String>,
|
||||
},
|
||||
Document {
|
||||
source: ChatMessageContentSource,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
name: Option<String>,
|
||||
},
|
||||
Audio {
|
||||
source: ChatMessageContentSource,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format: Option<String>,
|
||||
},
|
||||
Video {
|
||||
source: ChatMessageContentSource,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ChatMessageContentPart {
|
||||
pub fn text(text: impl Into<String>) -> Self {
|
||||
Self::Text { text: text.into() }
|
||||
}
|
||||
|
||||
pub fn image(source: impl Into<ChatMessageContentSource>) -> Self {
|
||||
Self::Image {
|
||||
source: source.into(),
|
||||
format: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn image_with_format(
|
||||
source: impl Into<ChatMessageContentSource>,
|
||||
format: impl Into<String>,
|
||||
) -> Self {
|
||||
Self::Image {
|
||||
source: source.into(),
|
||||
format: Some(format.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn document(source: impl Into<ChatMessageContentSource>) -> Self {
|
||||
Self::Document {
|
||||
source: source.into(),
|
||||
format: None,
|
||||
name: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn document_with_name(
|
||||
source: impl Into<ChatMessageContentSource>,
|
||||
name: impl Into<String>,
|
||||
) -> Self {
|
||||
Self::Document {
|
||||
source: source.into(),
|
||||
format: None,
|
||||
name: Some(name.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn audio(source: impl Into<ChatMessageContentSource>) -> Self {
|
||||
Self::Audio {
|
||||
source: source.into(),
|
||||
format: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn video(source: impl Into<ChatMessageContentSource>) -> Self {
|
||||
Self::Video {
|
||||
source: source.into(),
|
||||
format: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ChatMessageContentPart {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ChatMessageContentPart::Text { text } => {
|
||||
f.debug_struct("Text").field("text", text).finish()
|
||||
}
|
||||
ChatMessageContentPart::Image { source, format } => f
|
||||
.debug_struct("Image")
|
||||
.field("source", source)
|
||||
.field("format", format)
|
||||
.finish(),
|
||||
ChatMessageContentPart::Document {
|
||||
source,
|
||||
format,
|
||||
name,
|
||||
} => f
|
||||
.debug_struct("Document")
|
||||
.field("source", source)
|
||||
.field("format", format)
|
||||
.field("name", name)
|
||||
.finish(),
|
||||
ChatMessageContentPart::Audio { source, format } => f
|
||||
.debug_struct("Audio")
|
||||
.field("source", source)
|
||||
.field("format", format)
|
||||
.finish(),
|
||||
ChatMessageContentPart::Video { source, format } => f
|
||||
.debug_struct("Video")
|
||||
.field("source", source)
|
||||
.field("format", format)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, strum_macros::EnumIs, PartialEq, Debug, Serialize, Deserialize)]
|
||||
pub enum ChatMessage {
|
||||
System(String),
|
||||
User(String),
|
||||
UserWithParts(Vec<ChatMessageContentPart>),
|
||||
Assistant(Option<String>, Option<Vec<ToolCall>>),
|
||||
ToolOutput(ToolCall, ToolOutput),
|
||||
Reasoning(ReasoningItem),
|
||||
|
||||
// A summary of the chat. If encountered all previous messages are ignored, except the system
|
||||
// prompt
|
||||
Summary(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ChatMessage {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::System(s) => write!(f, "System: \"{s}\""),
|
||||
Self::User(s) => write!(f, "User: \"{s}\""),
|
||||
Self::UserWithParts(parts) => {
|
||||
let (text, attachments) = summarize_user_parts(parts);
|
||||
if attachments == 0 {
|
||||
write!(f, "User: \"{text}\"")
|
||||
} else {
|
||||
write!(f, "User: \"{text}\", attachments: {attachments}")
|
||||
}
|
||||
}
|
||||
Self::Assistant(content, tool_calls) => write!(
|
||||
f,
|
||||
"Assistant: \"{}\", tools: {}",
|
||||
content.as_deref().unwrap_or("None"),
|
||||
tool_calls.as_deref().map_or("None".to_string(), |tc| {
|
||||
tc.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
})
|
||||
),
|
||||
Self::ToolOutput(tc, to) => write!(f, "ToolOutput: \"{tc}\": \"{to}\""),
|
||||
Self::Reasoning(item) => write!(
|
||||
f,
|
||||
"Reasoning: \"{}\", encrypted: {}",
|
||||
item.summary.join("\n"),
|
||||
item.encrypted_content.is_some()
|
||||
),
|
||||
Self::Summary(s) => write!(f, "Summary: \"{s}\""),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatMessage {
|
||||
pub fn new_system(message: impl Into<String>) -> Self {
|
||||
Self::System(message.into())
|
||||
}
|
||||
|
||||
pub fn new_user(message: impl Into<String>) -> Self {
|
||||
Self::User(message.into())
|
||||
}
|
||||
|
||||
pub fn new_user_with_parts(parts: impl Into<Vec<ChatMessageContentPart>>) -> Self {
|
||||
Self::UserWithParts(parts.into())
|
||||
}
|
||||
|
||||
pub fn new_assistant(
|
||||
message: Option<impl Into<String>>,
|
||||
tool_calls: Option<Vec<ToolCall>>,
|
||||
) -> Self {
|
||||
Self::Assistant(message.map(Into::into), tool_calls)
|
||||
}
|
||||
|
||||
pub fn new_tool_output(tool_call: impl Into<ToolCall>, output: impl Into<ToolOutput>) -> Self {
|
||||
Self::ToolOutput(tool_call.into(), output.into())
|
||||
}
|
||||
|
||||
pub fn new_reasoning(message: ReasoningItem) -> Self {
|
||||
Self::Reasoning(message)
|
||||
}
|
||||
|
||||
pub fn new_summary(message: impl Into<String>) -> Self {
|
||||
Self::Summary(message.into())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn to_owned(&self) -> Self {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the content of the message as a string slice.
|
||||
///
|
||||
/// Note that this omits the tool calls from the assistant message.
|
||||
///
|
||||
/// If used for estimating tokens, consider this a very rought estimate
|
||||
impl AsRef<str> for ChatMessage {
|
||||
fn as_ref(&self) -> &str {
|
||||
match self {
|
||||
Self::System(s) | Self::User(s) | Self::Summary(s) => s,
|
||||
Self::UserWithParts(parts) => match parts.as_slice() {
|
||||
[ChatMessageContentPart::Text { text }] => text.as_ref(),
|
||||
_ => "",
|
||||
},
|
||||
Self::Assistant(message, _) => message.as_deref().unwrap_or(""),
|
||||
Self::ToolOutput(_, output) => output.content().unwrap_or(""),
|
||||
Self::Reasoning(_) => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn summarize_user_parts(parts: &[ChatMessageContentPart]) -> (String, usize) {
|
||||
let mut text_parts = Vec::new();
|
||||
let mut attachments = 0;
|
||||
for part in parts {
|
||||
match part {
|
||||
ChatMessageContentPart::Text { text } => text_parts.push(text.as_str()),
|
||||
ChatMessageContentPart::Image { .. }
|
||||
| ChatMessageContentPart::Document { .. }
|
||||
| ChatMessageContentPart::Audio { .. }
|
||||
| ChatMessageContentPart::Video { .. } => attachments += 1,
|
||||
}
|
||||
}
|
||||
(text_parts.join(" "), attachments)
|
||||
}
|
||||
|
||||
fn truncate_data_url(url: &str) -> Cow<'_, str> {
|
||||
const MAX_DATA_PREVIEW: usize = 32;
|
||||
|
||||
if !url.starts_with("data:") {
|
||||
return Cow::Borrowed(url);
|
||||
}
|
||||
|
||||
let Some((prefix, data)) = url.split_once(',') else {
|
||||
return Cow::Borrowed(url);
|
||||
};
|
||||
|
||||
if data.len() <= MAX_DATA_PREVIEW {
|
||||
return Cow::Borrowed(url);
|
||||
}
|
||||
|
||||
let preview = &data[..MAX_DATA_PREVIEW];
|
||||
let truncated = data.len() - MAX_DATA_PREVIEW;
|
||||
|
||||
Cow::Owned(format!(
|
||||
"{prefix},{preview}...[truncated {truncated} chars]"
|
||||
))
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user