How to Ask Grok via API

Author:TwexAPI Team
EN
Read in:
English
日本語中文
TwexAPI
Grok
X API
AI Analysis
API Tutorial
Data Analysis

Use TwexAPI's Ask Grok endpoint to send a prompt through an X account cookie, continue a Grok conversation, and store the response with source context and audit metadata.

Quick Answer

Use TwexAPI's Ask Grok endpoint, POST /v3/twitter/grok/ask, to send a server-side prompt to Grok with an X account cookie. Required fields are prompt and cookie; optional fields include Grok conversation_id for continuing a Grok thread, model defaulting to grok-3-latest, and proxy. The response returns conversation_id, optional chat item IDs, message, optional reasoning, soft_stop, and follow_up_suggestions. Store the prompt, source records, and Grok response together for audit.

FAQ

Which endpoint asks Grok through TwexAPI?

Use POST /v3/twitter/grok/ask on https://api.twexapi.io. Authenticate with a Bearer token and send JSON with required prompt and cookie; conversation_id, model, and proxy are optional.

Is Grok conversation_id the same as XChat conversation_id?

No. In Ask Grok, conversation_id identifies a Grok chat thread. XChat DM endpoints also use conversation_id for direct or group conversations. Store Grok IDs as grok_conversation_id to avoid mixing them.

What should I store after asking Grok?

Store the source job ID, source records, prompt, requested model, returned conversation_id, user_chat_item_id, agent_chat_item_id, message, reasoning, soft_stop, follow_up_suggestions, timestamp, and raw response. Store a credential reference for the cookie, not the cookie itself.

Grok is most useful in an analysis workflow when the prompt is tied to evidence you already collected: public posts from a search, user-authorized account data, or an internal report. The job is not just to ask a question. The job is to preserve what you asked, what source data you used, which authorized 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 source data or build the prompt for you. Collect permitted data first, build a concise prompt from that stored context, then call Ask Grok from your server.

Endpoint and Request Fields

Answer: Endpoint and Request Fields is implemented by calling the TwexAPI endpoint documented in this guide with a Bearer Token; batch or paginated requests reduce overhead to ~5 credits per call at 20+ QPS.

Use POST /v3/twitter/grok/ask to ask Grok from a server-side workflow.

FieldTypeRequiredNotes
promptstringYesUser prompt sent to Grok. Include source context and the task.
cookiestringYesX authentication cookie or auth_token. Keep it server-side.
conversation_idstring or nullNoExisting Grok conversation ID when you want to continue a Grok thread.
modelstring or nullNoOptional model ID. API default is grok-3-latest.
proxystring or nullNoOptional HTTP proxy for the session.

The conversation_id here belongs to Grok. Keep it distinct from identifiers used by other account workflows.

Basic Request

Answer: Basic Request means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

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

Answer: Build Prompts From Stored X Data means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

Keep prompts narrow. A useful prompt usually includes the task, source records, and output format.

1Task:
2Summarize the following X posts into customer questions and internal follow-up items.
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

Do 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

Answer: Python Grok Client means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

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 questions and internal follow-up items.",
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. Internal follow-up items",
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

Answer: Continuing a Grok Conversation means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

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. Store Grok IDs as grok_conversation_id in your database so they remain scoped to the analysis workflow.

Grok Analysis Workflow

Answer: Grok Analysis Workflow means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

  1. Collect permitted source data: Search public posts or fetch data from a user-authorized account with the relevant TwexAPI endpoint.
  2. Store the raw source: Keep tweet IDs, timestamps, authors, metrics, and other evidence needed for the analysis.
  3. Build a prompt: Include only the records needed for the task and state the output format.
  4. Ask Grok: Call POST /v3/twitter/grok/ask with prompt, cookie, and optional model.
  5. Store the result: Save message, conversation_id, chat item IDs, soft_stop, follow-up suggestions, prompt, and raw response.
  6. 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

Answer: Fields To Store means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

FieldWhy it matters
source_job_idConnects the Grok answer to the data extraction job.
promptShows exactly what was asked.
grok_conversation_idLets a later request continue the same Grok thread.
user_chat_item_idLinks the user prompt item when returned.
agent_chat_item_idLinks the Grok response item when returned.
messageFinal assistant answer.
reasoningOptional reasoning text returned by the API.
soft_stopShows whether the response soft-stopped.
follow_up_suggestionsSuggested next prompts from Grok.
modelRecords which model was requested.
asked_atTimestamp for audit and replay.
Raw response JSONLets you reprocess if your schema changes.

Do not store the full account cookie with Grok results. Store a credential reference instead.

Common Mistakes

Answer: Common Mistakes means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

  • Mixing up Grok conversation_id with XChat conversation_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

Answer: Wrap-up means using TwexAPI Bearer APIs on api.twexapi.io for this user case. A typical read uses 5 Credits (about $0.05 per 1,000), and qualifying paid plans publish 20+ QPS. As of 2026-10-14, official X API Post and User reads list at $5 and $10 per 1,000 resources; rate limits vary by endpoint.

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.