使用本地LLM时,如何将OpenAI Functions转为LangChain PromptTemplate并生成类OpenAI格式输出?
可以实现:将OpenAI Functions转为LangChain PromptTemplate并输出OpenAI格式
完全可以做到,核心是把OpenAI Functions的定义转换成自然语言说明放进LangChain的PromptTemplate,同时明确要求本地LLM输出和OpenAI API一致的函数调用JSON格式。下面是具体实现方案和代码:
完整代码示例
from langchain.prompts import PromptTemplate # 替换成你实际使用的本地LLM类,比如LlamaCpp、GPT4All等 from langchain.llms import LlamaCpp # 你的OpenAI Functions定义 functions = [ { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location"], }, } ] # 把OpenAI Functions格式转成Prompt里的自然语言说明 def functions_to_prompt_text(functions): func_desc_list = [] for func in functions: params_info = func["parameters"]["properties"] required_params = func["parameters"].get("required", []) # 生成参数说明文本 param_lines = [] for param_name, param_details in params_info.items(): line = f"- {param_name}: {param_details['description']}(类型:{param_details['type']}" if param_name in required_params: line += ",必填" else: line += ",可选" if "enum" in param_details: line += f",可选值:{', '.join(param_details['enum'])}" line += ")" param_lines.append(line) # 拼接单个函数的完整说明 func_text = f"""函数名称:{func['name']} 函数描述:{func['description']} 参数说明: {'\n'.join(param_lines)}""" func_desc_list.append(func_text) return "\n\n".join(func_desc_list) # 构建LangChain PromptTemplate,明确输出格式要求 prompt_template = PromptTemplate( input_variables=["user_query"], template="""你可以调用以下工具来回答用户问题: {functions_text} 请严格按照以下JSON格式输出函数调用,不要添加任何额外的解释或文本: {{ "name": "要调用的函数名称", "parameters": {{ "参数名": "对应参数值" }} }} 用户问题:{user_query}""" ) # 初始化本地LLM(这里以LlamaCpp为例,替换成你的模型路径和配置) llm = LlamaCpp( model_path="./llama-2-7b-chat.ggmlv3.q4_0.bin", temperature=0.1, max_tokens=200, top_p=1.0 ) # 生成Prompt并调用本地LLM functions_text = functions_to_prompt_text(functions) final_prompt = prompt_template.format(user_query="北京现在的天气怎么样?", functions_text=functions_text) llm_response = llm(final_prompt) print("本地LLM输出结果:") print(llm_response)
关键说明
- 自定义的
functions_to_prompt_text函数负责把机器可读的OpenAI Functions结构,转换成本地LLM能理解的自然语言说明,避免模型看不懂结构化的JSON定义。 - PromptTemplate里明确强制了输出格式,要求必须是符合OpenAI API规范的函数调用JSON,确保输出结果可以直接复用OpenAI的后续处理逻辑。
- 只要你的本地LLM具备基本的JSON生成能力,就能输出符合要求的结果;如果模型输出不稳定,可以适当调整Prompt里的格式要求,或者增加示例来引导模型。
内容的提问来源于stack exchange,提问作者Vaibhav Arduino
相关产品推荐
相关产品推荐

