# Your First Agent

This guide walks you through creating and running a minimal custom agent using the `agenticstar-platform` SDK. The SDK provides infrastructure (DB, events, storage, etc.), while you freely design the agent logic.

## Prerequisites

- Python 3.12 or higher
- pip or uv
- PostgreSQL database (local or Azure Database for PostgreSQL)
- Azure OpenAI API key (for LLM calls)

## Step 1: Install the SDK

**All Modules**

```bash
pip install agenticstar-platform[all]==0.5.40
```

**Minimal**

```bash
# Events + DB only (minimal configuration)
pip install agenticstar-platform[db]==0.5.40
```

**Using uv**

```bash
uv pip install agenticstar-platform[all]==0.5.40
```

## Step 2: Create the Configuration File

Create a `config.toml` file. Each SDK module reads its configuration from this file.

```toml
[database]
host = "localhost"
port = 5432
database = "agenticstar"
username = "agent_user"
password = "your_password"
pool_min_size = 2
pool_max_size = 10
# Set to true only when using Azure AD auth, and configure [database.azure_ad]
use_azure_ad = false

[events]
enable_db_handler = true
enable_webhook_handler = false
```

`PostgreSQLConfig.from_toml()` reads the `[database]` section by default. The field names are `username` / `pool_min_size` / `pool_max_size`. To use Azure AD auth, set `use_azure_ad = true` directly under `[database]` and provide `tenant_id` / `client_id` / `client_secret` in `[database.azure_ad]`.

## Step 3: Implement the Agent

Create `my_agent.py`. This example implements a simple agent that retrieves job information using the SDK's **DB module** and streams progress via the **Events module**.

```python
import asyncio
from openai import AsyncAzureOpenAI

from agenticstar_platform.db import PostgreSQLManager, PostgreSQLConfig, DataAccess
from agenticstar_platform.db.execution_access import ExecutionAccess
from agenticstar_platform.events import EventEmitter, EventType

# --- Configuration ---
db_config = PostgreSQLConfig.from_toml("config.toml")
llm_client = AsyncAzureOpenAI(
    azure_endpoint="https://your-endpoint.openai.azure.com/",
    api_version="2024-12-01-preview",
    api_key="your-api-key",
)

async def run_agent(execution_id: str, user_message: str):
    """Minimal agent execution flow"""

    # 1. Initialize DB connection
    db_manager = PostgreSQLManager(db_config)
    da = DataAccess(db_manager)
    await da.initialize()

    execution_access = ExecutionAccess(da)

    # 2. Initialize EventEmitter
    emitter = EventEmitter(execution_id=execution_id)

    # 3. Emit execution start event
    await emitter.emit_event(
        event_type=EventType.PHASE_START,
        message="Processing request...",
        metadata={"phase": "processing"},
    )

    # 4. Retrieve past messages
    history = await execution_access.get_messages(execution_id=execution_id)

    # 5. Call LLM (agent logic is freely designed)
    messages = [{"role": "system", "content": "You are a helpful assistant."}]
    if history:
        for h in history:
            messages.append({"role": h["role"], "content": h["content"]})
    messages.append({"role": "user", "content": user_message})

    response = await llm_client.chat.completions.create(
        model="gpt-4.1",
        messages=messages,
    )
    answer = response.choices[0].message.content

    # 6. Emit completion event
    await emitter.emit_event(
        event_type=EventType.COMPLETION_SUCCESS,
        message=answer,
    )

    # 7. Cleanup
    await emitter.cleanup()
    await da.close()

    return answer

if __name__ == "__main__":
    result = asyncio.run(run_agent("exec-001", "Hello!"))
    print(result)
```

## Step 4: Verify

```bash
python my_agent.py
```

If everything works correctly, the LLM response will be printed to the console.

## Run Marketplace-Compatible (runner, SDK 0.5.30+)

An agent function that works locally can run under the marketplace-compatible terminal lifecycle just by passing it to `run_marketplace_agent`. The runner takes care of receiving and validating identity (`EXECUTION_ID` etc.), fetching the input message, persisting the result to the DB, webhook notification, the terminal event (**exactly once, no matter what happens**), and cleanup — so the main boilerplate you wrote in Step 3 above is no longer needed.

