在Python中使用ChatGPT插件的方法及上下文长度超限解决方案
解决方案:用OpenAI或Langchain调用ChatGPT插件并解决Token超限问题
可以直接通过OpenAI Python包或Langchain实现需求,核心问题是自动生成的插件函数描述过长导致上下文超限,以下是具体操作方案:
一、Langchain优化方案
1. 手动精简插件工具定义(推荐)
AIPluginTool会自动把插件的完整元数据(包括冗长的介绍、免责声明等)塞进函数描述,这是token超限的主要原因。你可以手动提取插件的核心API信息,自定义工具:
from langchain.tools import StructuredTool from langchain.chat_models import ChatOpenAI from langchain.agents import initialize_agent, AgentType import requests # 手动实现Scholar AI插件的核心查询功能 def search_scholar(query: str) -> str: # 调用Scholar AI的API(从插件的ai-plugin.json中提取的API地址) response = requests.post( "https://scholar-ai.net/api/search", json={"query": query} ) return response.json()["results"] # 自定义工具,只保留必要的描述 scholar_tool = StructuredTool.from_function( func=search_scholar, name="scholar_ai_search", description="用于查询学术文献信息,输入学术相关的问题或关键词,返回文献摘要和关键结论" ) llm = ChatOpenAI(temperature=0, streaming=True, model_name="gpt-3.5-turbo-16k-0613") agent_chain = initialize_agent( [scholar_tool], llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True ) agent_chain.run("What are the antiviral effects of Sillymarin?")
2. 切换更大上下文的模型
如果不想修改工具定义,可以直接使用支持更大上下文的模型,比如gpt-4-32k或gpt-4o,只需修改model_name参数:
llm = ChatOpenAI(temperature=0, streaming=True, model_name="gpt-4o")
二、直接使用OpenAI Python包实现
无需Langchain,直接调用OpenAI的函数调用接口,手动控制函数描述长度:
from openai import OpenAI import requests client = OpenAI() # 定义精简后的函数结构 functions = [ { "name": "scholar_ai_search", "description": "查询学术文献中关于特定主题的研究结论", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "要查询的学术主题或问题" } }, "required": ["query"] } } ] # 第一步:调用模型,触发函数调用 response = client.chat.completions.create( model="gpt-3.5-turbo-16k-0613", messages=[{"role": "user", "content": "What are the antiviral effects of Sillymarin?"}], functions=functions, function_call="auto" ) # 第二步:处理函数调用结果 if response.choices[0].finish_reason == "function_call": function_args = eval(response.choices[0].message.function_call.arguments) # 调用Scholar AI插件的API api_response = requests.post( "https://scholar-ai.net/api/search", json={"query": function_args["query"]} ) results = api_response.json()["results"] # 第三步:将函数返回结果喂给模型,生成最终回答 final_response = client.chat.completions.create( model="gpt-3.5-turbo-16k-0613", messages=[ {"role": "user", "content": "What are the antiviral effects of Sillymarin?"}, response.choices[0].message, { "role": "function", "name": "scholar_ai_search", "content": str(results) } ] ) print(final_response.choices[0].message.content)
关键注意事项
- 必须精简函数的
description字段,只保留核心功能说明,去掉插件的冗余介绍、版权信息等。 - 如果使用多个插件,要确保所有函数定义的总token数加上用户查询、系统提示不超过模型的上下文限制。
内容的提问来源于stack exchange,提问作者tobias
相关产品推荐
相关产品推荐

