Metadata-Version: 2.5
Name: algocean-grok-oauth
Version: 0.1.0
Summary: Drop-in ChatOpenAI replacement for LangChain/LangGraph — local Grok OAuth or deployed xAI API key.
Project-URL: Homepage, https://github.com/algocean1204/AlgoceanGrokOAuth
Project-URL: Documentation, https://github.com/algocean1204/AlgoceanGrokOAuth#readme
Project-URL: Repository, https://github.com/algocean1204/AlgoceanGrokOAuth
Project-URL: Issues, https://github.com/algocean1204/AlgoceanGrokOAuth/issues
Project-URL: Changelog, https://github.com/algocean1204/AlgoceanGrokOAuth/releases
Author: algocean1204
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
Keywords: algocean,grok,langchain,langgraph,oauth,xai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: langchain-core>=0.3.0
Requires-Dist: langchain-openai>=0.2.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Description-Content-Type: text/markdown

# AlgoceanGrokOAuth

LangChain / LangGraph에서 **`ChatOpenAI` 자리에 그대로 꽂는** Grok 래퍼입니다.

- **`auth=oauth`** (기본) — SuperGrok / X Premium+ 브라우저 로그인 (Hermes와 같은 xAI device-code)
- **`auth=api_key`** — xAI API key 과금 (`langchain_openai.ChatOpenAI` → `https://api.x.ai/v1`)

