当前位置:   article > 正文

langchain 学习笔记-FunctionCalling三种方式_langchain function call

langchain function call

ChatGPT 基于海量的训练数据生成答案,所以它无法回答训练数据中没有的信息或搜索信息

人们希望 ChatGPT 具有对话以外的各种功能,例如“我想管理我的待办事项列表”。

        函数调用是对此类请求的响应。 通过使用函数调用,ChatGPT 现在可以在生成答案时使用用户提供的函数

例如,如果要添加一个查看天气的函数,可以定义一个确定天气预报 API 的函数。下面是示意图

函数

我们定义了一个获取天气函数 。这是一个常规的python 函数。

  1. def weather_function(location):
  2. match location:
  3. case "无锡" | "wuxi":
  4. weather = "晴天"
  5. case "苏州"| "suzhou":
  6. weather = "多云"
  7. case "常州" | "changzhou":
  8. weather = "雨"
  9. case _ :
  10. weather = "不清楚"
  11. weather_answer = [
  12. {"天气": weather}
  13. ]
  14. return json.dumps(weather_answer)

例-1--openAI function calling

  1. from openai import OpenAI
  2. import json
  3. client = OpenAI(
  4. api_key="sk-xxxxxx",
  5. base_url="https://api.chatanywhere.tech/v1"
  6. )
  7. def weather_function(location):
  8. match location:
  9. case "无锡" | "wuxi":
  10. weather = "晴天"
  11. case "苏州"| "suzhou":
  12. weather = "多云"
  13. case "常州" | "changzhou":
  14. weather = "雨"
  15. case _ :
  16. weather = "不清楚"
  17. weather_answer = [
  18. {"天气": weather}
  19. ]
  20. return json.dumps(weather_answer)
  21. functions = [
  22. {
  23. "name": "weather",
  24. "description": "了解天气",
  25. "parameters": {
  26. "type": "object",
  27. "properties": {
  28. "location": {
  29. "type": "string",
  30. "description": "输入您想要了解天气的位置。 示例:东京",
  31. },
  32. },
  33. "required": ["location"],
  34. },
  35. }
  36. ]
  37. messages = [
  38. {
  39. "role": "system",
  40. "content": "You are a useful assistant."
  41. },
  42. {
  43. "role": "user",
  44. "content": "无锡天气怎么样?"
  45. },
  46. ]
  47. print(messages[1]["content"])
  48. def role_function_conversation(message):
  49. response = client.chat.completions.create(
  50. model="gpt-3.5-turbo-0613",
  51. messages = message,
  52. temperature=0,
  53. functions= functions,
  54. function_call="auto",
  55. )
  56. message = response.choices[0].message.content
  57. print(message)
  58. completion = client.chat.completions.create(
  59. model="gpt-3.5-turbo",
  60. messages=messages,
  61. functions = functions,
  62. function_call = {
  63. "name": functions[0]["name"]
  64. }
  65. )
  66. message=completion.choices[0].message
  67. if(message.function_call):
  68. function_name = message.function_call.name
  69. arguments = json.loads(message.function_call.arguments)
  70. if (function_name == "weather"):
  71. weatherNow=weather_function(location=arguments.get('location'))
  72. messages.append(message)
  73. messages.append({"role": "function", "name": "weather", "content": weatherNow})
  74. #print(messages)
  75. role_function_conversation(messages)

从上面的程序看,功能调用被分成两段,分别访问两次大模型,第一次根据functions 模板获取函数的参数location,第二次真正调用 weather_function函数。然后将调用的结果交给大模型生成输出。

例-2 langchain Agent方式

