Metadata-Version: 2.4
Name: st-agent-chat
Version: 0.2.0
Summary: Drop-in agentic AI chat component for Streamlit — your AI agent can run shell commands, read/write files, execute Python, and browse the web.
Author: RhythrosaLabs
License: MIT
Project-URL: Homepage, https://github.com/RhythrosaLabs/st-agent-chat
Project-URL: Repository, https://github.com/RhythrosaLabs/st-agent-chat
Project-URL: Issues, https://github.com/RhythrosaLabs/st-agent-chat/issues
Keywords: streamlit,component,agent,chat,ai,llm,tools,agentic
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: User Interfaces
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: streamlit>=1.28.0
Requires-Dist: anthropic>=0.39.0
Requires-Dist: openai>=1.50.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: requests>=2.28.0
Dynamic: license-file

# st-agent-chat

**A drop-in agentic AI chat component for Streamlit.**

Add a fully functional AI agent to any Streamlit app in one line of code. The component is completely self-contained — no sidebar, no page takeover. Drop it into any column, tab, or container. The agent can run shell commands, read and write files, execute Python, and browse the web.

[![PyPI](https://img.shields.io/pypi/v/st-agent-chat?color=blue)](https://pypi.org/project/st-agent-chat/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://python.org)
[![Streamlit](https://img.shields.io/badge/streamlit-%E2%89%A51.28-red?logo=streamlit)](https://streamlit.io)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

![screenshot](screenshot.png)

---

## Install

```bash
pip install st-agent-chat
```

## Quick Start

```python
import streamlit as st
from st_agent_chat import agent_chat

st.set_page_config(page_title="My AI App", layout="wide")
agent_chat(workspace=".")
```

That's it. You get a compact header bar, a ⚙️ Settings popover for provider/model selection, a message input, and an AI agent that can execute tools on your machine. No sidebar — everything stays inline.

## Set Up an API Key

The component needs at least one LLM provider key. Set it in your environment or a `.env` file:

```bash
# Pick one (or several — the agent will use the first available)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
REPLICATE_API_TOKEN=r8_...
OPENROUTER_API_KEY=sk-or-...
```

Provider fallback order: Anthropic → OpenAI → Replicate → OpenRouter.

---

## What the Agent Can Do

The agent has **7 real executable tools**, not stubs:

| Tool | What it does |
|------|-------------|
| **bash** | Run any shell command (120s timeout) |
| **file_read** | Read file contents, optionally by line range |
| **file_write** | Create or overwrite files (auto-creates directories) |
| **file_edit** | Search-and-replace edit (exact match, must be unique) |
| **python_exec** | Execute Python code and return stdout/stderr |
| **web_fetch** | Fetch a URL; extracts readable text from HTML pages |
| **list_directory** | List files and folders in a directory |

All file operations are **sandboxed** to the workspace root you specify. The agent cannot read or write outside that directory.

The agent chains tools automatically — ask it to "find all TODO comments and create a summary file" and it will `bash` grep, `file_read` the matches, and `file_write` the summary, all in one turn.

## Supported LLM Providers

| Provider | Models | Env Variable |
|----------|--------|-------------|
| **Anthropic** | claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5 | `ANTHROPIC_API_KEY` |
| **OpenAI** | gpt-5.4, gpt-5.4-mini, gpt-5.4-nano | `OPENAI_API_KEY` |
| **Replicate** | llama-4-maverick, llama-4-scout, llama-3.3-70b | `REPLICATE_API_TOKEN` |
| **OpenRouter** | qwen-3.6-plus (free), nemotron-3-super (free), gemma-4-26b | `OPENROUTER_API_KEY` |

Switch providers live from the sidebar — no restart needed.

---

## API Reference

### `agent_chat()`

The main component. Renders a full chat UI with tool execution.

```python
from st_agent_chat import agent_chat

agent_chat(
    workspace="/path/to/project",   # Root for file operations (default: ".")
    provider="anthropic",           # LLM provider (default: auto-detect)
    model="claude-sonnet-4-6",       # Model ID (default: provider's default)
    api_key="",                     # API key (default: read from env)
    max_turns=25,                   # Max tool-call rounds per message
    max_tokens=8192,                # Max tokens per LLM response
    temperature=0.7,                # LLM temperature
    system_prompt="",               # Custom system prompt (default: built-in)
    show_config=True,               # Show inline ⚙️ Settings popover
    show_cost=True,                 # Show token usage per response
    key="my_chat",                  # Streamlit widget key
)
```

### `AgentEngine`

The engine behind the chat UI. Use it directly for programmatic / headless agent execution:

```python
from st_agent_chat import AgentEngine

engine = AgentEngine(workspace=".", provider="anthropic")

# Single call — runs the full tool loop and returns the final answer
result = engine.submit("List all Python files and count their lines of code")
print(result.output)
print(f"Tokens: {result.usage.input_tokens} in / {result.usage.output_tokens} out")
print(f"Tool calls made: {len(result.tool_calls)}")
```

The engine maintains conversation history across calls, so follow-up messages have context.

### `execute_tool()`

Run a single tool directly, outside the agent loop:

```python
from st_agent_chat import execute_tool

# Shell command
result = execute_tool("bash", {"command": "git log --oneline -5"})
print(result.output)

# Read a file
result = execute_tool("file_read", {"path": "README.md"})
print(result.output)

# Run Python
result = execute_tool("python_exec", {"code": "import sys; print(sys.version)"})
print(result.output)
```

### `TOOL_SCHEMAS`

The raw tool definitions (Anthropic format). Useful if you're building your own LLM integration:

```python
from st_agent_chat import TOOL_SCHEMAS
for tool in TOOL_SCHEMAS:
    print(f"{tool['name']}: {tool['description'][:60]}...")
```

---

## Examples

### Minimal chat app

```python
import streamlit as st
from st_agent_chat import agent_chat

st.set_page_config(layout="wide")
agent_chat()
```

### Custom system prompt

```python
agent_chat(
    workspace="./my_project",
    system_prompt="You are a senior Python developer. Always write tests for code you create.",
)
```

### Headless agent in a script

```python
from st_agent_chat import AgentEngine

engine = AgentEngine(workspace=".", provider="anthropic")

# Multi-turn conversation
engine.submit("Create a file called hello.py with a Flask hello world app")
engine.submit("Now add a /health endpoint that returns JSON")
engine.submit("Write a test for both endpoints using pytest")
```

### Embed alongside other Streamlit content

```python
import streamlit as st
from st_agent_chat import agent_chat

st.set_page_config(layout="wide")

st.title("My Dashboard")
col1, col2 = st.columns([2, 1])

with col1:
    st.metric("Users", "1,234")
    st.line_chart({"data": [1, 5, 2, 6, 3, 7]})

with col2:
    st.subheader("AI Assistant")
    agent_chat(workspace=".", key="assistant")
```

The component never touches the sidebar — your app's sidebar is yours.

---

## Architecture

```
st_agent_chat/
├── component.py    # Streamlit UI — chat interface, CSS, sidebar
├── engine.py       # AgentEngine — agentic tool loop (submit / stream_submit)
├── llm.py          # Multi-provider LLM client with automatic fallback
├── tools.py        # 7 executable tools with workspace sandboxing
└── __init__.py     # Public API exports
```

The component is self-contained with no external service dependencies beyond the LLM API. All tool execution happens locally in-process.

## Security

- **Workspace sandboxing**: All file operations are confined to the workspace root. Path traversal attempts are blocked.
- **Shell timeout**: `bash` commands have a 120-second timeout.
- **No credential leakage**: API keys are read from environment variables, never stored in state.
- **User-initiated only**: The agent only acts on explicit user messages — no background execution.

> **Note**: This component executes real commands on your machine. Use it in trusted environments. Do not deploy with unrestricted shell access to production servers.

## Development

```bash
git clone https://github.com/RhythrosaLabs/st-agent-chat.git
cd st-agent-chat
pip install -e ".[dev]"
streamlit run demo.py
```

## License

MIT — see [LICENSE](LICENSE).

## License

MIT
