Azure Databricks에 배포된 쿼리 에이전트

에이전트를 쿼리하는 방법은 해당 에이전트를 서비스하는 에이전트 서버에 따라 다릅니다. 다음 표에서 에이전트를 찾은 후 해당 섹션을 따라가세요. 에이전트 서버에 대해 알아보려면 에이전트 서버를 참조하세요.

사용자의 에이전트 에서 호스팅됨 조회 방법
사용 DurableAgentServer Agent Runtime on Databricks Apps Invocation API 위치 /api/invocations
MLflow AgentServer 또는 LongRunningAgentServer 사용 (레거시) Databricks 앱 Databricks OpenAI 클라이언트 또는 /responses에서 OpenAI 응답 API
모델 서빙에 배포됨 (레거시) 모델 서비스 접속점 Databricks OpenAI 클라이언트, REST API, ai_query또는 AI Playground

Databricks 앱에 호스팅된 에이전트는 Databricks OAuth 토큰이 필요합니다. 개인 액세스 토큰은 Databricks 앱에서는 작동하지 않습니다. 스크립트, 서비스 주체, 다른 앱 또는 노트북에서 OAuth 토큰을 생성하려면 토큰 인증을 사용하여 API Databricks 앱에 연결을(를) 참조하세요.

DurableAgentServer를 사용하는 에이전트를 조회합니다.

DurableAgentServer를 사용하는 에이전트는 호출 API를 제공합니다. Agent Bricks CLI로 생성한 에이전트는 DurableAgentServer를 사용하며, agentbricks deploy는 이를 라는 이름의 앱으로 agent-bricks-<name>에 배포합니다. API에 대한 각 요청은 에이전트의 한 번의 실행을 시작하며, 이를 호출(invocation)이라고 합니다.

엔드포인트 Description
POST /api/invocations 호출을 시작합니다. 기본적으로 요청은 결과를 반환할 때까지 대기합니다. 이벤트가 발생 background 하면 수신하도록 하거나 즉시 반환되도록 설정 stream 하세요.
GET /api/invocations/<id> 호출 상태를 반환하고, 호출이 완료된 후 출력을 반환합니다.
GET /api/invocations/<id>/events?after=<event-id> <event-id> 뒤에 오는 저장된 이벤트를 스트리밍합니다. 이 엔드포인트를 사용해 스트림에 다시 연결하세요.

요청 메시지 본문

POST /api/invocations에 대한 요청 본문은 다음 필드를 허용합니다. 서버는 다른 필드가 포함된 요청을 거부합니다.

Field Description
id Required. 각 호출마다 생성하는 UUID입니다. 서버는 ID를 멱등성 키로 취급합니다: 동일한 ID로 같은 요청을 다시 보내면 에이전트를 다시 실행하는 대신 기존 호출을 반환합니다. 다른 요청에 ID를 재사용하면 오류가 발생합니다 409 .
session_id 그 호출이 속한 대화입니다. 세션 ID를 공유하는 호출은 한 번에 하나씩, 순서대로 실행됩니다. CLI 템플릿에서 생성된 에이전트는 이 필드를 요구합니다.
input 에이전트를 위한 입력입니다. CLI 템플릿에서 생성된 에이전트는 메시지 목록이나 messages 목록이 있는 객체를 받습니다.
stream true로 설정하면 이벤트를 Server-Sent 이벤트(SSE)로 수신합니다.
background 202로 설정하면 상태 URL이 포함된 true 응답을 즉시 반환한 다음, 결과를 폴링하세요.

에이전트의 핸들러가 input의 구조를 정의합니다. CLI 템플릿에서 생성된 에이전트는 input가 객체인 경우 다음 필드를 읽습니다:

Field Description
messages 대화가 에이전트에게 전송되도록 전환됩니다.
actor 에이전트가 읽고 쓰는 장기 기억을 가진 식별 대상. 만약 actor를 전달하지 않으면 에이전트가 세션 ID를 사용하기 때문에 메모리가 새 세션으로 이월되지 않습니다. 사용자가 입력한 텍스트가 아니라 애플리케이션에 로그인한 사용자로부터 actor를 설정하세요.
model 에이전트 코드에 설정된 모델 대신 이 호출에 사용할 모델
resume 도구 호출 승인과 같은 인간 입력을 위해 일시 중지한 에이전트에 대한 응답. 에이전트가 일시 중지하면, 호출의 status는 interrupted입니다. 계속하려면 동일한 resume로 새 호출에서 session_id을(를) 보내세요.

