为什么使用ollama~ 因为适合本地部署; 为什么是langchain~因为目前集成了很多适合多场景的函数,便于开发.

langchain+ollama 函数调用

  1. 安装langchain和ollama
  2. 安装额外的依赖:

pip install langchain-experimental

调用函数

from langchain_experimental.llms.ollama_functions import OllamaFunctions

model=OllamaFunctions(modes="qwen:4b")

# 定义函数
def get_current_weather(location):
    return "Qing~~"
# 绑定这个函数
model = model.bind(
    functions=[
        {
            "name": "get_current_weather",
            "description": "获取本地的天气情况",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称,如:添加",
                    },
                },
                "required": ["location"],
            },
        }
    ],
    function_call={"name": "get_current_weather"},
)
result=model.invoke("北京的天气怎么样?")

# 返回结果中主要的是关于参数的调用
# AIMessage(content='', additional_kwargs={'function_call': {'name': 'get_current_weather', 'arguments': '{"location": "\\u5317\\u4eac"}'}}, id='run-15765e85-7657-4413-8571-d02d656fa8ff-0')

# 编写函数,解析函数和参数.然后调用自己的函数执行.

# 额,这里暂时没找到如何库里提供的方法来解析这个输出.
# 但是可以使用比较笨的办法进行调用~
result=json.loads(result.json())
args=eval(result["additional_kwargs"]["function_call"]['arguments'])
get_current_weather(args["location"])

希望哪天有缘~可以找到这个直接解析的方法,希望可以有伙伴给我留言

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