> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ariacompute.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# AGENT 运行时

AGENT 是咏唱引擎的 Agent 脚手架运行时，负责工具调用与规划。它自带 AGENT API（OpenAI Agents 形态）的本地服务端，用来创建智能体、管理会话，并把状态持久化到 Postgres + pgvector。

本页讲自托管的 CLI。HTTP API 见 [AGENT API 简介](/api-reference/agent/introduction)。

## 安装

从[下载页](/resources/downloads)下载你所在平台的最新发布版。

## setup 与 serve

```bash theme={null}
aria-agent setup
aria-agent setup --status

aria-agent serve --bind 127.0.0.1:8848
```

`setup` 之后，默认配置写在 `~/.ariacompute/agent.yml`。也可以用 `--config` 指向仓库里的示例配置。

* **数据面**（`--bind`）：`POST /v1/agents`、`POST /v1/agents/{agent_id}/sessions`、`POST /v1/agents/sessions/{session_id}/turns`
* **管理面**：健康检查、API 密钥、记忆

AGENT API 的基础 URL 默认为 `http://127.0.0.1:8848`（自托管）或云端 `https://agent.ariacompute.cn`。

<Warning>
  勿与 aria-engine / aria-router 常用端口（`8080` / `8010` / `8011` / `8899`）冲突。
</Warning>

## 概念说明

| 概念 | 含义 |
| - | - |
| 智能体 Agent | 绑定模型、指令与工具的长期实体 |
| 会话 Session | 一次交互的轨迹，持久化状态与消息 |
| 轮次 Turn | 一次模型调用 + 工具调用循环 |
| 记忆 Memory | 按主体的 `context_fragments`（pgvector） |

AGENT API 里的资源沿用 OpenAI Agents 的形态：智能体、会话、轮次、事件、记忆和子智能体。

## 快速请求

```bash theme={null}
curl -s https://agent.ariacompute.cn/v1/agents \
  -H 'content-type: application/json' \
  -H 'Authorization: ApiKey sk_aria_your_agent_api_key' \
  -d '{
    "model": "ariacompute/gemma-4-e2b-it",
    "name": "triage",
    "instructions": "你是退款客服助理。",
    "tools": []
  }'
```

## 语言绑定

AGENT API 的 SDK 覆盖 Python、Rust、Swift、Kotlin 和 TypeScript。

