Metadata-Version: 2.4
Name: crowtit
Version: 0.1.0
Summary: 한국 판례·법령에 근거한 법률 답변 API 클라이언트 (crowtit Legal Agent API)
Project-URL: Homepage, https://crow-tit.com
Project-URL: Console, https://console.crow-tit.com
Project-URL: Terms, https://crow-tit.com/terms
Author-email: "crowtit inc." <ducut91@gmail.com>
License: MIT License
        
        Copyright (c) 2026 crowtit inc.
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: api,case-law,korean-law,law,legal,legal-ai,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: Korean
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.27
Description-Content-Type: text/markdown

# crowtit

한국 판례·법령에 근거한 법률 답변 API 파이썬 클라이언트.

질문 하나를 보내면 서버가 판례 검색·법령 조회·양형 통계 같은 코퍼스 도구를 직접 돌려
근거를 확인한 뒤, 완성된 답변 하나를 돌려줍니다.

```bash
pip install crowtit
```

## 시작하기

키는 [console.crow-tit.com](https://console.crow-tit.com)에서 무료로 발급합니다.

```python
from crowtit import Lawful

client = Lawful(api_key="ct_...")        # 또는 환경변수 CROWTIT_API_KEY
answer = client.ask("전세 보증금을 집주인이 안 돌려주는데 어떻게 대응해야 하나요?")

print(answer.text)
print(answer.disclaimer)
```

> ⚠️ **`disclaimer`는 최종 사용자에게 답변과 함께 표시해야 합니다**(이용약관 제7조).
> 서비스는 변호사가 아니며 일반적인 법률 정보를 제공합니다.

근거를 찾는 동안 수십 초가 걸립니다. 그동안 화면을 비워 두고 싶지 않다면 스트리밍을 쓰세요.

## 스트리밍

```python
for text in client.stream("음주운전 초범인데 처벌 수위가 어떻게 되나요?"):
    print(text, end="", flush=True)
```

다 받은 뒤 근거 목록과 완성본이 필요하면:

```python
with client.stream("음주운전 초범 처벌은?") as stream:
    for text in stream:
        print(text, end="", flush=True)

    answer = stream.get_final_answer()
    for source in answer.sources:
        print(source.url)
```

### 도구 진행까지 보여주기

서버가 무엇을 찾고 있는지 화면에 표시하고 싶다면 이벤트를 직접 읽습니다.
형식은 [Anthropic Messages API](https://docs.claude.com/en/api/messages-streaming)와 같습니다.

```python
with client.stream("음주운전 초범 처벌은?") as stream:
    for event in stream.events:
        if event["type"] == "content_block_start":
            block = event["content_block"]
            if block["type"] == "server_tool_use":
                print(f"[{block['display_name']} 중…]")
        elif event["type"] == "content_block_delta":
            print(event["delta"]["text"], end="", flush=True)
```

## 답변 다루기

```python
answer = client.ask("임금체불을 당했습니다")

answer.text          # 최종 답변 본문
answer.disclaimer    # 표시 의무 문구
answer.sources       # [Source(url=...), ...] — 근거 판례·법령 링크
answer.usage         # Usage(input_tokens=..., output_tokens=..., tool_calls=...)
answer.tool_uses     # 서버가 실행한 코퍼스 도구들
answer.truncated     # 검색 예산 안에 답에 도달하지 못했으면 True
```

### `answer.text`는 왜 `content[0]`이 아닌가

모델은 도구를 부르기 전에 "관련 법령을 먼저 확인하겠습니다" 같은 서두를 쓸 때가 있습니다.
그 서두와 최종 답변은 서로 다른 블록이고, `answer.text`는 **마지막 text 블록**만 돌려줍니다.
이어붙이면 문장이 뭉개지고, 아직 확인하지 않은 사실이 단정처럼 읽히기 때문입니다.

서두를 진행 표시로 쓰고 싶다면 `answer.content`를 직접 보면 됩니다.

## 옵션

```python
answer = client.ask(
    "계약서를 검토해 주세요: ...",
    depth="quick",                       # "deep"(기본·품질 우선) | "quick"(빠른 확인)
    instructions="답변은 3문단 이내로, 존댓말로.",
)
```

`instructions`는 형식·어조에만 적용됩니다. 사실 확인·인용·안전 규칙은 바꿀 수 없습니다.

질문에는 계약서나 사실관계 전문을 붙여도 됩니다(최대 약 32,000 토큰 = 한국어 약 45,000자).

## 오류

```python
from crowtit import RateLimitError, AuthenticationError, APITimeoutError

try:
    answer = client.ask("...")
except RateLimitError as e:
    print(f"{e.retry_after}초 후 다시 시도하세요")     # 분당 한도든 하루 한도든 이 값만 보면 됩니다
except AuthenticationError:
    print("키를 확인하세요")
except APITimeoutError:
    print("stream() 을 쓰면 첫 글자부터 바로 받을 수 있습니다")
```

자동 재시도는 하지 않습니다 — 답변 한 번이 수십 초 걸리고 하루 한도를 깎기 때문에,
언제 다시 부를지는 호출자가 정하는 게 맞습니다.

## async

```python
import asyncio
from crowtit import AsyncLawful

async def main():
    async with AsyncLawful() as client:
        async for text in client.stream("음주운전 초범 처벌은?"):
            print(text, end="", flush=True)

asyncio.run(main())
```

## 한도

무료 베타 기준 분당 6회, 하루 100회입니다(하루 한도는 KST 자정에 초기화).
더 큰 한도가 필요하면 ducut91@gmail.com 으로 문의하세요.

## 링크

- 콘솔(키 발급·사용량) — https://console.crow-tit.com
- 이용약관·개인정보처리방침 — https://crow-tit.com/terms · https://crow-tit.com/privacy
- 법률AI 웹 서비스 — https://lawful.crow-tit.com

MIT License
