开源模型应用落地-工具使用篇-Spring AI-Function Call(八)

这篇具有很好参考价值的文章主要介绍了开源模型应用落地-工具使用篇-Spring AI-Function Call(八)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

​​​​​​​一、前言

    通过“开源模型应用落地-工具使用篇-Spring AI(七)-CSDN博客”文章的学习,已经掌握了如何通过Spring AI集成OpenAI和Ollama系列的模型,现在将通过进一步的学习,让Spring AI集成大语言模型更高阶的用法,使得我们能完成更复杂的需求。


二、术语

2.1、Spring AI

  是 Spring 生态系统的一个新项目,它简化了 Java 中 AI 应用程序的创建。它提供以下功能:

  • 支持所有主要模型提供商,例如 OpenAI、Microsoft、Amazon、Google 和 Huggingface。
  • 支持的模型类型包括“聊天”和“文本到图像”,还有更多模型类型正在开发中。
  • 跨 AI 提供商的可移植 API,用于聊天和嵌入模型。
  • 支持同步和流 API 选项。
  • 支持下拉访问模型特定功能。
  • AI 模型输出到 POJO 的映射。

2.2、Function Call

     是 GPT API 中的一项新功能。它可以让开发者在调用 GPT系列模型时,描述函数并让模型智能地输出一个包含调用这些函数所需参数的 JSON 对象。这种功能可以更可靠地将 GPT 的能力与外部工具和 API 进行连接。

    简单来说就是开放了自定义插件的接口,通过接入外部工具,增强模型的能力。

Spring AI集成Function Call:

Function Calling :: Spring AI Reference

开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring


三、前置条件

3.1、JDK 17+

    下载地址:Java Downloads | Oracle

    开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring

  

3.2、创建Maven项目

    SpringBoot版本为3.2.3

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

3.3、导入Maven依赖包

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
</dependency>

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-core</artifactId>
	<version>5.8.24</version>
</dependency>

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
	<version>0.8.0</version>
</dependency>

3.4、 科学上网的软件


四、技术实现

4.1、新增配置

spring:
  ai:
    openai:
      api-key: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
      chat:
        options:
          model: gpt-3.5-turbo
          temperature: 0.45
          max_tokens: 4096
          top-p: 0.9

  PS:

  1.   openai要替换自己的api-key
  2.   模型参数根据实际情况调整

 4.2、新增本地方法类(用于本地回调的function)

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;

@Slf4j
public class WeatherService implements Function<WeatherService.Request, WeatherService.Response> {

    /**
     * Weather Function request.
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonClassDescription("Weather API request")
    public record Request(@JsonProperty(required = true,
            value = "location") @JsonPropertyDescription("The city and state e.g.广州") String location) {
    }


    /**
     * Weather Function response.
     */
    public record Response(String weather) {
    }

    @Override
    public WeatherService.Response apply(WeatherService.Request request) {
        log.info("location: {}", request.location);
        String weather = "";
        if (request.location().contains("广州")) {
            weather = "小雨转阴 13~19°C";
        } else if (request.location().contains("深圳")) {
            weather = "阴 15~26°C";
        } else {
            weather = "热到中暑 99~100°C";
        }

        return new WeatherService.Response(weather);
    }
}

 4.3、新增配置类

import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

import java.util.function.Function;


@Configuration
public class FunctionConfig {


    @Bean
    public FunctionCallback weatherFunctionInfo() {
        return new FunctionCallbackWrapper<WeatherService.Request, WeatherService.Response>("currentWeather", // (1) function name
                "Get the weather in location", // (2) function description
                new WeatherService()); // function code
    }
}

 4.4、新增Controller类

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class OpenaiTestController {
    @Autowired
    private OpenAiChatClient openAiChatClient;


    @RequestMapping("/function_call")
    public String function_call(){
        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

        String userPrompt = "广州的天气如何?";
        Message userMessage = new UserMessage(userPrompt);

        Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "你是一个有用的人工智能助手"));

        Prompt prompt = new Prompt(List.of(userMessage, systemMessage), OpenAiChatOptions.builder().withFunction("currentWeather").build());

        List<Generation> response = openAiChatClient.call(prompt).getResults();

        String result = "";

        for (Generation generation : response){
            String content = generation.getOutput().getContent();
            result += content;
        }

        return result;

    }
}

