我正在使用Python向OpenAI发起一个简单的请求,询问棒球比赛的地点。
completion = openai.chat.completions.create( model="gpt-3.5-turbo", messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ])print (completion)
输出显示如下:
ChatCompletion(id='chatcmpl-9UgP85B0gYBjEAiYMcF3Ryt9Y3fdZ', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='The 2020 World Series was played at Globe Life Field in Arlington, Texas.', role='assistant', function_call=None, tool_calls=None))], created=1717099870, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=17, prompt_tokens=53, total_tokens=70))
但我希望它显示成这样:
{ "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "The 2020 World Series was played in Texas at Globe Life Field in Arlington.", "role": "assistant" }, "logprobs": null } ], "created": 1677664795, "id": "chatcmpl-7QyqpwdfhqwajicIEznoc6Q47XAyW", "model": "gpt-3.5-turbo-0613", "object": "chat.completion", "usage": { "completion_tokens": 17, "prompt_tokens": 57, "total_tokens": 74 }}
顺便提一下,我使用的是Python 3.12和Windows Terminal。
回答:
使用.model_dump_json()
completion = client.chat.completions.create( model="gpt-3.5-turbo", messages = [ {"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ])data = completion.model_dump_json()print(data)
输出:
{"id":"chatcmpl-9VGebGyeosYhcWW19F6f5B6lMFhpl","choices":[{"finish_reason":"stop","index":0,"logprobs":null,"message":{"content":"The World Series in 2020 was played at Globe Life Field in Arlington, Texas.","role":"assistant","function_call":null,"tool_calls":null}}],"created":1717239213,"model":"gpt-3.5-turbo-0125","object":"chat.completion","system_fingerprint":null,"usage":{"completion_tokens":18,"prompt_tokens":52,"total_tokens":70}}
如果需要美化输出,可以使用ident参数:
data = completion.model_dump_json(indent=3)print(data)
输出:
{ "id": "chatcmpl-9VGphVuZLKh2QuqT9vSAUdWCxoifg", "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas, home of the Texas Rangers.", "role": "assistant", "function_call": null, "tool_calls": null } } ], "created": 1717239901, "model": "gpt-3.5-turbo-0125", "object": "chat.completion", "system_fingerprint": null, "usage": { "completion_tokens": 23, "prompt_tokens": 52, "total_tokens": 75 }}