Cortex Agents REST API

API 를 사용하여 대화형 채팅 애플리케이션을 간단하게 만들 수 있습니다.

에이전트 실행

POST <account_url>/api/v2/cortex/agent:run

요청 본문에 제공된 Cortex Agents 서비스에 사용자 쿼리를 전송하고 응답을 반환합니다.

요청

경로 매개 변수

매개 변수

설명

account_url

(필수) Snowflake 계정 URL. 계정 URL 찾기에 대한 지침은 계정의 조직 및 계정 이름 찾기 섹션을 참조하십시오.

헤더 요청

헤더

설명

Authorization

(필수) 승인 토큰. 자세한 내용은 REST API 인증 구성 섹션을 참조하십시오.

Content-Type

(필수) 애플리케이션/json

요청 본문

요청 본문에는 모델, 응답 지침, 실험 필드, 도구, 도구 리소스 및 메시지가 포함됩니다.

필드

타입

설명

model

문자열

Agent가 응답을 생성하는 데 사용하는 모델의 이름입니다. 지원되는 모델 목록은 지원 모델 섹션을 참조하십시오.

response_instruction

문자열

모델이 응답을 생성할 때 따르는 지침입니다.

experimental

오브젝트

에이전트에게 전달된 실험적 플래그입니다.

tools

배열

에이전트가 사용할 수 있는 도구 사양의 배열입니다.

tool_resources

오브젝트

도구의 필수 리소스입니다.

tool_choice

오브젝트

도구를 선택하는 데 사용되는 구성입니다.

messages

배열

대화의 메시지 배열입니다.

응답 지침

response_instruction 필드는 응답 생성을 위해 모델에 지침을 제공하는 문자열입니다.

도구 구성

이 섹션에서는 지원되는 도구 유형과 해당 구성 옵션, 각 도구에 필요한 리소스를 지정하는 방법에 대해 자세히 설명합니다.

도구 사양

tools 필드에는 사용 가능한 도구가 배열되어 있습니다.

필드

타입

설명

tool_spec.type

문자열

도구 유형입니다. 유형과 이름의 조합은 고유 식별자입니다.

tool_spec.name

문자열

도구의 이름입니다. 유형과 이름의 조합은 고유 식별자입니다.

지원되는 tool_spec.type 값은 다음과 같습니다.

  • cortex_search: Cortex Search 기능에 사용

  • cortex_analyst_text_to_sql: Cortex Analyst text-to-SQL 에 사용됩니다.

  • sql_exec: SQL 쿼리 실행에 사용됩니다. SQL 쿼리를 실행하고 그 결과를 도구 결과로 제공할 책임은 사용자에게 있습니다. 자세한 내용은 아래 샘플 답변 요청 을 참조하십시오.

  • data_to_chart: 차트 생성에 사용

도구 리소스

tool_resources 오브젝트는 각 도구에 대한 구성 오브젝트를 제공합니다.

tool_resources: {
    "toolName1": {configuration object for toolName1},
    "toolName2": {configuration object for toolName2},
    // ...
}
Copy

각 도구 유형에 대한 구성은 아래에 설명되어 있습니다.

cortex_search

SearchName 오브젝트에는 Cortex Search 도구에 대한 구성이 포함되어 있습니다.

"SearchName": {
    // Required: The Snowflake search service identifier
    "name": "database.schema.service_name",
    // Optional: Number of search results to include
    "max_results": 5,
    // Optional: Column to use as document title
    "title_column": "title",
    // Optional: Column to use as document identifier
    "id_column": "id",
     // Optional: Filters to apply to search results (such as @eq for equality)
    "filter": {
      "@eq": {"<column>": "<value>"}
    }
}
Copy
cortex_analyst_text_to_sql

AnalystName 오브젝트에는 Cortex Analyst 텍스트-SQL 도구에 대한 구성이 포함되어 있습니다. 구성에는 사용할 의미 체계 모델 또는 뷰가 포함되어야 합니다. 예:

"AnalystName": {
    // Stage path to semantic model file in `semantic_model_file`
    "semantic_model_file": "@database.schema.stage/my_semantic_model.yaml"
}
Copy

또는 의미 체계 뷰 개요 사용