五、测试

调用结果:

  浏览器输出:

开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring

  idea输出:

开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring


六、附带说明

6.1、流式模式不支持Function Call

开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring

6.2、更多的模型参数配置

OpenAI Chat :: Spring AI Reference

开源模型应用落地-工具使用篇-Spring AI-Function Call(八),开源大语言模型-新手试炼,深度学习,spring

6.3、qwen系列模型如何支持function call

 通过vllm启动兼容openai接口的api_server,命令如下:

python -m vllm.entrypoints.openai.api_server --served-model-name Qwen1.5-7B-Chat --model Qwen/Qwen1.5-7B-Chat 

   详细教程参见:

  使用以下代码进行测试:文章来源地址https://www.toymoban.com/news/detail-839637.html

# Reference: https://openai.com/blog/function-calling-and-other-api-updates
import json
from pprint import pprint

import openai

# To start an OpenAI-like Qwen server, use the following commands:
#   git clone https://github.com/QwenLM/Qwen-7B;
#   cd Qwen-7B;
#   pip install fastapi uvicorn openai pydantic sse_starlette;
#   python openai_api.py;
#
# Then configure the api_base and api_key in your client:
openai.api_base = 'http://localhost:8000/v1'
openai.api_key = 'none'


def call_qwen(messages, functions=None):
    print('input:')
    pprint(messages, indent=2)
    if functions:
        response = openai.ChatCompletion.create(model='Qwen',
                                                messages=messages,
                                                functions=functions)
    else:
        response = openai.ChatCompletion.create(model='Qwen',
                                                messages=messages)
    response = response.choices[0]['message']
    response = json.loads(json.dumps(response,
                                     ensure_ascii=False))  # fix zh rendering
    print('output:')
    pprint(response, indent=2)
    print()
    return response


def test_1():
    messages = [{'role': 'user', 'content': '你好'}]
    call_qwen(messages)
    messages.append({'role': 'assistant', 'content': '你好!很高兴为你提供帮助。'})

    messages.append({
        'role': 'user',
        'content': '给我讲一个年轻人奋斗创业最终取得成功的故事。故事只能有一句话。'
    })
    call_qwen(messages)
    messages.append({
        'role':
        'assistant',
        'content':
        '故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。李明想要成为一名成功的企业家。……',
    })

    messages.append({'role': 'user', 'content': '给这个故事起一个标题'})
    call_qwen(messages)