这个程序使用Langchain Agent 方式调用函数,简约了许多。

  1. import json
  2. import os
  3. from langchain_openai import ChatOpenAI
  4. from langchain.agents import initialize_agent, Tool
  5. from langchain.agents.mrkl import prompt
  6. os.environ['OPENAI_API_KEY'] ="sk-xxxxx"
  7. os.environ['OPENAI_BASE_URL'] ="https://api.chatanywhere.tech/v1"
  8. def weather_function(location):
  9. match location:
  10. case "无锡" | "wuxi":
  11. weather = "晴天"
  12. case "苏州"| "suzhou":
  13. weather = "多云"
  14. case "常州" | "changzhou":
  15. weather = "雨"
  16. case _ :
  17. weather = "不清楚"
  18. weather_answer = [
  19. {"天气": weather}
  20. ]
  21. return json.dumps(weather_answer)
  22. def lang_chain_agent(text):
  23. llm = ChatOpenAI(model_name="gpt-3.5-turbo",base_url="https://api.chatanywhere.tech/v1")
  24. tools = [
  25. Tool(
  26. name = "Weather",
  27. func=weather_function,
  28. description="输入你希望了解天气的位置,例如 无锡",
  29. )
  30. ]
  31. agent = initialize_agent(
  32. tools,
  33. llm,
  34. agent="zero-shot-react-description",
  35. agent_kwargs=dict(suffix='Answer should be in chinese.' + prompt.SUFFIX),
  36. verbose=True,
  37. return_intermediate_steps=True)
  38. response = agent({"input": text})
  39. return response
  40. lang_chain_agent("常州天气如何?")

例-3 langchain-functioncall方式

这个程序利用langchain 实现函数调用

  1. import os
  2. import json
  3. from langchain.schema import (
  4. HumanMessage,
  5. FunctionMessage
  6. )
  7. from langchain_openai import ChatOpenAI
  8. os.environ['OPENAI_API_KEY'] ="sk-xxxxxxxx"
  9. os.environ['OPENAI_BASE_URL'] ="https://api.chatanywhere.tech/v1"
  10. def weather_function(location):
  11. match location:
  12. case "无锡" | "wuxi":
  13. weather = "晴天"
  14. case "苏州"| "suzhou":
  15. weather = "多云"
  16. case "常州" | "changzhou":
  17. weather = "雨"
  18. case _ :
  19. weather = "不清楚"
  20. weather_answer = [
  21. {"天气": weather}
  22. ]
  23. return json.dumps(weather_answer)
  24. def lang_chain_with_function_calling(text):
  25. functions = [
  26. {
  27. "name": "weather",
  28. "description": "了解天气",
  29. "parameters": {
  30. "type": "object",
  31. "properties": {
  32. "location": {
  33. "type": "string",
  34. "description": "输入您想要了解天气的位置。 示例:东京",
  35. },
  36. },
  37. "required": ["location"],
  38. },
  39. }
  40. ]
  41. messages=[HumanMessage(content=text)]
  42. llm = ChatOpenAI(model_name="gpt-3.5-turbo",base_url="https://api.chatanywhere.tech/v1", temperature=0)
  43. message = llm.predict_messages(
  44. messages, functions=functions
  45. )
  46. if message.additional_kwargs:
  47. function_name = message.additional_kwargs["function_call"]["name"]
  48. arguments = json.loads(message.additional_kwargs["function_call"]["arguments"])
  49. function_response = weather_function(
  50. location=arguments.get("location"),
  51. )
  52. function_message = FunctionMessage(name=function_name, content=function_response)
  53. messages.append(function_message)
  54. second_response = llm.predict_messages(
  55. messages=messages, functions=functions
  56. )
  57. return "AI的回答: " + second_response.content
  58. else:
  59. return "AI的回答: " + message.content
  60. print(lang_chain_with_function_calling("无锡的天气怎么样?"))

结束语

这里介绍了三种大模型函数调用的方法。还可以调用多个函数,比如如果要使用大模型实现“如果天黑了,就关上灯” ,我觉得要调用两个函数

CheckDarkness 函数

判断是否天黑。

LightControl 函数

控制灯光。

下一次来研究怎么实现吧!

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

闽ICP备14008679号