콘텐츠로 이동
테마 선택어두운 테마밝은 테마자동
문서 버전1.0.0
언어 선택한국어

화면 작성

A2uiAuthor를 사용하려면 author를 켭니다. RunContext로 보내려면 ag-ui-server를 추가합니다. Author는 버전·catalog·스키마 설정을 불변으로 공유하고, 각 요청은 독립적인 생성 상태를 가집니다.

use ag_ui_a2ui::{A2uiAuthor, A2uiVersion, Result};
use serde_json::json;
async fn create_cart() -> Result<ag_ui_a2ui::ValidatedSurface> {
let author = A2uiAuthor::basic(A2uiVersion::V0_9_1)?.with_send_data_model(true);
author.create("cart", "Show the cart title")
.generate(|prompt, attempt| async move {
// Replace this deterministic fixture with model.complete(&prompt).await.
if attempt == 1 {
return Ok("invalid generated document".into());
}
assert!(prompt.contains("Correction required"));
Ok(json!([
{"version":"v0.9.1","createSurface":{
"surfaceId":"cart",
"catalogId":"https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json",
"sendDataModel":true
}},
{"version":"v0.9.1","updateComponents":{
"surfaceId":"cart",
"components":[{"id":"root","component":"Text","text":"Your cart"}]
}}
]).to_string())
}).await
}

예제의 결정적 응답 대신 기존 모델 클라이언트의 비동기 호출을 넣습니다. 콜백에는 소유한 String prompt와 1부터 시작하는 시도 번호가 전달됩니다. 응답은 JSON 배열, 메시지 하나, 또는 <a2ui-json> 태그 내부 JSON입니다. 잘못 생성된 문서는 검증 오류를 포함한 교정 prompt로 재시도합니다. Provider 자체의 오류는 즉시 반환하며, Error::generation으로 원래 오류 source를 보존할 수 있습니다. 네트워크 재시도는 호출자가 결정합니다.

Executor나 필수 Send 조건을 강제하지 않습니다. Send 콜백·future는 AG-UI 서버 agent에서 사용할 수 있고, local 콜백은 Rc를 캡처할 수 있습니다. 모델 핸들을 공유한다면 시도마다 핸들을 clone하여 async move로 넘깁니다.

with_send_data_model(true)는 생성 메시지에 sendDataModel: true를 요구하며, 이력 복원과 수정에서도 원래 생성 설정을 확인합니다. 이 플래그는 renderer가 후속 요청에 현재 폼 입력을 첨부하도록 요청합니다. false는 생략과 명시적 false를 모두 허용하고, 이 정책을 설정하지 않으면 어느 값이든 수용합니다.

use ag_ui_a2ui::{A2uiAuthor, Result, ValidatedSurface};
use serde_json::json;
async fn edit_cart(author: &A2uiAuthor, prior: &ValidatedSurface) -> Result<ValidatedSurface> {
author.edit(prior, "Set memo to null")
.generate(|_prompt, _attempt| async {
Ok(json!([{"version":"v0.9.1","updateDataModel":{
"surfaceId":"cart","path":"/memo","value":null
}}]).to_string())
}).await
}

Edit은 기존 surface의 update만 허용합니다. 다른 ID·버전·catalog, create, delete는 거부합니다. 기존 컴포넌트와 theme도 현재 author의 스키마로 다시 검증합니다. 사용자의 다른 입력을 보존하려면 필요한 데이터 path만 수정합니다. Prior는 관찰된 상태이므로 renderer의 현재 입력보다 오래됐을 수 있습니다. 이 API가 동시 편집을 동기화하지는 않습니다.

ValidatedSurface는 private 필드와 읽기 전용 getter를 제공합니다. operations()는 이번에 전송할 batch이고, history()는 이전 batch를 포함한 전체 관찰 이력입니다. 이력을 저장한 뒤 복원할 때는 raw JSON 배열로 읽고 author.validate_create(surface_id, &messages)를 호출합니다. 검사하지 않은 JSON을 ValidatedSurface로 역직렬화할 수 없습니다.

요청에서 a2uiClientDataModel metadata 값을 꺼내 검증하고, 해당 요청이 수정할 수 있는 surface의 snapshot만 반영합니다. ClientDataModel은 metadata를 읽으며 상태 변경은 애플리케이션이 결정합니다. 다음 예제의 cart는 이미 소유권을 확인하고 선택한 surface입니다:

use ag_ui_a2ui::{A2uiAuthor, ClientDataModel, Result, ValidatedSurface};
use serde_json::{json, Value};
fn apply_cart_input(
author: &A2uiAuthor,
cart: &ValidatedSurface,
metadata: &Value,
) -> Result<ValidatedSurface> {
let input = ClientDataModel::from_json(metadata)?;
let Some(snapshot) = input.surfaces.get(cart.surface_id()) else {
return Ok(cart.clone());
};
author.validate_edit(cart, &[json!({
"version":input.version,
"updateDataModel":{
"surfaceId":cart.surface_id(),"path":"/","value":snapshot
}
})])
}

반환한 surface를 author.edit에 넘기면 후속 생성에서 renderer 입력을 사용합니다. Root update는 모델 전체를 교체하므로, 오래된 요청이나 동시 수정의 충돌은 앱에서 판단해야 합니다.

use ag_ui::server::{AgentState, Error, Result, RunContext};
use ag_ui_a2ui::{ValidatedSurface, adapters::agui::SurfacePainter};
fn send<S: AgentState>(ctx: &mut RunContext<S>, surface: &ValidatedSurface) -> Result<()> {
let mut painter = SurfacePainter::from_history(ctx.messages()).map_err(Error::agent)?;
painter.paint(ctx, surface.operations())?;
Ok(())
}