에이전트가 세션 간에 사용자에 대해 알게 된 내용을 기억하려면, 사용자의 ID를 다음과 같이 actor전달하세요:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "session_id": "support-case-123",
  "input": {
    "messages": [{ "role": "user", "content": "What does Databricks do?" }],
    "actor": "user-42"
  }
}

에이전트 브릭스

터미널에서 배포된 에이전트를 테스트하려면 agentbricks endpoint invoke를 사용하세요. 이 명령어는 앱을 조회하고 CLI 프로필로 인증합니다.

agentbricks --profile <profile> endpoint invoke agent-bricks-<name> \
  --path /api/invocations \
  --json "{\"id\":\"$(uuidgen)\",\"session_id\":\"$(uuidgen)\",\"input\":[{\"role\":\"user\",\"content\":\"Hello\"}]}"

응답을 스트리밍하려면 JSON 본체에 "stream":true를 추가하고 --sse를 전달하세요. 에이전트를 로컬에서 agentbricks dev로 실행하는 동안 테스트하려면 앱 이름을 --url http://localhost:8000로 바꾸세요.

REST API

  1. 앱 URL을 가져오세요. 출력의 URL 필드는 호출 API의 기본 URL입니다.

    agentbricks --profile <profile> deployments get agent-bricks-<name>
    
  2. 프로필용 OAuth 토큰을 받으세요. 출력에는 access_token 필드에 토큰이 포함됩니다.

    databricks auth token --profile <profile>
    
  3. 요청 보내기:

    curl --request POST \
      --url <app-url>/api/invocations \
      --header 'Authorization: Bearer <OAuth token>' \
      --header 'content-type: application/json' \
      --data '{
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "session_id": "support-case-123",
        "input": [{ "role": "user", "content": "What does Databricks do?" }]
      }'
    

응답에는 호출 id, 해당 status, 그리고 에이전트가 반환하는 값이 담긴 output 필드가 포함됩니다. 서버는 출력 스키마를 요구하지 않습니다: 핸들러는 JSON 직렬화 가능한 어떤 값이든 반환할 수 있습니다. CLI 템플릿에서 생성된 에이전트는 다음과 같은 필드를 가진 객체를 반환합니다:

  • output: 요원이 이 호출에서 생성한 메시지들.
  • status: completed, 또는 interrupted 에이전트가 인간 입력을 위해 일시 중지된 경우.

Python

다음 예시는 Databricks SDK를 사용해 앱 URL을 조회하고 OAuth 토큰을 생성한 후 invocations API를 호출합니다. WorkspaceClient는 반드시 OAuth 인증을 사용해야 합니다.

import uuid

import requests
from databricks.sdk import WorkspaceClient

w = WorkspaceClient()
app_url = w.apps.get("agent-bricks-<name>").url
session_id = str(uuid.uuid4())

response = requests.post(
    f"{app_url}/api/invocations",
    headers=w.config.authenticate(),
    json={
        "id": str(uuid.uuid4()),
        "session_id": session_id,
        "input": [{"role": "user", "content": "What does Databricks do?"}],
    },
)
response.raise_for_status()
print(response.json()["output"])

대화를 계속하려면 다음 메시지를 같은 session_id와 새 id로 보내세요.

스트리밍, 백그라운드 실행 및 재연결

  • 스트림: 설정 "stream": true. 응답은 SSE 스트림으로, 스트림에는 run.started 및 run.completed(또는 run.failed) 이벤트가 포함되며, 에이전트가 방출하는 이벤트들, 예를 들어 스트리밍된 텍스트가 포함된 delta 이벤트와 같은 이벤트도 포함됩니다. 각 이벤트에는 ID가 있습니다.
  • 백그라운드에서 실행: 설정 "background": true. 서버는 202 응답을 status_url와 함께 반환합니다. 상태가 completedGET /api/invocations/<id>일 때까지 폴링하세요. "stream": true도 설정하면 응답에 이벤트를 읽을 수 있는 events_url도 포함됩니다.
  • 재연결: 스트림이 끊기면 마지막으로 받은 이벤트의 ID와 함께 GET /api/invocations/<id>/events?after=<event-id>를 호출하세요.