def test_2():
    functions = [
        {
            'name_for_human':
            '谷歌搜索',
            'name_for_model':
            'google_search',
            'description_for_model':
            '谷歌搜索是一个通用搜索引擎,可用于访问互联网、查询百科知识、了解时事新闻等。' +
            ' Format the arguments as a JSON object.',
            'parameters': [{
                'name': 'search_query',
                'description': '搜索关键词或短语',
                'required': True,
                'schema': {
                    'type': 'string'
                },
            }],
        },
        {
            'name_for_human':
            '文生图',
            'name_for_model':
            'image_gen',
            'description_for_model':
            '文生图是一个AI绘画(图像生成)服务,输入文本描述,返回根据文本作画得到的图片的URL。' +
            ' Format the arguments as a JSON object.',
            'parameters': [{
                'name': 'prompt',
                'description': '英文关键词,描述了希望图像具有什么内容',
                'required': True,
                'schema': {
                    'type': 'string'
                },
            }],
        },
    ]

    messages = [{'role': 'user', 'content': '(请不要调用工具)\n\n你好'}]
    call_qwen(messages, functions)
    messages.append({
        'role': 'assistant',
        'content': '你好!很高兴见到你。有什么我可以帮忙的吗?'
    }, )

    messages.append({'role': 'user', 'content': '搜索一下谁是周杰伦'})
    call_qwen(messages, functions)
    messages.append({
        'role': 'assistant',
        'content': '我应该使用Google搜索查找相关信息。',
        'function_call': {
            'name': 'google_search',
            'arguments': '{"search_query": "周杰伦"}',
        },
    })

    messages.append({
        'role': 'function',
        'name': 'google_search',
        'content': 'Jay Chou is a Taiwanese singer.',
    })
    call_qwen(messages, functions)
    messages.append(
        {
            'role': 'assistant',
            'content': '周杰伦(Jay Chou)是一位来自台湾的歌手。',
        }, )

    messages.append({'role': 'user', 'content': '搜索一下他老婆是谁'})
    call_qwen(messages, functions)
    messages.append({
        'role': 'assistant',
        'content': '我应该使用Google搜索查找相关信息。',
        'function_call': {
            'name': 'google_search',
            'arguments': '{"search_query": "周杰伦 老婆"}',
        },
    })

    messages.append({
        'role': 'function',
        'name': 'google_search',
        'content': 'Hannah Quinlivan'
    })
    call_qwen(messages, functions)
    messages.append(
        {
            'role': 'assistant',
            'content': '周杰伦的老婆是Hannah Quinlivan。',
        }, )

    messages.append({'role': 'user', 'content': '用文生图工具画个可爱的小猫吧,最好是黑猫'})
    call_qwen(messages, functions)
    messages.append({
        'role': 'assistant',
        'content': '我应该使用文生图API来生成一张可爱的小猫图片。',
        'function_call': {
            'name': 'image_gen',
            'arguments': '{"prompt": "cute black cat"}',
        },
    })

    messages.append({
        'role':
        'function',
        'name':
        'image_gen',
        'content':
        '{"image_url": "https://image.pollinations.ai/prompt/cute%20black%20cat"}',
    })
    call_qwen(messages, functions)


def test_3():
    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'],
        },
    }]

    messages = [{
        'role': 'user',
        # Note: The current version of Qwen-7B-Chat (as of 2023.08) performs okay with Chinese tool-use prompts,
        # but performs terribly when it comes to English tool-use prompts, due to a mistake in data collecting.
        'content': '波士顿天气如何?',
    }]
    call_qwen(messages, functions)
    messages.append(
        {
            'role': 'assistant',
            'content': None,
            'function_call': {
                'name': 'get_current_weather',
                'arguments': '{"location": "Boston, MA"}',
            },
        }, )

    messages.append({
        'role':
        'function',
        'name':
        'get_current_weather',
        'content':
        '{"temperature": "22", "unit": "celsius", "description": "Sunny"}',
    })
    call_qwen(messages, functions)


def test_4():
    from langchain.agents import AgentType, initialize_agent, load_tools
    from langchain.chat_models import ChatOpenAI

    llm = ChatOpenAI(
        model_name='Qwen',
        openai_api_base='http://localhost:8000/v1',
        openai_api_key='EMPTY',
        streaming=False,
    )
    tools = load_tools(['arxiv'], )
    agent_chain = initialize_agent(
        tools,
        llm,
        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True,
    )
    # TODO: The performance is okay with Chinese prompts, but not so good when it comes to English.
    agent_chain.run('查一下论文 1605.08386 的信息')


if __name__ == '__main__':
    print('### Test Case 1 - No Function Calling (普通问答、无函数调用) ###')
    test_1()
    print('### Test Case 2 - Use Qwen-Style Functions (函数调用,千问格式) ###')
    test_2()
    print('### Test Case 3 - Use GPT-Style Functions (函数调用,GPT格式) ###')
    test_3()
    print('### Test Case 4 - Use LangChain (接入Langchain) ###')
    test_4()