> **GitHub:** [algocean1204/AlgoceanGrokOAuth](https://github.com/algocean1204/AlgoceanGrokOAuth)

OAuth 프로토콜(엔드포인트, client_id, device-code, refresh)은 [Hermes Agent](https://github.com/NousResearch/hermes-agent)의 공식 xAI Grok OAuth 코드를 거의 그대로 가져왔습니다.

---

## 1분 시작

```bash
pip install -U algocean-grok-oauth langgraph langchain-core
python -m algocean_grok_oauth login   # oauth 사용 시 1회 (브라우저)
```

```python
from algocean_grok_oauth import AlgoceanGrokOAuth
from langchain_core.messages import HumanMessage

llm = AlgoceanGrokOAuth.chat(model="grok-4.6")
print(llm.invoke([HumanMessage(content="Hello")]).content)

AlgoceanGrokOAuth.print_models()
```

LangGraph 노드에도 **동일한 `llm` 객체**를 넣으면 됩니다.

**하네스는 적용되지 않습니다.** Hermes / Codex / AGENTS.md / 레포 룰 / 사용자 하네스를 읽지 않습니다.  
oauth는 구독 토큰을 `https://api.x.ai/v1`에 넣는 것 외에는 API key와 같습니다. 로컬 개인 자동화·개인 서비스에 그대로 쓰면 됩니다.

---

## 어떤 auth를 쓸까?

| | `auth=oauth` (기본) | `auth=api_key` |
|---|---|---|
| **언제** | 로컬 개발 PC | 배포 서버, CI |
| **인증** | `python -m algocean_grok_oauth login` | `ALGOCEANGROKOAUTH_API` 또는 `XAI_API_KEY` |
| **과금** | SuperGrok / X Premium+ 구독 | xAI API |
| **설치** | `pip install algocean-grok-oauth` (동일) | 동일 |
| **tool calling** (`bind_tools`) | ✅ | ✅ |
| **structured output** | ✅ | ✅ |
| **토큰 스트리밍** | ✅ | ✅ |

**그래프 코드는 그대로** — `llm`을 만드는 줄만 `auth`와 `model`을 바꾸면 됩니다.

---

## 설치

```bash
pip install -U algocean-grok-oauth
```

### oauth — 로컬 개발 (추가 1회)

```bash
python -m algocean_grok_oauth login
python -m algocean_grok_oauth status
```

브라우저에서 [accounts.x.ai](https://accounts.x.ai) 코드를 승인하면 됩니다.  
토큰은 `~/.algocean_grok_oauth/auth.json`에 저장되고, 만료 전에 자동 refresh 됩니다.

원격/SSH에서는 `--no-browser`로 URL만 출력합니다.

```bash
python -m algocean_grok_oauth login --no-browser
```

구독: [SuperGrok](https://x.ai/grok) 또는 [X Premium+](https://x.com/i/premium_sign_up)

### api_key — 배포 / 서버

```bash
export ALGOCEANGROKOAUTH_API=<your-xai-api-key>
# 또는 export XAI_API_KEY=<your-xai-api-key>
```

---

## 기본 사용

```python
from algocean_grok_oauth import AlgoceanGrokOAuth, oauth, api_key
from langchain_core.messages import HumanMessage

llm = AlgoceanGrokOAuth(model="grok-4.6")
llm = AlgoceanGrokOAuth(auth=api_key, model="grok-4.6")

response = llm.invoke([HumanMessage(content="FastAPI Depends를 짧게 설명해줘.")])
await llm.ainvoke([HumanMessage(content="...")])
```

### 환경 변수 / `.env`로 모드 선택

```python
llm = AlgoceanGrokOAuth.from_env()
```

| 상황 | 결과 |
|---|---|
| `ALGOCEANGROKOAUTH_AUTH` 지정 | 그 값 (`oauth` / `api_key`) |
| `ALGOCEANGROKOAUTH_API` 또는 `XAI_API_KEY`만 있음 | `api_key` |
| 둘 다 없음 | `oauth` (구독) |

---

## LangGraph

```python
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, END
from typing_extensions import TypedDict
from algocean_grok_oauth import AlgoceanGrokOAuth

class State(TypedDict):
    user_input: str
    answer: str

llm = AlgoceanGrokOAuth(model="grok-4.6")

async def assistant_node(state: State) -> State:
    messages = [
        SystemMessage(content="간결한 개인 비서."),
        HumanMessage(content=state["user_input"]),
    ]
    ai = await llm.ainvoke(messages)
    return {"answer": ai.content}

graph = StateGraph(State)
graph.add_node("assistant", assistant_node)
graph.set_entry_point("assistant")
graph.add_edge("assistant", END)
app = graph.compile()
```

### ReAct Agent / Structured Output

```python
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from algocean_grok_oauth import AlgoceanGrokOAuth

@tool
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

llm = AlgoceanGrokOAuth.chat(model="grok-4.6")
agent = create_react_agent(llm, tools=[add])
```

xAI는 OpenAI-compatible API라 `bind_tools` / `with_structured_output` / 스트리밍이 ChatOpenAI와 동일합니다.

---

## 생성자 옵션

```python
AlgoceanGrokOAuth(
    model="grok-4.6",
    reasoning_effort=None,
    temperature=None,
    max_tokens=None,
    top_p=None,
    stop=None,
    auth=oauth,          # oauth | api_key
    timeout=180,
    base_url=None,       # 기본 https://api.x.ai/v1
)
```

## 환경 변수

| 변수 | 설명 |
|---|---|
| `ALGOCEANGROKOAUTH_API` | api_key 모드 xAI API key |
| `XAI_API_KEY` | 위와 동일 (fallback) |
| `ALGOCEANGROKOAUTH_AUTH` | `oauth` 또는 `api_key` |
| `XAI_BASE_URL` | inference URL 오버라이드 (`*.x.ai`만 허용) |
| `ALGOCEANGROKOAUTH_HOME` | 토큰 저장 디렉터리 (기본 `~/.algocean_grok_oauth`) |

---

## 제한 사항

- **oauth** — 개인 로컬 / 개인 구독 용도. SaaS 서버 배포에는 부적합.
- OAuth 로그인 후 inference가 HTTP 403이면 xAI가 티어를 막는 경우입니다. `auth=api_key`로 전환하세요.
- Codex 라이브러리의 `repo_read` / `repo_write` 같은 CLI 샌드박스는 없습니다. Grok은 일반 LLM API입니다.

---

## License

MIT

OAuth 프로토콜 일부는 Hermes Agent (Nous Research, MIT)에서 가져왔습니다. `NOTICE` 참고.

## Links

- [GitHub](https://github.com/algocean1204/AlgoceanGrokOAuth)
- [xAI Grok OAuth (Hermes)](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/guides/xai-grok-oauth.md)
- [xAI API](https://docs.x.ai/)
