grok-2-image-latest
但是请求出错,控制台已经能看到这模型了
grok-2-image-latest
但是请求出错,控制台已经能看到这模型了
我去看看
还不上grok 3 api…
Grok3 API 还没好啊,虽然现在网页端也够我用了,而且体验做得很好。
请求404
已经可以用了
要使用 image 接口 现在的聊天体默认 chat 接口调用就会404
https://docs.x.ai/docs/guides/image-generations#generate-image
curl -X 'POST' https://api.x.ai/v1/images/generations \
-H 'accept: application/json' \
-H 'Authorization: Bearer <API_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"model": "grok-2-image",
"prompt": "A cat in a tree"
}'
什么时候出3啊!
感谢大佬!难怪我试了一直有问题
import os
from openai import OpenAI
XAI_API_KEY = os.getenv("XAI_API_KEY")
client = OpenAI(base_url="https://api.x.ai/v1", api_key=XAI_API_KEY)
response = client.images.generate(
model="grok-2-image",
prompt="A cat in a tree"
n=4
)
for image in response.data:
print(image.url)
openai 调用
为什么我在one api 里调用失败
可以丢 dify 建一个工作流 ,里面转一下,调用 dify 的 api。
import requests
import json
import os
import sys
import time
import base64
import tkinter as tk
from tkinter import filedialog, messagebox
from pathlib import Path
# 设置代理(如需要)
os.environ.update({'http_proxy': 'http://127.0.0.1:1081', 'https_proxy': 'http://127.0.0.1:1081'})
# 请在此处填入您的 Grok API 密钥
API_KEY = "*" # 替换为您的实际 Grok API 密钥
def get_text_prompt(default_prompt="A cat in a tree"):
"""获取用户输入的文本提示词,优化UI样式"""
root = tk.Tk()
root.title("输入生图提示词")
# 设置窗口大小和位置
window_width = 500
window_height = 180
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
center_x = int(screen_width/2 - window_width/2)
center_y = int(screen_height/2 - window_height/2)
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
# 创建框架来包含所有元素
main_frame = tk.Frame(root, padx=10, pady=10)
main_frame.pack(fill=tk.BOTH, expand=True)
# 输入框,减少内边距
text_entry = tk.Text(main_frame, height=5, width=50, padx=5, pady=5)
text_entry.pack(fill=tk.BOTH, expand=True)
text_entry.insert("1.0", default_prompt)
# 创建底部按钮框架
button_frame = tk.Frame(main_frame)
button_frame.pack(fill=tk.X, pady=(5, 0))
prompt_result = {"text": ""}
def on_submit():
prompt_result["text"] = text_entry.get("1.0", "end-1c")
root.destroy()
# 按钮放在右侧
submit_button = tk.Button(button_frame, text="提交", command=on_submit, width=10)
submit_button.pack(side=tk.RIGHT)
# 聚焦到文本框并设置光标位置
text_entry.focus_set()
text_entry.mark_set("insert", "end")
# 绑定回车键提交(按Ctrl+Enter提交)
def on_ctrl_enter(event):
on_submit()
return "break" # 阻止默认行为
text_entry.bind("<Control-Return>", on_ctrl_enter)
root.mainloop()
return prompt_result["text"]
def save_image_from_url(url, output_path):
"""从URL下载图片并保存到指定路径"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return True
except Exception as e:
print(f"保存图片时出错: {e}")
return False
def main():
# 获取当前脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 创建输出目录
output_dir = os.path.join(script_dir, "Grok Images")
os.makedirs(output_dir, exist_ok=True)
timestamp = int(time.time())
# 获取用户输入的提示词
prompt_text = get_text_prompt()
if not prompt_text.strip():
print("未输入提示词,退出程序。")
return
print(f"使用提示词: {prompt_text}")
# 构建请求数据
request_data = {
"model": "grok-2-image",
"prompt": prompt_text
}
# 生成请求ID用于文件命名
request_id = f"grok_image_{timestamp}"
# 发送请求
print("正在发送请求到 Grok API...")
try:
api_url = 'https://api.x.ai/v1/images/generations'
response = requests.post(
api_url,
headers={
'accept': 'application/json',
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
},
json=request_data,
proxies={
'http': 'http://127.0.0.1:1081',
'https': 'http://127.0.0.1:1081'
}
)
# 保存请求数据用于调试
debug_request_file = os.path.join(output_dir, f"{request_id}_request.json")
with open(debug_request_file, 'w', encoding='utf-8') as f:
json.dump(request_data, f, ensure_ascii=False, indent=2)
# 检查响应状态
if response.status_code != 200:
print(f"API返回错误: {response.status_code}")
print(f"错误详情: {response.text}")
# 保存错误响应
error_file = os.path.join(output_dir, f"{request_id}_error.json")
with open(error_file, 'w', encoding='utf-8') as f:
try:
error_json = response.json()
json.dump(error_json, f, ensure_ascii=False, indent=2)
except:
f.write(response.text)
print(f"错误信息已保存到: {error_file}")
sys.exit(1)
# 解析响应
result = response.json()
# 保存完整响应到 JSON 文件
response_file = os.path.join(output_dir, f"{request_id}_response.json")
with open(response_file, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
# 尝试提取和保存图片
try:
if "data" in result and len(result["data"]) > 0:
image_count = 0
for i, image_data in enumerate(result["data"]):
if "url" in image_data:
image_count += 1
image_url = image_data["url"]
# 保存图片,使用与请求/响应文件相同的命名格式
image_file = os.path.join(output_dir, f"{request_id}_generated_{image_count}.png")
if save_image_from_url(image_url, image_file):
print(f"生成成功!图片 {image_count} 已保存到: {image_file}")
else:
print(f"图片 {image_count} 下载失败")
if image_count == 0:
print("响应中未找到图片URL,请检查响应JSON文件")
else:
print(f"共保存了 {image_count} 张生成的图片")
else:
print("响应中未找到data字段或为空,请检查响应JSON文件")
# 打开保存目录
print(f"所有文件已存储到: {output_dir}")
os.startfile(output_dir)
except Exception as e:
print(f"处理响应时出错: {e}")
print("请查看保存的 JSON 文件以了解完整响应结构")
except requests.exceptions.RequestException as e:
print(f"请求错误: {str(e)}")
sys.exit(1)
except Exception as e:
print(f"发生错误: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()
佬儿是直接在nextchat里修改接口为https://api.x.ai/v1/images/generations吗,我测试好像不可以呀
每天都在等3 结果憋出个文生图
话说,送的150$有说过可以用grok3的API吗,还是只能用2?
不太清楚,现在感觉传的都不太靠谱
我是直接用python试了试
我用的是cherry改成这样后也不行诶,不知道咋回事了