到了这里,关于开源模型应用落地-工具使用篇-Spring AI-Function Call(八)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 开源模型应用落地-工具使用篇-向量数据库(三)

    一、前言     通过学习\\\"开源模型应用落地\\\"系列文章,我们成功地建立了一个完整可实施的AI交付流程。现在,我们要引入向量数据库,作为我们AI服务的二级缓存。本文将详细介绍如何使用Milvus Lite来为我们的AI服务部署一个前置缓存。 二、术语 2.1、向量数据库     向量数

    2024年02月19日
    浏览(43)
  • 开源模型应用落地-总述

            在当今社会,实际应用比纯粹理解原理和概念更为重要。即使您对某个领域的原理和概念有深入的理解,但如果无法将其应用于实际场景并受制于各种客观条件,那么与其一开始就过于深入,不如先从基础开始,实际操作后再逐步深入探索。         在这种实践至上

    2024年03月14日
    浏览(48)
  • 开源模型应用落地-业务优化篇(六)

    一、前言     经过线程池优化、请求排队和服务实例水平扩容等措施,整个AI服务链路的性能得到了显著地提升。但是,作为追求卓越的大家,绝不会止步于此。我们的目标是在降低成本和提高效率方面不断努力,追求最佳结果。如果你们在实施AI项目方面有经验,那一定会

    2024年02月22日
    浏览(41)
  • 开源模型应用落地-业务整合篇(四)

    一、前言     通过学习第三篇文章,我们已经成功地建立了IM与AI服务之间的数据链路。然而,我们目前面临一个紧迫需要解决的安全性问题,即非法用户可能会通过获取WebSocket的连接信息,顺利地连接到我们的服务。这不仅占用了大量的无效连接和资源,还对业务数据带来

    2024年01月24日
    浏览(37)
  • 开源模型应用落地-业务整合篇(一)

    一、前言     经过对qwen-7b-chat的部署以及与vllm的推理加速的整合,我们成功构建了一套高性能、高可靠、高安全的AI服务能力。现在,我们将着手整合具体的业务场景,以实现完整可落地的功能交付。     作为上游部门,通常会采用最常用的方式来接入下游服务。为了调用

    2024年01月20日
    浏览(42)
  • 开源模型应用落地-qwen模型小试-入门篇(三)

    一、前言     相信您已经学会了如何在Windows环境下以最低成本、无需GPU的情况下运行qwen大模型。现在,让我们进一步探索如何在Linux环境下,并且拥有GPU的情况下运行qwen大模型,以提升性能和效率。 二、术语     2.1. CentOS         CentOS是一种基于Linux的自由开源操作系统。

    2024年01月21日
    浏览(46)
  • 开源模型应用落地-qwen2模型小试-入门篇(六)

        经过前五篇“qwen模型小试”文章的学习,我们已经熟练掌握qwen大模型的使用。然而,就在前几天开源社区又发布了qwen1.5版本,它是qwen2模型的测试版本。在基于transformers的使用方式上有较大的调整,现在,我们赶紧跟上脚步,去体验一下新版本模型的推理质量。    

    2024年03月17日
    浏览(63)
  • 开源模型应用落地-baichuan2模型小试-入门篇(三)

            相信您已经学会了如何在Windows环境下以最低成本、无需GPU的情况下运行baichuan2大模型。现在,让我们进一步探索如何在Linux环境下,并且拥有GPU的情况下运行baichuan2大模型,以提升性能和效率。     CentOS是一种基于Linux的自由开源操作系统。它是从Red Hat Enterprise Li

    2024年04月17日
    浏览(43)
  • 开源模型应用落地-chatglm3-6b模型小试-入门篇(一)

         刚开始接触AI时,您可能会感到困惑,因为面对众多开源模型的选择,不知道应该选择哪个模型,也不知道如何调用最基本的模型。但是不用担心,我将陪伴您一起逐步入门,解决这些问题。      在信息时代,我们可以轻松地通过互联网获取大量的理论知识和概念。然

    2024年04月10日
    浏览(47)
  • 开源模型应用落地-chatglm3-6b模型小试-入门篇(三)

         刚开始接触AI时,您可能会感到困惑,因为面对众多开源模型的选择,不知道应该选择哪个模型,也不知道如何调用最基本的模型。但是不用担心,我将陪伴您一起逐步入门,解决这些问题。      在信息时代,我们可以轻松地通过互联网获取大量的理论知识和概念。然

    2024年04月12日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包