다음 Python 예시는 응답을 스트리밍합니다:

with requests.post(
    f"{app_url}/api/invocations",
    headers=w.config.authenticate(),
    json={
        "id": str(uuid.uuid4()),
        "session_id": session_id,
        "input": [{"role": "user", "content": "Summarize our last conversation."}],
        "stream": True,
    },
    stream=True,
) as response:
    response.raise_for_status()
    for line in response.iter_lines(decode_unicode=True):
        if line.startswith("data: "):
            print(line[len("data: "):])

여러 인스턴스로 에이전트를 배포한다면, 세션 ID를 X-Routing-Key 헤더로 보내 세션 내 모든 요청을 동일한 인스턴스로 라우팅하세요.

레거시 MLflow를 사용하는 에이전트에게 쿼리하세요 AgentServer

이 섹션은 레거시 에이전트 서버를 사용해 Databricks 앱에 배포하는 에이전트, 즉 ResponsesAgent 인터페이스를 사용하는 MLflow AgentServer 또는 LongRunningAgentServer에 대해 사용하세요. 이 에이전트들은 /responses에서 OpenAI Responses API를 제공합니다.

LongRunningAgentServer 동일한 API를 제공하므로 다음 예시들도 적용됩니다. 또한 백그라운드 런을 지원합니다: 요청에서 true를 background로 설정한 후, 응답은 GET /responses/<response-id>?stream=true&starting_after=<sequence-number>로 가져오며, 해당 시퀀스 번호 이후의 이벤트를 스트리밍합니다.

Databricks OpenAI 클라이언트

Databricks는 이 에이전트들에 대해 Databricks OpenAI 클라이언트 를 권장합니다. 모델명에 접두사를 apps/ 포함하세요.

from databricks.sdk import WorkspaceClient
from databricks_openai import DatabricksOpenAI

input_msgs = [{"role": "user", "content": "What does Databricks do?"}]
app_name = "<agent-app-name>"

# The WorkspaceClient must use OAuth authentication.
w = WorkspaceClient()
client = DatabricksOpenAI(workspace_client=w)

# Non-streaming request
response = client.responses.create(model=f"apps/{app_name}", input=input_msgs)
print(response)

# Streaming request
streaming_response = client.responses.create(
    model=f"apps/{app_name}", input=input_msgs, stream=True
)
for chunk in streaming_response:
    print(chunk)

custom_inputs를 전달하려면 extra_body 매개변수를 사용하세요:

response = client.responses.create(
    model=f"apps/{app_name}",
    input=input_msgs,
    extra_body={"custom_inputs": {"id": 5}},
)

요청의 트레이스 ID를 얻으려면 x-mlflow-return-trace-id 헤더를 포함하세요. 그런 다음 MLflow get_trace 를 사용하여 전체 추적을 검색합니다.

response = client.responses.create(
    model=f"apps/{app_name}",
    input=input_msgs,
    extra_headers={"x-mlflow-return-trace-id": "true"},
)
trace_id = response.metadata["trace_id"]
trace = client.get_trace(trace_id)

REST API

/responses 앱 URL 경로로 요청을 보냅니다. 요청 본문은 OpenAI 응답 API를 따르므로, 이를 지원하는 HTTP 클라이언트나 도구를 사용할 수 있습니다.

curl --request POST \
  --url <app-url>/responses \
  --header 'Authorization: Bearer <OAuth token>' \
  --header 'content-type: application/json' \
  --data '{
    "input": [{ "role": "user", "content": "hi" }],
    "stream": true
  }'

custom_inputs를 전달하려면 요청 본문에 추가하세요:

