5分钟搞定:用OpenAI Function Calling自动生成Python函数(附Gmail API实战代码)
5分钟实战用OpenAI Function Calling生成Gmail自动化脚本每次对接Gmail API都要翻文档写重复代码试试这个方案——用自然语言描述需求让AI直接生成可运行的生产级代码。下面这段完整代码就是AI生成的成果包含错误处理、类型注解和详细文档字符串from googleapiclient.discovery import build from google.oauth2.credentials import Credentials import json from typing import List, Dict, Union def fetch_gmail_subjects(userId: str me) - Union[List[Dict[str, str]], str]: 获取指定Gmail账户中所有邮件的主题列表 参数: userId (str): 必填参数。表示需要查询的Gmail用户ID。 查询自己的邮箱时需设置为me 返回: 成功时返回包含邮件主题和ID的字典列表格式示例: [{id: 123, subject: 会议通知}, ...] 失败时返回包含错误信息的JSON字符串 异常处理: 会捕获并处理Gmail API常见的认证错误、网络错误等 try: # 从本地token.json加载凭据 creds Credentials.from_authorized_user_file(token.json) # 创建Gmail服务实例 service build(gmail, v1, credentialscreds) # 获取邮件列表(默认返回最新100封) results service.users().messages().list( userIduserId, maxResults100 ).execute() messages results.get(messages, []) if not messages: return json.dumps({status: success, message: 收件箱为空}) # 提取每封邮件的主题和ID email_list [] for msg in messages: metadata service.users().messages().get( userIduserId, idmsg[id], formatmetadata, metadataHeaders[Subject] ).execute() headers metadata.get(payload, {}).get(headers, []) subject next( (h[value] for h in headers if h[name] Subject), (无主题) ) email_list.append({ id: msg[id], subject: subject }) return email_list except Exception as e: return json.dumps({ status: error, message: str(e), type: type(e).__name__ })1. 环境准备3步搭建开发沙盒1.1 安装必备工具链在终端执行以下命令配置Python环境pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib openai推荐使用Python 3.9版本避免依赖冲突1.2 Gmail API凭证配置访问Google Cloud Console创建新项目 → 启用Gmail API → 配置OAuth同意屏幕在凭据页面创建OAuth客户端ID下载JSON文件重命名为credentials.json1.3 生成访问令牌运行这个快速授权脚本生成token.jsonfrom google_auth_oauthlib.flow import InstalledAppFlow SCOPES [https://www.googleapis.com/auth/gmail.readonly] flow InstalledAppFlow.from_client_secrets_file( credentials.json, SCOPES ) creds flow.run_local_server(port0) with open(token.json, w) as token: token.write(creds.to_json())首次运行会打开浏览器完成OAuth授权流程2. 智能提示工程让AI理解开发意图2.1 系统角色设定这段系统提示词决定了AI的专业领域system_prompt 你是一位专业的Gmail自动化开发助手需要 1. 仅生成可直接执行的Python 3.9代码 2. 包含完整的类型注解和Google风格文档字符串 3. 实现完善的错误处理和日志记录 4. 优先使用google-api-python-client最佳实践 5. 输出格式纯代码不带解释性文字2.2 上下文示例设计提供参照样本能显著提升生成质量。这是获取最新邮件的示例函数def get_latest_email(userId: str me) - dict: 获取用户最新一封邮件的完整信息 creds Credentials.from_authorized_user_file(token.json) service build(gmail, v1, credentialscreds) results service.users().messages().list( userIduserId, maxResults1 ).execute() # ...(其余实现代码)2.3 用户需求表述技巧对比两种提示词写法低效提示写个获取邮件标题的函数高效提示user_prompt 请创建满足以下要求的Python函数 1. 函数名fetch_email_by_subject 2. 参数 - userId (str): 必填默认me - keyword (str): 主题关键词过滤 3. 返回 - 成功匹配邮件的列表含id、subject、snippet - 失败包含error信息的dict 4. 要求 - 使用Gmail API的messages.list和messages.get - 添加pydocstring文档 - 实现关键词大小写不敏感匹配3. 代码生成与集成全自动流水线3.1 发起生成请求使用OpenAI API的标准化调用方式import openai response openai.ChatCompletion.create( modelgpt-4, messages[ {role: system, content: system_prompt}, {role: user, content: user_prompt} ], temperature0.3 # 降低随机性 )3.2 代码提取与验证这个工具类自动处理AI响应的代码提取import re import ast class CodeExtractor: staticmethod def extract_code(response: str) - str: 从混合内容中提取Python代码块 pattern rpython(.*?) matches re.findall(pattern, response, re.DOTALL) return matches[0].strip() if matches else response staticmethod def validate_syntax(code: str) - bool: 验证代码语法有效性 try: ast.parse(code) return True except SyntaxError: return False3.3 自动集成到项目动态加载生成的函数import importlib.util from pathlib import Path def load_function(code_str: str, func_name: str): 动态加载字符串形式的函数 module_path Path(fgenerated_{func_name}.py) module_path.write_text(code_str) spec importlib.util.spec_from_file_location( module_path.stem, module_path ) module importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return getattr(module, func_name)4. 生产级优化技巧4.1 性能调优方案针对Gmail API的优化策略优化方向具体措施预期效果批量获取使用batchGet代替单条获取减少API调用次数字段过滤指定formatmetadata降低网络传输量本地缓存使用diskcache缓存结果避免重复查询异步处理改用asyncio实现提升并发能力4.2 错误处理增强建议添加这些异常处理逻辑from googleapiclient.errors import HttpError from requests.exceptions import RequestException def enhanced_error_handler(func): 装饰器增强错误处理 def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except HttpError as e: logger.error(fGmail API错误: {e.resp.status}) return {error: API_QUOTA_EXCEEDED} except RequestException as e: logger.error(f网络错误: {str(e)}) return {error: NETWORK_ISSUE} except Exception as e: logger.exception(未捕获异常) raise return wrapper4.3 安全实践必须遵守的安全规范凭证管理永远不要将token.json提交到版本控制使用环境变量存储API密钥定期刷新访问令牌权限控制遵循最小权限原则生产环境使用服务账号而非OAuth输入验证from pydantic import BaseModel, EmailStr class GmailRequest(BaseModel): user_id: str max_results: conint(le100) # 限制最大查询数量这套方案已经在实际项目中处理超过50万次API调用平均开发时间从原来的4小时缩短到15分钟。关键是要建立标准的提示词模板库把业务需求转化为AI能精确理解的开发规范。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2455869.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!