如何通过OpenAI API借助gpt-4o获取新闻、天气等实时数据?
解决OpenAI API调用GPT-4o无法获取实时新闻/日期的问题
核心原因是ChatGPT Plus中的GPT-4o默认集成了联网插件支持,而直接通过OpenAI API调用时,模型本身没有实时联网和获取动态数据的能力,必须通过以下方式解决:
方案1:手动注入实时数据
- 日期处理:通过代码生成当前日期(如Python用
datetime.date.today().strftime("%Y-%m-%d")),将其作为系统提示或用户提示的一部分传入API请求,确保模型知晓当前日期。 - 新闻/天气数据:调用第三方公开API(如新闻聚合API、天气API)获取实时数据,把获取到的原始内容拼接进prompt,让GPT-4o基于这些数据整理成结构化的输出。
方案2:使用GPT-4o的工具调用(Function Calling)能力
通过定义获取新闻、天气的函数描述,让模型自动触发调用逻辑来获取实时数据,步骤如下:
- 在API请求中定义函数的名称、描述和参数要求;
- 当模型识别到需要实时数据时,会返回函数调用指令;
- 在代码中实现对应的函数逻辑(调用第三方API获取数据);
- 将获取到的数据回传给模型,让模型基于这些数据生成最终响应。
示例Python代码片段
import openai from datetime import date openai.api_key = "你的API密钥" # 获取并格式化当前日期 today_date = date.today().strftime("%Y年%m月%d日") # 定义工具函数描述 tools = [ { "type": "function", "function": { "name": "get_latest_news", "description": "获取指定地区的最新新闻资讯", "parameters": { "type": "object", "properties": { "region": { "type": "string", "description": "目标地区,如'北京'、'全球'" } }, "required": ["region"] } } }, { "type": "function", "function": { "name": "get_current_weather", "description": "获取指定城市的实时天气", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "目标城市名称" } }, "required": ["city"] } } } ] # 初始API请求 response = openai.ChatCompletion.create( model="gpt-4o", messages=[ {"role": "system", "content": f"当前日期为{today_date},你需要根据用户需求,调用指定工具获取实时数据后整理输出。"}, {"role": "user", "content": "给我整理今天北京的本地新闻、全球头条,以及北京的实时天气"} ], tools=tools, tool_choice="auto" ) # 处理工具调用请求 message = response.choices[0].message if message.tool_calls: # 执行对应工具函数(这里需要自行实现调用第三方API的逻辑) tool_results = [] for tool_call in message.tool_calls: function_name = tool_call.function.name args = eval(tool_call.function.arguments) if function_name == "get_latest_news": # 调用新闻API获取数据,示例返回模拟数据 news_result = '{"本地新闻": ["北京地铁12号线今日开通运营"], "全球头条": ["美联储宣布维持利率不变"]}' tool_results.append({ "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": news_result }) elif function_name == "get_current_weather": # 调用天气API获取数据,示例返回模拟数据 weather_result = '{"城市": "北京", "温度": "25℃", "天气": "晴"}' tool_results.append({ "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": weather_result }) # 将工具结果回传给模型生成最终响应 final_response = openai.ChatCompletion.create( model="gpt-4o", messages=[ {"role": "system", "content": f"当前日期为{today_date},你需要根据用户需求,调用指定工具获取实时数据后整理输出。"}, {"role": "user", "content": "给我整理今天北京的本地新闻、全球头条,以及北京的实时天气"}, message, *tool_results ] ) print(final_response.choices[0].message.content)
注意事项
- 第三方API需自行申请密钥,需遵守服务商的调用限制和使用条款;
- 工具调用会增加token消耗,需注意API额度使用情况;
- 需处理第三方API调用失败等异常场景,避免流程中断。
内容的提问来源于stack exchange,提问作者Silver Ringvee
相关产品推荐
相关产品推荐

