구조화된 데이터(SQL) 질의하기
구조화된 데이터(SQL) 질의하기
이 페이지는 SQL 생성을 사용해 구조화된 데이터를 질의하는 방법을 설명해요. Cohere로 데이터베이스에 SQL 쿼리와 분석을 수행하는 과정을 살펴볼게요.
출처: 문서
본문
이 튜토리얼에서는 Cohere를 사용해 데이터베이스에서 SQL 쿼리와 분석을 수행하는 방법을 배우게 돼요.
완전한 코드 예시 (Complete code example)
전체 코드 예시는 다음과 같아요:
PYTHON
import cohere
co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")
# Step 1: Provide the schema to the model
schema = """
CREATE TABLE employees (
id INT,
name TEXT,
department TEXT,
employment_type TEXT,
)
"""
# Step 2: Define the use query
user_query = "What is the distribution of employees by department and employment type?"
# Step 3: Generate SQL
sql_query = co.chat(
model="command-a-03-2025",
messages=[
{"role": "system", "content": "You are an SQL query writer who translates user requests into SQL queries."},
{"role": "user", "content": f"Schema: {schema} Query: {user_query} Return the SQL only."}
],
temperature=0, # deterministic
tool_choice="none",
)
# Step 4: Execute the SQL query
import sqlite3
conn = sqlite3.connect("employees.db")
cursor = conn.cursor()
cursor.execute(sql_query.message.content[0].text)
# Step 5: Analyze the results
conn.commit()
rows = cursor.fetchall()
print(rows)
다음 단계 (Next Steps)
다음 생성/에이전트 패턴들을 살펴보아요: