【AI大模型】Ollama+Qwen2,轻松搭建支持函数调用的聊天系统
前言本文介绍如何通过Ollama结合Qwen2搭建OpenAI格式的聊天API并与外部函数结合来拓展模型的更多功能。tools是OpenAI的Chat Completion API中的一个可选参数可用于提供函数调用规范function specifications。这样做的目的是使模型能够生成符合所提供的规范的函数参数格式。同时API 实际上不会执行任何函数调用。开发人员需要使用模型输出来执行函数调用。Ollama支持OpenAI格式API的tool参数在tool参数中如果functions提供了参数Qwen将会决定何时调用什么样的函数不过Ollama目前还不支持强制使用特定函数的参数tool_choice。注本文测试用例参考OpenAI cookbookhttps://cookbook.openai.com/examples/how_to_call_functions_with_chat_models本文主要包含以下三个部分模型部署使用Ollama和千问通过设置template部署支持Function call的聊天API接口。生成函数参数指定一组函数并使用 API 生成函数参数。调用具有模型生成的参数的函数通过实际执行具有模型生成的参数的函数来闭合循环。1、模型部署单模型文件下载使用ModelScope命令行工具下载单个模型本文使用Qwen2-7B的GGUF格式modelscope download--modelqwen/Qwen2-7B-Instruct-GGUF--local_dir.qwen2-7b-instruct-q5_k_m.ggufLinux环境使用Liunx用户可使用魔搭镜像环境安装【推荐】modelscope download--modelmodelscope/ollama-linux--local_dir./ollama-linux cd ollama-linux sudo chmod777./ollama-modelscope-install.sh./ollama-modelscope-install.sh启动Ollama服务ollama serve创建ModelFile复制模型路径创建名为“ModelFile”的meta文件其中设置template使之支持function call内容如下FROM/mnt/workspace/qwen2-7b-instruct-q5_k_m.gguf# set the temperature to 0.7 [higher is more creative, lower is more coherent]PARAMETER temperature0.7PARAMETER top_p0.8PARAMETER repeat_penalty1.05TEMPLATE{{ if .Messages }} {{- if or .System .Tools }}|im_start|system {{ .System }} {{- if .Tools }} # Tools You are provided with function signatures within tools/tools XML tags. You may call one or more functions to assist with the user query. Dont make assumptions about what values to plug into functions. Here are the available tools: tools{{- range .Tools }}{{ .Function }}{{- end }}/tools For each function call, return a JSON object with function name and arguments within tool_call/tool_call XML tags as follows: tool_call {name: function-name, arguments: args-json-object} /tool_call{{- end }}|im_end|{{- end }} {{- range .Messages }} {{- if eq .Role user }} |im_start|{{ .Role }} {{ .Content }}|im_end| {{- else if eq .Role assistant }} |im_start|{{ .Role }} {{- if .Content }} {{ .Content }} {{- end }} {{- if .ToolCalls }} tool_call {{ range .ToolCalls }}{name: {{ .Function.Name }}, arguments: {{ .Function.Arguments }}} {{ end }}/tool_call {{- end }}|im_end| {{- else if eq .Role tool }} |im_start|user tool_response {{ .Content }} /tool_response|im_end| {{- end }} {{- end }} |im_start|assistant {{ else }}{{ if .System }}|im_start|system {{ .System }}|im_end| {{ end }}{{ if .Prompt }}|im_start|user {{ .Prompt }}|im_end| {{ end }}|im_start|assistant {{ end }} 创建自定义模型使用ollama create命令创建自定义模型ollama create myqwen2--file./ModelFile运行模型ollama run myqwen22、生成函数参数安装依赖!pip install scipy--quiet !pip install tenacity--quiet !pip install tiktoken--quiet !pip install termcolor--quiet !pip install openai--quiet使用OpenAI的API格式调用本地部署的qwen2模型importjsonimportopenaifromtenacityimportretry,wait_random_exponential,stop_after_attemptfromtermcolorimportcolored MODELmyqwen2clientopenai.OpenAI(base_urlhttp://127.0.0.1:11434/v1,api_keyNone)实用工具首先让我们定义一些实用工具用于调用聊天完成 API 以及维护和跟踪对话状态。retry(waitwait_random_exponential(multiplier1,max40),stopstop_after_attempt(3))defchat_completion_request(messages,toolsNone,tool_choiceNone,modelMODEL):try:responseclient.chat.completions.create(modelmodel,messagesmessages,toolstools,tool_choicetool_choice,)returnresponseexceptExceptionase:print(Unable to generate ChatCompletion response)print(fException:{e})returnedefpretty_print_conversation(messages):role_to_color{system:red,user:green,assistant:blue,function:magenta,}formessageinmessages:ifmessage[role]system:print(colored(fsystem:{message[content]}\n,role_to_color[message[role]]))elifmessage[role]user:print(colored(fuser:{message[content]}\n,role_to_color[message[role]]))elifmessage[role]assistantandmessage.get(function_call):print(colored(fassistant:{message[function_call]}\n,role_to_color[message[role]]))elifmessage[role]assistantandnotmessage.get(function_call):print(colored(fassistant:{message[content]}\n,role_to_color[message[role]]))elifmessage[role]function:print(colored(ffunction ({message[name]}):{message[content]}\n,role_to_color[message[role]]))基本概念https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#basic-concepts这里假设了一个天气 API并设置了一些函数规范和它进行交互。将这些函数规范传递给 Chat API以便模型可以生成符合规范的函数参数。tools[{type:function,function:{name:get_current_weather,description:Get the current weather,parameters:{type:object,properties:{location:{type:string,description:The city and state, e.g. San Francisco, CA,},format:{type:string,enum:[celsius,fahrenheit],description:The temperature unit to use. Infer this from the users location.,},},required:[location,format],},}},{type:function,function:{name:get_n_day_weather_forecast,description:Get an N-day weather forecast,parameters:{type:object,properties:{location:{type:string,description:The city and state, e.g. San Francisco, CA,},format:{type:string,enum:[celsius,fahrenheit],description:The temperature unit to use. Infer this from the users location.,},num_days:{type:integer,description:The number of days to forecast,}},required:[location,format,num_days]},}},]如果我们向模型询问当前的天气情况它将会反问希望获取到进一步的更多的参数信息。messages[]messages.append({role:system,content:Dont make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.})messages.append({role:user,content:hi can you tell me whats the weather like today})chat_responsechat_completion_request(messages,toolstools)assistant_messagechat_response.choices[0].message messages.append(assistant_message)assistant_messageChatCompletionMessage(content‘Of course, I can help with that. To provide accurate information, could you please specify the city and state you are interested in?’, role‘assistant’, function_callNone, tool_callsNone)一旦我们通过对话提供缺失的参数信息模型就会为我们生成适当的函数参数。messages.append({role:user,content:Im in Glasgow, Scotland.})chat_responsechat_completion_request(messages,toolstools)assistant_messagechat_response.choices[0].message messages.append(assistant_message)assistant_messageChatCompletionMessage(content‘’, role‘assistant’, function_callNone, tool_calls[ChatCompletionMessageToolCall(id‘call_qq8e5z9w’, functionFunction(arguments‘{“location”:“Glasgow, Scotland”}’, name‘get_current_weather’), type‘function’)])通过不同的提示词我们可以让它反问不同的问题以获取函数参数信息。messages[]messages.append({role:system,content:Dont make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.})messages.append({role:user,content:can you tell me, what is the weather going to be like in Glasgow, Scotland in next x days})chat_responsechat_completion_request(messages,toolstools)assistant_messagechat_response.choices[0].message messages.append(assistant_message)assistant_messageChatCompletionMessage(content‘Sure, I can help with that. Could you please specify how many days ahead you want to know the weather forecast for Glasgow, Scotland?’, role‘assistant’, function_callNone, tool_callsNone)messages.append({role:user,content:5 days})chat_responsechat_completion_request(messages,toolstools)chat_response.choices[0]Choice(finish_reason‘stop’, index0, logprobsNone, messageChatCompletionMessage(content‘’, role‘assistant’, function_callNone, tool_calls[ChatCompletionMessageToolCall(id‘call_b7f3j7im’, functionFunction(arguments‘{“location”:“Glasgow, Scotland”,“num_days”:5}’, name‘get_n_day_weather_forecast’), type‘function’)]))并行函数调用https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#parallel-function-calling支持一次提问中并行调用多次函数messages[]messages.append({role:system,content:Dont make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.})messages.append({role:user,content:what is the weather going to be like in San Francisco and Glasgow over the next 4 days})chat_responsechat_completion_request(messages,toolstools,modelMODEL)assistant_messagechat_response.choices[0].message.tool_calls assistant_message[ChatCompletionMessageToolCall(id‘call_vei89rz3’, functionFunction(arguments‘{“location”:“San Francisco, CA”,“num_days”:4}’, name‘get_n_day_weather_forecast’), type‘function’),ChatCompletionMessageToolCall(id‘call_4lgoubee’, functionFunction(arguments‘{“location”:“Glasgow, UK”,“num_days”:4}’, name‘get_n_day_weather_forecast’), type‘function’)]使用模型生成函数https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#how-to-call-functions-with-model-generated-arguments在这个示例中演示如何执行输入由模型生成的函数并使用它来实现可以为我们解答有关数据库的问题的代理。本文使用Chinook 示例数据库https://www.sqlitetutorial.net/sqlite-sample-database/。指定执行 SQL 查询的函数https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#specifying-a-function-to-execute-sql-queries首先让我们定义一些有用的函数来从 SQLite 数据库中提取数据。importsqlite3 connsqlite3.connect(data/Chinook.db)print(Opened database successfully)importsqlite3 connsqlite3.connect(data/Chinook.db)print(Opened database successfully)现在可以使用这些实用函数来提取数据库模式的表示。database_schema_dictget_database_info(conn)database_schema_string\n.join([fTable:{table[table_name]}\nColumns:{, .join(table[column_names])}fortableindatabase_schema_dict])与之前一样我们将为希望 API 为其生成参数的函数定义一个函数规范。请注意我们正在将数据库模式插入到函数规范中。这对于模型了解这一点很重要。tools[{type:function,function:{name:ask_database,description:Use this function to answer user questions about music. Input should be a fully formed SQL query.,parameters:{type:object,properties:{query:{type:string,description:f SQL query extracting info to answer the users question. SQL should be written using this database schema:{database_schema_string}The query should be returned in plain text, not in JSON. ,}},required:[query],},}}]执行 SQL 查询https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#executing-sql-queries现在让我们实现实际执行数据库查询的函数。defask_database(conn,query):Function to query SQLite database with a provided SQL query.try:resultsstr(conn.execute(query).fetchall())exceptExceptionase:resultsfquery failed with error:{e}returnresults使用 Chat Completions API 调用函数的步骤https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#steps-to-invoke-a-function-call-using-chat-completions-api步骤 1向模型提示可能导致模型选择要使用的工具的内容。工具的描述例如函数名称和签名在“工具”列表中定义并在 API 调用中传递给模型。如果选择函数名称和参数将包含在响应中。步骤 2通过编程检查模型是否想要调用函数。如果是则继续执行步骤 3。步骤 3从响应中提取函数名称和参数使用参数调用该函数。将结果附加到消息中。步骤 4使用消息列表调用聊天完成 API 以获取响应。messages[{role:user,content:What is the name of the album with the most tracks?}]responseclient.chat.completions.create(modelmyqwen2,messagesmessages,toolstools,tool_choiceauto)# Append the message to messages listresponse_messageresponse.choices[0].message messages.append(response_message)print(response_message)ChatCompletionMessage(content‘’, role‘assistant’, function_callNone, tool_calls[ChatCompletionMessageToolCall(id‘call_23nnhlv6’, functionFunction(arguments‘{“query”:“SELECT Album.Title FROM Album JOIN Track ON Album.AlbumId Track.AlbumId GROUP BY Album.Title ORDER BY COUNT(*) DESC LIMIT 1”}’, name‘ask_database’), type‘function’)])# Step 2: determine if the response from the model includes a tool call.tool_callsresponse_message.tool_callsiftool_calls:# If true the model will return the name of the tool / function to call and the argument(s)tool_call_idtool_calls[0].idtool_function_nametool_calls[0].function.name tool_query_stringjson.loads(tool_calls[0].function.arguments)[query]# Step 3: Call the function and retrieve results. Append the results to the messages list.iftool_function_nameask_database:resultsask_database(conn,tool_query_string)messages.append({role:tool,tool_call_id:tool_call_id,name:tool_function_name,content:results})# Step 4: Invoke the chat completions API with the function response appended to the messages list# Note that messages with role tool must be a response to a preceding message with tool_callsmodel_response_with_function_callclient.chat.completions.create(modelmyqwen2,messagesmessages,)# get a new response from the model where it can see the function responseprint(model_response_with_function_call.choices[0].message.content)else:print(fError: function{tool_function_name}does not exist)else:# Model did not identify a function to call, result can be returned to the userprint(response_message.content)最后的最后感谢你们的阅读和喜欢作为一位在一线互联网行业奋斗多年的老兵我深知在这个瞬息万变的技术领域中持续学习和进步的重要性。为了帮助更多热爱技术、渴望成长的朋友我特别整理了一份涵盖大模型领域的宝贵资料集。这些资料不仅是我多年积累的心血结晶也是我在行业一线实战经验的总结。这些学习资料不仅深入浅出而且非常实用让大家系统而高效地掌握AI大模型的各个知识点。如果你愿意花时间沉下心来学习相信它们一定能为你提供实质性的帮助。这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】大模型知识脑图为了成为更好的 AI大模型 开发者这里为大家提供了总的路线图。它的用处就在于你可以按照上面的知识点去找对应的学习资源保证自己学得较为全面。经典书籍阅读阅读AI大模型经典书籍可以帮助读者提高技术水平开拓视野掌握核心技术提高解决问题的能力同时也可以借鉴他人的经验。对于想要深入学习AI大模型开发的读者来说阅读经典书籍是非常有必要的。实战案例光学理论是没用的要学会跟着一起敲要动手实操才能将自己的所学运用到实际当中去这时候可以搞点实战案例来学习。面试资料我们学习AI大模型必然是想找到高薪的工作下面这些面试题都是总结当前最新、最热、最高频的面试题并且每道题都有详细的答案面试前刷完这套面试题资料小小offer不在话下640套AI大模型报告合集这套包含640份报告的合集涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师还是对AI大模型感兴趣的爱好者这套报告合集都将为您提供宝贵的信息和启示。这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】