curl --request POST \
  --url <app-url>/responses \
  --header 'Authorization: Bearer <OAuth token>' \
  --header 'content-type: application/json' \
  --data '{
    "input": [{ "role": "user", "content": "hi" }],
    "custom_inputs": { "id": 5 }
  }'

트레이스 ID를 얻으려면 x-mlflow-return-trace-id: true 헤더를 포함하세요. 응답 본문에는 metadata.trace_id 필드에 트레이스 ID가 포함됩니다. 스트리밍 요청의 경우, 트레이스 ID는 스트림 끝부분에 별도의 SSE 이벤트(data: {"trace_id": "tr-..."})로 도착합니다.

Model Serving의 레거시 에이전트 조회

모델 서빙 엔드포인트에 배포된 레거시 에이전트에 대해서는 이 섹션을 사용하세요. Databricks OAuth 토큰이나 개인 액세스 토큰으로 인증할 수 있습니다. 이 에이전트들을 Databricks 앱으로 이동하려면 ' 모델 서빙에서 Databricks 앱으로 에이전트 마이그레이션'을 참조하세요.

Databricks OpenAI 클라이언트

ResponsesAgent 인터페이스를 사용하는 에이전트의 경우, 엔드포인트 이름을 모델로 사용하여 responses.create을 호출합니다:

from databricks_openai import DatabricksOpenAI

input_msgs = [{"role": "user", "content": "What does Databricks do?"}]
endpoint = "<agent-endpoint-name>"

client = DatabricksOpenAI()

# Non-streaming request. Calls predict.
response = client.responses.create(model=endpoint, input=input_msgs)
print(response)

# Streaming request. Calls predict_stream.
streaming_response = client.responses.create(model=endpoint, input=input_msgs, stream=True)
for chunk in streaming_response:
    print(chunk)

레거시 ChatAgent 또는 ChatModel 인터페이스를 사용하는 상담원은 채팅 완료 클라이언트를 사용하세요:

from databricks.sdk import WorkspaceClient

messages = [{"role": "user", "content": "What does Databricks do?"}]
endpoint = "<agent-endpoint-name>"

client = WorkspaceClient().serving_endpoints.get_open_ai_client()
response = client.chat.completions.create(model=endpoint, messages=messages)
print(response)

클라이언트 중 어느 쪽이든 custom_inputs 또는 databricks_options를 extra_body 매개변수를 통해 전달합니다. 예를 들어, extra_body={"databricks_options": {"return_trace": True}}는 응답과 함께 트레이스를 반환합니다.

REST API

인터페이스를 사용하는 ResponsesAgent 에이전트의 경우, 엔드포인트 이름을 모델로 하여 /serving-endpoints/responses로 요청을 보냅니다:

curl --request POST \
  --url https://<workspace-url>/serving-endpoints/responses \
  --header 'Authorization: Bearer <token>' \
  --header 'content-type: application/json' \
  --data '{
    "model": "<agent-endpoint-name>",
    "input": [{ "role": "user", "content": "hi" }],
    "stream": true
  }'

ChatAgent 또는 input 인터페이스를 사용하는 에이전트의 경우, ChatModel 대신 /serving-endpoints/chat/completions 목록과 함께 messages로 요청을 보내세요. custom_inputs 또는 databricks_options를 전달하려면 요청 본문에 추가하세요. 엔드포인트 /serving-endpoints/<agent-endpoint-name>/invocations 의 URL로 요청을 보낼 수도 있습니다. 엔드포인트 뒤의 개별 모델 쿼리를 참조하세요.

AI 플레이그라운드

코드를 작성하지 않고 모델 서빙에서 에이전트와 채팅하려면 AI Playground 를 열고 에이전트의 서빙 엔드포인트를 선택하세요. AI Playground에서 custom_inputs를 에이전트에게 전달하려면 AI Playground 및 검토 앱에서 custom_inputs 제공을(를) 참조하세요.

SQL 사용

ai_query를 사용하여 SQL에서 모델 서빙의 에이전트를 쿼리하세요. 구문과 매개변수는 ai_query함수를 참조하세요.

SELECT ai_query(
  "<agent-endpoint-name>", question
) FROM (VALUES ('what is MLflow?'), ('how does MLflow work?')) AS t(question);

추가 리소스