当前位置:   article > 正文

langchain_ollama调用函数_ollamafunctions

ollamafunctions

为什么使用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"])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/832845
推荐阅读
相关标签
  

闽ICP备14008679号