```python
from agenticstar_platform import run_marketplace_agent


async def my_agent(emitter, message: str) -> str:
    """Your agent logic. Any framework (LangChain / OpenAI Agents SDK / custom)."""
    return message.upper()  # replace with your actual logic


if __name__ == "__main__":
    run_marketplace_agent(my_agent)
```

```bash
pip install 'agenticstar-platform[runner]==0.5.40'
python marketplace_agent.py
```

On the platform, `EXECUTION_ID` / `CONVERSATION_ID` / `USER_ID` / `MESSAGE_ID` are injected by the marketplace executor at pod startup. Configure the DB connection (`DB_HOST` etc., following the `PostgreSQLConfig.from_env()` contract) and `WEBHOOK_URL` as agent environment variables at registration time. If a required variable is missing, the runner stops with `MarketplaceRunnerConfigError` without invoking your agent.

- The agent function's return value is persisted and notified as `completion_success`
- Exceptions from the agent function converge to `completion_failure` (traceback goes to logs only)
- Agent functions that emit their own terminal event (like the local sample) do not cause duplicates

## Local Integration Lab (SDK 0.5.35+)

Experience the full integration journey across DB / RAG / storage (`ingest → retrieve → artifact/result persist → terminal outcome`) with a single command — no external service contracts, no cloud credentials, no `.env` editing. All you need is Docker (with compose v2) and Python 3.11+.

```bash
pip install 'agenticstar-platform[lab]==0.5.40'
python -m agenticstar_platform.lab            # run the journey (one command)
python -m agenticstar_platform.lab doctor     # read-only diagnostics
python -m agenticstar_platform.lab --reset    # tear down (lists targets, confirms / --yes)
```

- Starts PostgreSQL / Qdrant / S3-compatible storage (MinIO) via a version-pinned Docker Compose manifest (bound to 127.0.0.1 only)
- Embeddings use a deterministic offline implementation — no cloud endpoint or API key is ever used
- The only credentials involved are fixed, non-production lab values; the lab never asks for, stores, or prints production credentials
- A local copy of the artifact is written to `agenticstar-lab-artifacts/` under the current working directory
- On success it shows the retrieved document, the artifact location, and the next Marketplace runner command to try. If something fails, `doctor` classifies the cause (Docker not running / port conflict / missing extras etc.) with the next command to run

## Step 5: Add Tools (Optional)

Here is an example of adding tools (function calling) to your agent. This uses the SDK's **RAG module** to search a knowledge base.

```python
from agenticstar_platform.rag import QdrantManager, QdrantConfig
from agenticstar_platform.rag import EmbeddingGenerator, EmbeddingConfig

async def search_knowledge(query: str, top_k: int = 5) -> list[dict]:
    """Search the knowledge base for documents related to the query"""

    # Initialize the embedding generator and the Qdrant manager
    # QdrantManager requires an EmbeddingGenerator (it embeds the query internally at search time)
    embed_config = EmbeddingConfig.from_toml("config.toml")
    generator = EmbeddingGenerator(embed_config)

    qdrant_config = QdrantConfig.from_toml("config.toml")  # collection_name comes from config
    qdrant = QdrantManager(qdrant_config, generator)
    await qdrant.initialize()

    # Search by query text (no query_vector needed; embedding is generated internally)
    result = await qdrant.search(query_text=query, limit=top_k)

    # The return value is a dict; hits are in result["data"]["results"]
    return [
        {"content": hit["payload"].get("content", ""), "score": hit["score"]}
        for hit in result["data"]["results"]
    ]
```

## Example Project Structure

```text
my-agent/
├── config.toml              # SDK configuration file
├── my_agent.py              # Agent main logic
├── tools/
│   ├── search_knowledge.py  # RAG search tool
│   └── file_manager.py      # Storage operations tool
├── Dockerfile               # Container build
├── requirements.txt
└── README.md
```

## Next Steps

- [Architecture Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/develop/guide/architecture.md) — SDK module structure and design philosophy
- [Deploy Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/develop/guide/deploy.md) — Docker build and platform registration
- [Events / Streaming Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/develop/guide/events-guide.md) — SSE event delivery details
- [SDK API Reference](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/develop/reference/sdk-ref.md) — Complete specifications for all modules and classes