"AnalystName": {
    // Fully qualified name of the semantic view object
    "semantic_view": "@database.schema.semantic_view"
}
Copy

도구 선택

tool_choice 필드는 도구 선택 동작을 구성합니다.

필드

타입

설명

type

문자열

도구 선택 방법.

유효한 값:

  • "auto" ` (기본값)

  • "required" (1개 이상의 도구 사용)

  • "tool" (지정된 도구 사용)

name

배열

사용할 도구 이름의 선택적 배열입니다. type = "tool" 의 경우에만 유효합니다.

메시지

messages 배열에는 사용자와 어시스턴트 간의 대화 기록이 포함됩니다.

필드

타입

설명

messages[].role

문자열

메시지 발신자의 역할.

유효한 값:

  • "system"

  • "user"

  • "assistant"

messages[].content

배열

메시지를 구성하는 내용 요소의 배열입니다.

메시지 내용 구조

각 메시지의 content 배열에는 유형이 다른 여러 내용 요소가 포함될 수 있습니다.

필드

타입

설명

messages[].content[].type

문자열

내용 유형입니다.

유효한 값:

  • "text"

  • "chart"

  • "table"

  • "tool_use"

  • "tool_results"

텍스트 내용

type"text" 인 경우:

필드

타입

설명

messages[].content[].text

문자열

메시지의 텍스트 내용입니다.

예:

{
  "type": "text",
  "text": "Show me sales by region for Q1 2024"
}
Copy
차트 내용

type 이 “차트”인 경우:

필드

타입

설명

messages[].content[].chart

오브젝트

메시지의 차트 내용입니다.

messages[].content[].chart.chart_spec

문자열

베가 라이트 사양의 차트입니다.

예:

{
  "type": "chart",
  "chart": {
    "chart_spec": "{\"$schema\":\"https://vega.github.io/schema/vega-lite/v5.json\",\"data\":{\"values\":[{\"REGION\":\"NORTH_AMERICA\",\"SUM(SALES)\":\"2000.00\"},{\"REGION\":\"EUROPE\",\"SUM(SALES)\":\"1700.00\"},{\"REGION\":\"SAUTH_AMERICA\",\"SUM(SALES)\":\"1500.00\"}]},\"encoding\":{\"x\":{\"field\":\"REGION\",\"sort\":null,\"type\":\"nominal\"},\"y\":{\"field\":\"SUM(SALES)\",\"sort\":null,\"type\":\"quantitative\"}},\"mark\":\"bar\"}",
  }
}
Copy
테이블 내용

type 이 “테이블”인 경우:

필드

타입

설명

messages[].content[].table

오브젝트

메시지의 테이블 내용입니다.

messages[].content[].table.query_id

문자열

실행된 쿼리의 ID 입니다.

예:

{
  "type": "table",
  "table": {
    "query_id": "01bbff92-0304-c8c7-0022-b7869a076c22"
  }
}
Copy
도구 사용

type 이 “tool_use”인 경우:

필드

타입

설명

messages[].content[].tool_use

오브젝트

도구 사용 요청 세부 정보를 위한 컨테이너입니다.

messages[].content[].tool_use.tool_use_id

문자열

이 도구 사용 요청에 대한 고유 식별자입니다.

messages[].content[].tool_use.name

문자열

실행할 도구의 이름입니다. 도구 배열의 도구 이름과 일치해야 합니다.

messages[].content[].tool_use.input

오브젝트

도구 실행을 위한 매개 변수를 입력합니다.

예:

{
  "type": "tool_use",
  "tool_use": {
    "tool_use_id": "tu_01",
    "name": "Analyst1",
    "input": {
      "query": "Show me sales by region for Q1 2024"
    }
  }
}
Copy
도구 결과

type"tool_results" 인 경우:

필드

타입

설명

messages[].content[].tool_results

오브젝트

도구 실행 결과 및 메타데이터를 위한 컨테이너입니다.

messages[].content[].tool_results.tool_use_id

문자열

이러한 결과를 생성한 tool_use_id를 참조합니다.

messages[].content[].tool_results.name

문자열

실행된 도구의 이름입니다. 도구 배열의 도구 이름과 일치해야 합니다.

messages[].content[].tool_results.status

문자열

도구 실행 상태입니다.

유효한 값:

  • "success"

  • "error"

messages[].content[].tool_results.content

배열

도구 실행에 의해 생성된 내용 요소의 배열입니다.

다음 유형의 요소를 포함할 수 있습니다.

타입

필드

설명

text

type: "text"
text: string

도구에서 반환한 일반 텍스트 내용입니다.

json

type: "json"
json: object

도구에서 반환한 정형 JSON 데이터입니다.

예:

{
  "type": "tool_results",
  "tool_results": {
    "tool_use_id": "tu_01",
    "status": "success",
    "content": [
      {
        "type": "json",
        "json": {
          "sql": "SELECT region, SUM(sales) FROM sales_data WHERE quarter='Q1' AND year=2024 GROUP BY region"
          "text": "This is our interpretation of your question: Show me sales by region for Q1 2024. We have generated the following SQL query for you: SELECT region, SUM(sales) FROM sales_data WHERE quarter='Q1' AND year=2024 GROUP BY region"
        }
      }
    ]
  }
}
Copy
전체 메시지 예시

이 예는 사용자 쿼리(roleuser) 및 응답(roleassistant)이 포함된 전체 메시지를 보여줍니다. 응답에는 Analyst1 이라는 도구에 대한 도구 사용 이벤트와 동일한 도구에 대한 도구 결과 이벤트가 포함됩니다.

{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Show me sales by region for Q1 2024"
        }
      ]
    },
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool_use",
          "tool_use": {
            "tool_use_id": "tu_01",
            "name": "Analyst1",
            "input": {
              "query": "Show me sales by region for Q1 2024"
            }
          }
        },
        {
          "type": "tool_results",
          "tool_results": {
            "tool_use_id": "tu_01",
            "name": "Analyst1",
            "status": "success",
            "content": [
              {
                "type": "json",
                "json": {
                  "sql": "SELECT region, SUM(sales) FROM sales_data WHERE quarter='Q1' AND year=2024 GROUP BY region"
                  "text": "This is our interpretation of your question: Show me sales by region for Q1 2024. We have generated the following SQL query for you: SELECT region, SUM(sales) FROM sales_data WHERE quarter='Q1' AND year=2024 GROUP BY region"
                }
              }
            ]
          }
        }
      ]
    }
  ]
}
Copy

응답

스트리밍 시 각 이벤트는 다음과 같은 기본 패턴을 가진 서버 전송 이벤트(SSE) 형식으로 도착합니다.

  • 출력의 청크에 대한 증분 message.delta 이벤트

  • 오류가 발생한 경우 error 이벤트.

message.delta 이벤트

필드

타입

설명

event

문자열

부분 메시지 데이터의 경우 message.delta.

data

오브젝트

증분 업데이트 데이터를 포함합니다.

data.id

문자열

메시지의 고유 식별자입니다.

data.object

문자열

message.delta 또는 이와 유사한 설명자.

data.delta.content

배열

청크 또는 부분 메시지 세그먼트의 목록입니다.

data.delta.content[].index

정수

현재 메시지 내에서 이 청크의 위치입니다.

data.delta.content[].type

문자열

내용 유형. 유효한 값:

  • "text"

  • "chart"

  • "table"

  • "tool_use"

  • "tool_results"

data.delta.content[].text

문자열

type = "text" 인 경우 부분 텍스트 문자열입니다.

data.delta.content[].chart

오브젝트

type = "chart" 인 경우 메시지의 차트 내용입니다.

data.delta.content[].chart.chart_spec

문자열

베가 라이트 사양의 차트입니다.

data.delta.content[].table

오브젝트

type = "table" 인 경우 메시지의 테이블 내용입니다.

data.delta.content[].table.query_id

문자열

실행된 쿼리의 ID 입니다.

data.delta.content[].tool_use

오브젝트

type = "tool_use" 인 경우 도구 호출이 진행 중임을 나타냅니다. Tool_use_id, 이름, 입력을 포함합니다.

data.delta.content[].tool_use.tool_use_id

문자열

도구 호출의 고유 식별자입니다.

data.delta.content[].tool_use.name

문자열

호출 중인 도구의 이름입니다.

data.delta.content[].tool_use.input

오브젝트

JSON 도구의 페이로드입니다.

data.delta.content[].tool_results

오브젝트

type = "tool_results" 인 경우 도구 출력이 포함되어 있습니다.

data.delta.content[].tool_results.tool_use_id

문자열

도구 출력의 고유 식별자입니다.

data.delta.content[].tool_results.status

문자열

도구 실행 상태입니다. 유효한 값:

  • "success"

  • "error"

data.delta.content[].tool_results.content

배열

도구에서 반환된 데이터를 설명하는 항목 목록입니다.

data.delta.content[].tool_results.content[].type

문자열

도구에서 반환하는 내용 유형입니다. 유효한 값:

  • "text/csv"

  • "application/json"

  • "application/pdf"

data.delta.content[].tool_results.content[].json

오브젝트

type = "application/json", 도구에서 반환한JSON데이터입니다.

data.delta.content[].tool_results.content[].text

문자열

type = "text", 도구에서 반환한 텍스트 데이터입니다.

error 이벤트

필드

타입

설명

event

문자열

error 를 클릭해 오류 이벤트를 확인하십시오.

data

오브젝트

오류 세부 정보가 포함되어 있습니다.

data.code

문자열

Snowflake 오류 코드입니다. 예: "399505".

data.message

문자열

무엇이 잘못되었는지에 대한 설명입니다. 예: "Internal server error".

샘플 대화 플로우

이 섹션에서는 Cortex Agents REST API 를 사용하는 사용자와 어시스턴트 간의 샘플 대화 플로우를 보여줍니다.

샘플 요청하기

{
  "model": "llama3.3-70b",
  "response_instruction": "You will always maintain a friendly tone and provide concise response.",
  "experimental": {},
  "tools": [
    {
      "tool_spec": {
        "type": "cortex_analyst_text_to_sql",
        "name": "Analyst1"
      }
    },
    {
      "tool_spec": {
        "type": "cortex_analyst_text_to_sql",
        "name": "Analyst2"
      }
    },
    {
      "tool_spec": {
        "type": "sql_exec",
        "name": "sql_execution_tool"
      }
    },
    {
      "tool_spec": {
        "type": "data_to_chart",
        "name": "data_to_chart"
      }
    },
    {
      "tool_spec": {
        "type": "cortex_search",
        "name": "Search1"
      }
    }
  ],
  "tool_resources": {
    "Analyst1": { "semantic_model_file": "stage1"},
    "Analyst2": { "semantic_model_file": "stage2"},
    "Search1": {
      "name": "db.schema.service_name",
      "filter": {"@eq": {"region": "North America"} }
    }
  },
  "tool_choice": {
    "type": "auto"
  },
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What are the top three customers by revenue?"
        }
      ]
    }
  ]
}
Copy

샘플 응답

{
  "id": "msg_001",
  "object": "message.delta",
  "delta": {
    "content": [
      {
        "index": 0,
        "type": "tool_use",
        "tool_use": {
          "tool_use_id": "toolu_XXXXXX",
          "name": "analyst1",
          "input": {
            "messages": [
              "role:USER content:{text:{text:\"What are the top three customers by revenue?\"}}"
            ],
            "model": "snowflake-hosted-semantic",
            "experimental": ""
          }
        }
      },
      {
        "index": 0,
        "type": "tool_results",
        "tool_results": {
          "tool_use_id": "toolu_XXXXXX",
          "content": [
            {
              "type": "json",
              "json": {
                "suggestions": [],
                "sql": "WITH __customers AS (\n  SELECT\n    customer_id,\n    revenue\n  FROM user_database.user_schema.user_table\n)\nSELECT\n  customer_id, revenue FROM __customers ORDER BY revenue DESC LIMIT 3\n -- Generated by Cortex Analyst\n;",
                "text": "This is our interpretation of your question:\n\n__What are the top three customers by revenue?\n\n"
              }
            }
          ],
          "status": "success"
        }
      },
        {
          "type": "tool_use",
          "tool_use": {
            "tool_use_id": "tool_002",
            "name": "sql_execution_tool",
            "input": {
              "sql": "WITH __customers AS (SELECT customer_id, revenue FROM user_database.user_schema.user_table) SELECT customer_id, revenue FROM __customers ORDER BY revenue DESC LIMIT 3"
            }
          }
        }
    ]
  }
}
Copy

샘플 답변 요청

Cortex Agents는 실행된 SQL 쿼리를 기반으로 텍스트 및 차트 답변을 생성할 수 있습니다. 다음 예는 Cortex Agents API 를 사용하여 이러한 답변을 생성하는 방법을 보여줍니다.

답변을 얻기 위해 클라이언트는 클라이언트 측에서 실행된 SQL 의 query_id 를 사용하여 Cortex Agent API 에 후속 요청을 합니다. 실행할SQL은 최신 응답 메시지의 sql_exec 도구 유형의 tool_use 이벤트에서 제공됩니다.

요청자는 텍스트 답변을 얻으려면 cortex_analyst_text_to_sqlsql_exec 도구를 사용해야 하며, 차트 답변을 얻으려면 data_to_chart 도구를 사용해야 합니다. 에이전트가 차트가 답을 제시하는 좋은 방법이라고 판단하는 경우에만 차트가 반환됩니다.

참고

셀 수가 4000개가 넘는 결과 세트의 경우 textchart 응답 대신 table 응답이 반환됩니다.

{
  "model": "llama3.3-70b",
  "response_instruction": "You will always maintain a friendly tone and provide concise response.",
  "experimental": {},
  "tools": [
    {
      "tool_spec": {
        "type": "cortex_analyst_text_to_sql",
        "name": "Analyst1"
      }
    },
    {
      "tool_spec": {
        "type": "cortex_analyst_text_to_sql",
        "name": "Analyst2"
      }
    },
    {
      "tool_spec": {
        "type": "sql_exec",
        "name": "sql_execution_tool"
      }
    },
    {
      "tool_spec": {
        "type": "data_to_chart",
        "name": "data_to_chart"
      }
    },
    {
      "tool_spec": {
        "type": "cortex_search",
        "name": "Search1"
      }
    }
  ],
  "tool_resources": {
    "Analyst1": { "semantic_model_file": "stage1"},
    "Analyst2": { "semantic_model_file": "stage2"},
    "Search1": {
      "name": "db.schema.service_name",
      "filter": {"@eq": {"region": "North America"} }
    }
  },
  "tool_choice": {
    "type": "auto"
  },
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What are the top three customers by revenue?"
        }
      ]
    },
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool_use",
          "tool_use": {
            "tool_use_id": "tool_001",
            "name": "Analyst1",
            "input": {
              "messages": [
                "role:USER content:{text:{text:\"What are the top three customers by revenue?\"}}"
              ],
              "model": "snowflake-hosted-semantic",
            }
          }
        },
        {
          "type": "tool_results",
          "tool_results": {
            "status": "success",
            "tool_use_id": "tool_001",
            "content": [
              {
                "type": "json",
                "json": {
                  "sql": "select * from table",
                  "text": "This is our interpretation of your question: What are the top three customers by revenue? \n\n"
                }
              }
            ]
          }
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "tool_results",
          "tool_results": {
            "tool_use_id": "tool_002",
            "result": {
              "query_id": "01bbff92-0304-c8c7-0022-b7869a076c22"
            }
          }
        }
      ]
    }
  ]
}
Copy

샘플 답변 응답

{
  "id": "msg_001",
  "object": "message.delta",
  "delta": {
    "content": [
      {
        "index": 0,
        "type": "text",
        "text": "This is a textual answer to your question"
      },
      {
        "index": 0,
        "type": "chart",
        "chart": {
          "chart_spec": "{\"$schema\": \"https://vega.github.io/schema/vega-lite/v5.json\", \"title\": \"Example chart\", \"mark\": \"bar\", \"encoding\": {\"x\": {\"field\": \"column_x\", \"type\": \"nominal\", \"sort\": null}, \"y\": {\"field\": \"column_y\", \"type\": \"quantitative\"}}, \"data\": {\"values\": [{\"column_x\": \"A\", \"column_y\": \"1\"}, {\"column_x\": \"A\", \"column_y\": \"1\"}]}}"
        }
      }
    ]
  }
}
Copy

Cortex Agents 제한 사항

  • Streamlit in Snowflake (SiS) 앱은 소유자의 권한 으로 실행되므로 SiS 앱 내에서 SQL 문을 실행하는 것은 지원되지 않습니다.

  • Azure OpenAI 모델은 지원되지 않습니다.