<CodeGroup>
  ```python Python theme={null}
  # pip install ariacompute-agent
  import asyncio
  import os

  from ariacompute_agent import Agent, ClientOptions, Runner, Session, function_tool

  # Cloud SDK — talks to the beta Agents REST API.
  client = ClientOptions(
      base_url=os.environ.get("ARIA_AGENT_BASE_URL", "https://agent.ariacompute.cn"),
      api_key=os.environ.get("AGENT_CLOUD_API_KEY"),
  )


  @function_tool
  def history_fun_fact() -> str:
      """Return a short history fact."""
      return "Sharks are older than trees."


  agent = Agent(
      name="History tutor",
      instructions="Answer history questions clearly and concisely.",
      model="gpt-4o-mini",
      tools=[history_fun_fact],
      client=client,
      # memory backend: cloud | local (aria memo) | both
      memory_backend="both",
      memo_db="~/.ariacompute/memo.db",
  )


  async def main() -> None:
      session = Session.create(agent, client)

      # 1) One-shot run.
      first = await Runner.run(agent, "When did the Roman Empire fall?", session=session)
      print(first.final_output)

      # Long-term memory: memorize persists a fact that every later turn of the
      # session can recall — Postgres + pgvector in the cloud, aria memo locally.
      session.memorize("user_name", "Ada")

      # 2) Continue the same conversation by reusing the session.
      second = await Runner.run(agent, "What is my name?", session=session)
      print(second.final_output)
      print(session.recall("user_name"))                     # -> "Ada"
      print(session.recall("user_name", backend="local"))    # aria memo copy only

      # 3) Streaming run — agent.turn.* events.
      streamed = await Runner.run_streamed(agent, "Tell me something surprising", session=session)
      async for event in streamed.events:
          if event["type"] == "agent.turn.output_text.delta":
              print(event["delta"], end="")
      print((await streamed.completed).final_output)


  asyncio.run(main())
  ```

  ```rust Rust theme={null}
  // cargo add ariacompute-agent
  use aria_agent_ffi::{
      create_agent_with, SdkAgentConfig, SdkAgentListener, SdkMemoryConfig, SdkStreamEvent,
  };

  struct Printer;

  impl SdkAgentListener for Printer {
      fn on_event(&self, event: SdkStreamEvent) {
          if let SdkStreamEvent::Token { text } = event {
              print!("{text}");
          }
      }
  }

  fn main() -> Result<(), Box<dyn std::error::Error>> {
      // Native SDK — the runtime embedded in-process (no server, no network).
      // No session argument: the runtime assigns one isolated context scope per agent.
      // memory.backend selects cloud | local (aria memo) | both; default is local.
      let agent = create_agent_with(SdkAgentConfig {
          agent_name: "History tutor".into(),
          instructions: "Answer history questions clearly and concisely.".into(),
          model: "gpt-4o-mini".into(),
          memory: SdkMemoryConfig {
              backend: "both".into(),
              local_db_path: "~/.ariacompute/memo.db".into(),
              cloud_base_url: std::env::var("ARIA_AGENT_BASE_URL")
                  .unwrap_or_else(|_| "https://agent.ariacompute.cn".into()),
              cloud_api_key: String::new(),
          },
          ..Default::default()
      })?;

      // 1) One-shot run.
      println!("{}", agent.run("When did the Roman Empire fall?".into())?);

      // Long-term memory: memorize persists a fact that later turns recall.
      let session = agent.session();
      session.memorize("user_name".into(), "Ada".into())?;

      // 2) Continue the same conversation (same agent / session scope).
      println!("{}", agent.run("What is my name?".into())?);
      println!("{:?}", session.recall("user_name".into(), None)?);                  // Some("Ada")
      println!("{:?}", session.recall("user_name".into(), Some("local".into()))?);  // aria memo only

      // 3) Streaming run — events are pushed to the listener.
      agent.run_stream("Tell me something surprising".into(), Box::new(Printer))?;
      Ok(())
  }
  ```

  ```swift Swift theme={null}
  // pod 'AriaComputeAgent'
  import AriaComputeAgent

  do {
      // Native SDK — the runtime embedded in-process (no server, no network).
      // memory.backend selects cloud | local (aria memo) | both; default is local.
      let agent = try createAgentWith(config: SdkAgentConfig(
          agentName: "History tutor",
          instructions: "Answer history questions clearly and concisely.",
          model: "gpt-4o-mini",
          sandboxProvider: "docker",
          memory: SdkMemoryConfig(
              backend: "both",
              localDbPath: "~/.ariacompute/memo.db",
              cloudBaseUrl: "https://agent.ariacompute.cn",
              cloudApiKey: ""
          )
      ))

      // 1) One-shot run.
      print(try agent.run("When did the Roman Empire fall?"))

      // Long-term memory: memorize persists a fact that later turns recall.
      let session = agent.session()
      try session.memorize(key: "user_name", value: "Ada", backend: nil)

      // 2) Continue the same conversation (same agent / session scope).
      print(try agent.run("What is my name?"))
      print(try session.recall(key: "user_name", backend: nil) ?? "")      // -> "Ada"
      print(try session.recall(key: "user_name", backend: "local") ?? "")  // aria memo only

      // 3) Streaming run — events are delivered to the listener.
      try agent.runStream("Tell me something surprising", listener: Printer())
  } catch {
      print(error)
  }
  ```

  ```kotlin Kotlin theme={null}
  // implementation("com.ariacompute:agent:+")
  import com.ariacompute.agent.uniffi.aria_agent_ffi.*

  fun main() {
      // Native SDK — the runtime embedded in-process (no server, no network).
      // memory.backend selects cloud | local (aria memo) | both; default is local.
      val agent = createAgentWith(
          SdkAgentConfig(
              agentName = "History tutor",
              instructions = "Answer history questions clearly and concisely.",
              model = "gpt-4o-mini",
              sandboxProvider = "docker",
              memory = SdkMemoryConfig(
                  backend = "both",
                  localDbPath = "~/.ariacompute/memo.db",
                  cloudBaseUrl = "https://agent.ariacompute.cn",
                  cloudApiKey = ""
              )
          )
      )

      // 1) One-shot run.
      println(agent.run("When did the Roman Empire fall?"))

      // Long-term memory: memorize persists a fact that later turns recall.
      val session = agent.session()
      session.memorize("user_name", "Ada", null)

      // 2) Continue the same conversation (same agent / session scope).
      println(agent.run("What is my name?"))
      println(session.recall("user_name", null))     // -> "Ada"
      println(session.recall("user_name", "local"))  // aria memo only

      // 3) Streaming run — events are delivered to the listener.
      agent.runStream("Tell me something surprising", Printer())
  }
  ```

  ```typescript TypeScript theme={null}
  // npm i @ariacompute/agent
  import { Agent, run, runStreamed, Session, tool } from "@ariacompute/agent";

  // Cloud SDK — talks to the beta Agents REST API.
  const client = {
    baseUrl: process.env.ARIA_AGENT_BASE_URL ?? "https://agent.ariacompute.cn",
    apiKey: process.env.AGENT_CLOUD_API_KEY,
  };

  const historyFunFact = tool({
    name: "history_fun_fact",
    description: "Return a short history fact.",
    parameters: { type: "object", properties: {} },
  });

  const agent = new Agent({
    name: "History tutor",
    instructions: "Answer history questions clearly and concisely.",
    model: "gpt-4o-mini",
    tools: [historyFunFact],
    client,
    // memory backend: cloud | local (aria memo) | both
    memory: { ...client, backend: "both", memoDb: "~/.ariacompute/memo.db" },
  });

  const session = await Session.create(agent, client);

  // 1) One-shot run.
  const first = await run(agent, "When did the Roman Empire fall?", { session });
  console.log(first.finalOutput);

  // Long-term memory: memorize persists a fact that every later turn of the
  // session can recall — Postgres + pgvector in the cloud, aria memo locally.
  await session.memorize("user_name", "Ada");

  // 2) Continue the same conversation by reusing the session.
  const second = await run(agent, "What is my name?", { session });
  console.log(second.finalOutput);
  console.log(await session.recall("user_name"));                          // -> "Ada"
  console.log(await session.recall("user_name", { backend: "local" }));    // aria memo only

  // 3) Streaming run — agent.turn.* events.
  const streamed = await runStreamed(agent, "Tell me something surprising", { session });
  for await (const event of streamed.events) {
    if (event.type === "agent.turn.output_text.delta") process.stdout.write(event.delta);
  }
  console.log((await streamed.completed).finalOutput);
  ```
</CodeGroup>

## 何时用 aria-agent，何时用 aria-router / aria-engine

* **Agent 脚手架（工具调用与规划）**：`aria-agent`
* **仅类型化 System One 决策**：直接调用 [aria-engine](/sdks/engine-runtime) 或 [Ollaya](/guides/run-olaya)
* **OpenAI 兼容推理网关（chat + 策略）**：[aria-router](/sdks/router-runtime)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.