전체 surface를 담은 render_a2ui 도구 호출과 이번 batch의 a2ui_operations 결과, 그리고 프런트엔드가 화면을 그리는 a2ui-surface activity를 발행합니다. 성공 반환은 로컬 이벤트 enqueue를 확인하며, renderer의 수신·반영을 확인한 것은 아닙니다. 전송 오류가 나도 앞선 이벤트가 나갔을 수 있으므로 전체 batch를 자동 재전송하지 마세요. 이 경로는 전체 생성·검증 후 전송하며, 부분 화면 전송과 생성 재시도를 한 API에 섞지 않습니다.

개발자가 카드 틀을 고정하고 agent에게 입력값만 받는 도구를 제공할 수 있습니다. 이 예제는 author feature를 쓰지만 모델을 호출하지 않습니다. validate_create()는 코드가 만든 화면을 공식 스키마로 검사하여 ValidatedSurface를 반환합니다.

use ag_ui_a2ui::{A2uiAuthor, A2uiVersion, AgentMessage, Component, Result, ValidatedSurface};
use ag_ui_a2ui::constants::OFFICIAL_BASIC_CATALOG_ID;
use serde_json::json;
fn summary_card(surface_id: &str, title: &str, description: &str) -> Result<ValidatedSurface> {
let author = A2uiAuthor::basic(A2uiVersion::V0_9_1)?;
let messages = [
AgentMessage::create_surface(surface_id, OFFICIAL_BASIC_CATALOG_ID),
AgentMessage::update_components(surface_id, vec![
Component::new("root", "Card").with("child", json!("body")),
Component::new("body", "Column").with("children", json!(["title", "description"])),
Component::new("title", "Text").with("text", json!({"path":"/title"})),
Component::new("description", "Text").with("text", json!({"path":"/description"})),
]),
AgentMessage::update_data_model(surface_id, "/", json!({
"title": title, "description": description,
})),
].into_iter()
.map(|message| serde_json::to_value(message.with_version(A2uiVersion::V0_9_1)))
.collect::<serde_json::Result<Vec<_>>>()?;
author.validate_create(surface_id, &messages)
}
let card = summary_card("weather-1", "서울 날씨", "맑음 · 21도")?;
assert_eq!(card.data_model().to_json()?["title"], "서울 날씨");

agent 애플리케이션은 이 함수를 다음과 같은 도구 뒤에 연결할 수 있습니다.

weather_get("서울")
→ 맑음, 21도
a2ui_get("summaryCard")
→ 이 템플릿에는 title과 description이 필요함
a2ui_render(template="summaryCard", data={title:"서울 날씨", description:"맑음 · 21도"})
→ summary_card(...) 호출 → 검증된 A2UI → renderer

a2ui_search, a2ui_get, a2ui_render는 애플리케이션이 정하는 예시 이름입니다. A2UI 표준에 정해진 도구가 아닙니다. 검색은 템플릿이 많을 때, get은 설명·입력 형식이 필요할 때 추가합니다. 소수의 고정 템플릿이라면 a2ui_summarycard(title, description) 같은 실행 도구만 등록해도 됩니다. get이 설명을 반환한다고 새 도구가 자동으로 등록되지는 않습니다.

여기서 summaryCard는 기존 Card·Column·Text를 조합한 애플리케이션 템플릿입니다. 새 SummaryCard 컴포넌트 타입을 wire에 넣으려면 별도 catalog 정의와 renderer 구현이 필요합니다. 반환한 card는 AG-UI 서버에서 painter.paint(ctx, card.operations())?로 보낼 수 있습니다. 같은 surface를 다시 표시할 때는 또 create하지 않고 기존 검증 결과에 validate_edit()로 데이터 갱신을 적용합니다. 템플릿 선택과 데이터 수집은 앱, 프로토콜 조립·검증·전송은 SDK가 맡습니다.

직접 작성한 operation과 대화 이력

섹션 제목: “직접 작성한 operation과 대화 이력”

AgentMessage로 프로토콜 메시지를 만들거나, AG-UI에서 SurfaceSpec과 assemble_ops로 UI를 조립합니다. 이력을 읽을 때는 adapters::agui::surfaces_in이나 latest_surface를 사용합니다. 복원 중 오류는 Result로 반환됩니다. SurfacePainter::from_history는 동일한 대화 이력을 사용합니다.

정해진 surface 밖의 생성이나 모델 답변의 점진적 처리가 필요하면 agent 계층에서 A2uiRequestProcessor와 ResponseStream을 사용합니다.

use ag_ui_a2ui::A2uiVersion;
use ag_ui_a2ui::agent::{CatalogConfig, CatalogDocument, RendererCapabilities, resolve_catalogs};
use serde_json::json;
let cards = CatalogDocument::load(
json!({"catalogId":"example.com:cards","components":{}}),
None,
Some(A2uiVersion::V0_9),
).unwrap();
let renderer = RendererCapabilities::from_json(&json!({
"v0.9":{"supportedCatalogIds":["example.com:cards"]}
})).unwrap();
let active = resolve_catalogs(&[CatalogConfig::new(cards)], Some(&renderer), false).unwrap();
assert_eq!(active[0].catalog_id(), "example.com:cards");

RendererCapabilities::from_json은 기능 정보를 읽습니다. Generator가 inline catalog를 허용하면 해당 ID의 완전한 문서를 사용합니다. 이미 활성화한 ID에는 기존 문서를 유지합니다. Capability가 포함된 요청에는 활성 catalog가 하나 이상 필요합니다. 버전별 metadata 키와 catalog ID는 버전과 catalog 선택을 참고합니다.