TwexAPI で Grok に質問する方法
Automation workflow で Grok を使うなら、prompt はすでに収集した evidence と結びついているべきです。Search で取得した tweets、DM conversation summary、account status check、campaign report などです。単に質問するのではなく、何を聞いたか、どの source data を使ったか、どの X account から request したか、次にどの Grok conversation を続けるかを保存します。
TwexAPI の Ask Grok endpoint は、POST /v3/twitter/grok/ask で Twitter/X account cookie を使って Grok に prompt を送ります。
この endpoint は Grok response を返します。Tweets を取得したり、DM history を読んだり、prompt を自動構築したりはしません。先に X data を取得し、保存済み context から concise prompt を作り、server-side から Ask Grok を呼びます。
Endpoint と Request Fields
Server-side workflow から Grok に質問するには POST /v3/twitter/grok/ask を使います。
| Field | Type | Required | Notes |
|---|---|---|---|
prompt | string | Yes | Grok に送る user prompt。Source context と task を含めます。 |
cookie | string | Yes | X authentication cookie または auth_token。server-side に保管します。 |
conversation_id | string or null | No | 既存 Grok conversation を続ける場合に渡します。 |
model | string or null | No | Optional model ID。API default は grok-3-latest。 |
proxy | string or null | No | Optional HTTP proxy。 |
ここでの conversation_id は Grok のものです。DM endpoints の XChat conversation_id と混同しないでください。
Basic Request
curl --request POST \
--url https://api.twexapi.io/v3/twitter/grok/ask \
--header "Authorization: Bearer $TWEXAPI_BEARER_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"prompt": "Summarize the following five X posts into three risks and three follow-up actions. Keep the answer concise. Source posts: ...",
"model": "grok-3-latest",
"cookie": "auth_token=...; ct0=...; twid=..."
}'response は Grok conversation ID と final assistant message を返します。
1{
2 "code": 200,
3 "msg": "success",
4 "data": {
5 "conversation_id": "2076320454898278729",
6 "user_chat_item_id": "2076320454898278730",
7 "agent_chat_item_id": "2076320454898278731",
8 "message": "The main risks are...",
9 "reasoning": "Thinking about your request",
10 "soft_stop": false,
11 "follow_up_suggestions": [
12 {
13 "label": "Turn this into an action plan",
14 "properties": null,
15 "tools_overrides": null
16 }
17 ]
18 }
19}次の prompt で同じ Grok thread を続ける場合は、返却された conversation_id を保存します。message を回答として保存し、audit のため raw response も残します。
Build Prompts From Stored X Data
Prompt は narrow にします。Useful prompt は task、source records、output format を含みます。
1Task:
2Summarize the following X posts into customer objections and sales follow-up actions.
3
4Source records:
5- tweet_id=...
6 author=...
7 created_at=...
8 text=...
9 metrics=...
10
11Output:
121. Top objections
132. Evidence from source posts
143. Follow-up actions
154. Questions that need human review保存データにないことを Grok に推測させないでください。Source records が不完全なら、そのことを prompt に書きます。
Python Grok Client
この script は保存済み source records から prompt を作り、Grok を呼び、後で判断を replay できる metadata を保存します。
1import os
2from datetime import datetime, timezone
3from typing import Any
4
5import requests
6
7API_URL = "https://api.twexapi.io/v3/twitter/grok/ask"
8BEARER_TOKEN = os.environ["TWEXAPI_BEARER_TOKEN"]
9X_COOKIE = os.environ["TWEXAPI_X_COOKIE"]
10GROK_MODEL = os.environ.get("TWEXAPI_GROK_MODEL", "grok-3-latest")
11PROXY = os.environ.get("TWEXAPI_PROXY")
12
13def build_prompt(source_records: list[dict[str, Any]]) -> str:
14 lines = [
15 "Task:",
16 "Summarize these X posts into customer objections and follow-up actions.",
17 "",
18 "Source records:",
19 ]
20 for item in source_records:
21 lines.extend(
22 [
23 f"- tweet_id={item['tweet_id']}",
24 f" author={item.get('author', 'unknown')}",
25 f" created_at={item.get('created_at', 'unknown')}",
26 f" text={item.get('text', '')}",
27 f" metrics={item.get('metrics', {})}",
28 ]
29 )
30 lines.extend(
31 [
32 "",
33 "Output:",
34 "1. Top objections",
35 "2. Evidence from source posts",
36 "3. Follow-up actions",
37 "4. Questions that need human review",
38 ]
39 )
40 return "\n".join(lines)
41
42def ask_grok(
43 prompt: str,
44 *,
45 conversation_id: str | None = None,
46) -> dict[str, Any]:
47 payload: dict[str, Any] = {
48 "prompt": prompt,
49 "cookie": X_COOKIE,
50 "model": GROK_MODEL,
51 }
52 if conversation_id:
53 payload["conversation_id"] = conversation_id
54 if PROXY:
55 payload["proxy"] = PROXY
56
57 response = requests.post(
58 API_URL,
59 headers={
60 "Authorization": f"Bearer {BEARER_TOKEN}",
61 "Content-Type": "application/json",
62 "Accept": "application/json",
63 },
64 json=payload,
65 timeout=120,
66 )
67 response.raise_for_status()
68 data = response.json()
69
70 if data.get("code") != 200:
71 raise RuntimeError(data.get("msg", "TwexAPI returned an error"))
72
73 return data["data"]
74
75def normalize_grok_result(
76 *,
77 source_job_id: str,
78 prompt: str,
79 result: dict[str, Any],
80) -> dict[str, Any]:
81 return {
82 "source_job_id": source_job_id,
83 "prompt": prompt,
84 "grok_conversation_id": result["conversation_id"],
85 "user_chat_item_id": result.get("user_chat_item_id"),
86 "agent_chat_item_id": result.get("agent_chat_item_id"),
87 "message": result["message"],
88 "reasoning": result.get("reasoning"),
89 "soft_stop": result.get("soft_stop"),
90 "follow_up_suggestions": result.get("follow_up_suggestions") or [],
91 "model": GROK_MODEL,
92 "asked_at": datetime.now(timezone.utc).isoformat(),
93 "raw": result,
94 }
95
96if __name__ == "__main__":
97 source_records = [
98 {
99 "tweet_id": "1234567890123456789",
100 "author": "example_user",
101 "created_at": "2026-07-16T09:00:00Z",
102 "text": "The export works, but I need clearer errors when a cursor expires.",
103 "metrics": {"likes": 12, "replies": 3},
104 }
105 ]
106 prompt = build_prompt(source_records)
107 result = ask_grok(prompt)
108 print(
109 normalize_grok_result(
110 source_job_id="weekly-objection-review-2026-07-16",
111 prompt=prompt,
112 result=result,
113 )
114 )Script を実行する前に、server environment に TWEXAPI_BEARER_TOKEN と TWEXAPI_X_COOKIE を設定します。この endpoint は X cookie を必要とするため、browser から呼ばないでください。
Continuing a Grok Conversation
Response の conversation_id は grok_conversation_id として保存します。次の request が同じ Grok thread を続ける場合だけ、それを渡します。
follow_up = ask_grok(
"Turn the previous answer into a support team checklist.",
conversation_id=saved_grok_conversation_id,
)Naming は明確にします。conversation_id は XChat workflow にも出てくるため、database では grok_conversation_id として保存します。
Grok Analysis Workflow
- Collect source data: Relevant TwexAPI endpoint で posts、DM history、account data を取得します。
- Store the raw source: Tweet IDs、timestamps、authors、metrics、DM message IDs などの evidence を保存します。
- Build a prompt: Task に必要な records だけを入れ、output format を指定します。
- Ask Grok:
POST /v3/twitter/grok/askにprompt、cookie、optionalmodelを渡します。 - Store the result:
message、conversation_id、chat item IDs、soft_stop、follow-up suggestions、prompt、raw response を保存します。 - Review before action: Grok output は analysis として扱います。External messages、public posts、customer-facing decisions は human approval を通します。
すべての answer が source records に結びつくので、結果を review しやすくなります。
Fields To Store
| Field | Why it matters |
|---|---|
source_job_id | Grok answer を data extraction job に結びつけます。 |
prompt | 何を聞いたかを正確に残します。 |
grok_conversation_id | 後続 request で同じ Grok thread を続けます。 |
user_chat_item_id | 返却された場合、user prompt item を示します。 |
agent_chat_item_id | 返却された場合、Grok response item を示します。 |
message | Final assistant answer。 |
reasoning | API が返す optional reasoning text。 |
soft_stop | Response が soft-stopped したかを示します。 |
follow_up_suggestions | Grok が提案する next prompts。 |
model | Requested model を記録します。 |
asked_at | Audit と replay の timestamp。 |
| Raw response JSON | Schema が変わったときに reprocess できます。 |
Full account cookie を Grok results に保存しないでください。Credential reference だけを保存します。
Common Mistakes
- Grok
conversation_idと XChatconversation_idを混同する。 - Source records なしの broad prompt を送り、その answer を evidence として扱う。
- Client-side code から endpoint を呼び、X cookie を露出する。
- Saved ID を job/account で scope せず、別の Grok conversation を続けてしまう。
- Grok output で public actions を review なしに実行する。
Wrap-up
収集済み X data を Grok に分析・要約させたいときは、POST /v3/twitter/grok/ask を使います。Clear prompt を送り、X cookie は server-side に置き、返却された Grok conversation_id を保存し、response を source records と結びつけます。