相关新闻

从“能用”到“好用”,国产低代码平台政企转型实录

从“能用”到“好用”,国产低代码平台政企转型实录

上周跟一个在国企信息中心干了十来年的朋友吃饭,他吐槽说现在上面催数字化催得紧,但手上那套老系统改一处牵全身,业务部门天天喊“这也不好用那也不顺手”。他苦笑说,我们这哪是转型,简直是“转圈”。这话挺戳心。很多…

2026/11/21 11:33:19 阅读更多 →
扫描版PDF优化处理工具 v

扫描版PDF优化处理工具 v

链接:https://pan.quark.cn/s/9bc69b67c496扫描版PDF,实际上就是一张张图片合并起来形成PDF,对于图片处理网上工具非常多,但要批处理图片,最好还是老马的ComicEnhancerPro,如果不嫌弃麻烦,对于扫…

2026/11/21 11:33:19 阅读更多 →
AutoClicker

AutoClicker

链接:https://pan.quark.cn/s/a516042783a1AI按照我的需求写出来的一个win版点击器,测试了一下,蛮好用,需要的拿去吧

2026/10/25 6:47:25 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/20 23:27:28 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/20 23:27:28 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/20 23:27:28 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/20 21:55:32 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/20 23:27:28 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/20 22:59:12 阅读更多 →

日新闻

周新闻

月新闻