Fix xAI API: migrate to Agent Tools API

xAI deprecated search_parameters - now requires Agent Tools API:
- Changed endpoint from /v1/chat/completions to /v1/responses
- Changed from messages array to input array format
- Changed from search_parameters to tools: [{"type": "x_search"}]
- Updated model selection to grok-4-1-fast (required for x_search tool)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Matt Van Horn
2026-01-23 20:02:43 -08:00
parent a0bcfc9514
commit 891307f6c2
2 changed files with 11 additions and 18 deletions
+3 -3
View File
@@ -9,11 +9,11 @@ from . import cache, http
OPENAI_MODELS_URL = "https://api.openai.com/v1/models"
OPENAI_FALLBACK_MODELS = ["gpt-5.2", "gpt-5.1", "gpt-5", "gpt-4o"]
# xAI API
# xAI API - Agent Tools API requires grok-4 family
XAI_MODELS_URL = "https://api.x.ai/v1/models"
XAI_ALIASES = {
"latest": "grok-3",
"stable": "grok-3",
"latest": "grok-4-1-fast", # Required for x_search tool
"stable": "grok-4-1-fast",
}
+8 -15
View File
@@ -13,8 +13,8 @@ def _log_error(msg: str):
sys.stderr.write(f"[X ERROR] {msg}\n")
sys.stderr.flush()
# xAI uses chat completions endpoint
XAI_CHAT_URL = "https://api.x.ai/v1/chat/completions"
# xAI uses responses endpoint with Agent Tools API
XAI_RESPONSES_URL = "https://api.x.ai/v1/responses"
# Depth configurations: (min, max) posts to request
DEPTH_CONFIG = {
@@ -91,14 +91,13 @@ def search_x(
# Adjust timeout based on depth
timeout = 60 if depth == "quick" else 90 if depth == "default" else 120
# Use chat completions format with search enabled
# Use Agent Tools API with x_search tool
payload = {
"model": model,
"messages": [
{
"role": "system",
"content": "You are a research assistant with access to real-time X (Twitter) data. Search X and return structured results."
},
"tools": [
{"type": "x_search"}
],
"input": [
{
"role": "user",
"content": X_SEARCH_PROMPT.format(
@@ -110,15 +109,9 @@ def search_x(
),
}
],
"search_parameters": {
"mode": "auto",
"sources": [{"type": "x"}],
"from_date": from_date,
"to_date": to_date,
},
}
return http.post(XAI_CHAT_URL, payload, headers=headers, timeout=timeout)
return http.post(XAI_RESPONSES_URL, payload, headers=headers, timeout=timeout)
def parse_x_response(response: Dict[str, Any]) -> List[Dict[str, Any]]: