How to Ask Grok with TwexAPI
Grok is most useful in an automation workflow when the prompt is tied to evidence you already collected: tweets from a search, DM conversation summaries, account status checks, or a campaign report. The job is not just to ask a question. The job is to preserve what you asked, what source data you used, which X account made the request, and which Grok conversation should continue next time.
TwexAPI's Ask Grok endpoint sends a prompt to Grok with a Twitter/X account cookie by calling POST /v3/twitter/grok/ask.
This endpoint returns a Grok response. It does not fetch tweets, read DM history, or build the prompt for you. Pull the X data first, build a concise prompt from that stored context, then call Ask Grok from your server.
Endpoint and Request Fields
Use POST /v3/twitter/grok/ask to ask Grok from a server-side workflow.
| Field | Type | Required | Notes |
|---|---|---|---|
prompt | string | Yes | User prompt sent to Grok. Include source context and the task. |
cookie | string | Yes | X authentication cookie or auth_token. Keep it server-side. |
conversation_id | string or null | No | Existing Grok conversation ID when you want to continue a Grok thread. |
model | string or null | No | Optional model ID. API default is grok-3-latest. |
proxy | string or null | No | Optional HTTP proxy for the session. |
The conversation_id here belongs to Grok. Do not confuse it with XChat conversation_id from DM endpoints.
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=..."
}'The response returns the Grok conversation ID and 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}Store the returned conversation_id if the next prompt should continue the same Grok thread. Store message as the answer, and keep the raw response for auditing.
Build Prompts From Stored X Data
Keep prompts narrow. A useful prompt usually includes the task, source records, and 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 reviewDo not ask Grok to guess what your stored data does not contain. If the source records are incomplete, say that in the prompt.
Python Grok Client
This script takes a set of saved source records, builds a prompt, calls Grok, and stores enough metadata to replay the decision later.
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 )Set TWEXAPI_BEARER_TOKEN and TWEXAPI_X_COOKIE in your server environment before running the script. Do not call this endpoint from the browser because the request needs the X cookie.
Continuing a Grok Conversation
When the response returns conversation_id, save it as grok_conversation_id. Pass it back only when the next request should continue the same Grok thread.
follow_up = ask_grok(
"Turn the previous answer into a support team checklist.",
conversation_id=saved_grok_conversation_id,
)Keep the naming explicit. A field named conversation_id can also appear in XChat workflows, so store Grok IDs as grok_conversation_id in your database.
Grok Analysis Workflow
- Collect source data: Search posts, export DM history, or fetch account data with the relevant TwexAPI endpoint.
- Store the raw source: Keep tweet IDs, timestamps, authors, metrics, DM message IDs, or other evidence.
- Build a prompt: Include only the records needed for the task and state the output format.
- Ask Grok: Call
POST /v3/twitter/grok/askwithprompt,cookie, and optionalmodel. - Store the result: Save
message,conversation_id, chat item IDs,soft_stop, follow-up suggestions, prompt, and raw response. - Review before action: Treat Grok output as analysis. Human approval should still gate external messages, public posts, or customer-facing decisions.
This makes the result easier to trust because every answer points back to the source records used in the prompt.
Fields To Store
| Field | Why it matters |
|---|---|
source_job_id | Connects the Grok answer to the data extraction job. |
prompt | Shows exactly what was asked. |
grok_conversation_id | Lets a later request continue the same Grok thread. |
user_chat_item_id | Links the user prompt item when returned. |
agent_chat_item_id | Links the Grok response item when returned. |
message | Final assistant answer. |
reasoning | Optional reasoning text returned by the API. |
soft_stop | Shows whether the response soft-stopped. |
follow_up_suggestions | Suggested next prompts from Grok. |
model | Records which model was requested. |
asked_at | Timestamp for audit and replay. |
| Raw response JSON | Lets you reprocess if your schema changes. |
Do not store the full account cookie with Grok results. Store a credential reference instead.
Common Mistakes
- Mixing up Grok
conversation_idwith XChatconversation_id. - Sending a broad prompt without source records, then treating the answer as evidence.
- Calling the endpoint from client-side code and exposing the X cookie.
- Continuing the wrong Grok conversation because the saved ID was not scoped to a job or account.
- Using Grok output to trigger public actions without review.
Wrap-up
Use POST /v3/twitter/grok/ask when you want Grok to analyze or summarize X data you have already collected. Send a clear prompt, keep the X cookie server-side, store the returned Grok conversation_id, and keep the response tied to the source records that informed it.