人工智能(四)- Function Calling 核心原理與實戰(zhàn)

人工智能(三)- 提供 API,搭建智能客服系統(tǒng)

大模型雖然擅長自然語言理解與生成,但在處理實時數(shù)據(jù)查詢、精準(zhǔn)數(shù)學(xué)計算、外部系統(tǒng)交互等場景時往往力不從心。Function Calling(函數(shù)調(diào)用)作為大模型連接外部工具的核心能力,讓模型能夠“調(diào)用工具”解決原本無法直接回答的問題,成為構(gòu)建智能應(yīng)用的關(guān)鍵技術(shù)。

一、Function Calling 核心工作原理

Function Calling 本質(zhì)是大模型與外部工具的協(xié)作交互流程,通過標(biāo)準(zhǔn)化的多輪對話機制,讓模型能夠自主決策是否調(diào)用工具、調(diào)用哪個工具,并基于工具返回結(jié)果生成最終回答。完整流程分為5個核心步驟:

工作流程示意圖

1.1 首次模型調(diào)用:傳遞問題與工具清單

應(yīng)用程序向大模型發(fā)起請求,請求內(nèi)容包含兩部分核心信息:

  • 用戶的原始問題(如“北京今天天氣怎么樣?”)
  • 模型可調(diào)用的工具清單(包含工具名稱、功能描述、入?yún)⒁?guī)范)

1.2 模型決策:返回工具調(diào)用指令或直接回答

模型基于用戶問題和工具清單進行判斷:

  • 需要調(diào)用工具:返回 JSON 格式的工具調(diào)用指令,包含「要調(diào)用的工具名稱」和「工具所需入?yún)ⅰ?/li>
  • 無需調(diào)用工具:直接返回自然語言格式的回答(如回答常識性問題)

1.3 應(yīng)用端執(zhí)行工具調(diào)用

應(yīng)用程序解析模型返回的工具調(diào)用指令,調(diào)用對應(yīng)的外部工具(如天氣 API、計算器、數(shù)據(jù)庫查詢接口),獲取工具執(zhí)行結(jié)果。

1.4 二次模型調(diào)用:傳入工具執(zhí)行結(jié)果

將工具返回的結(jié)果(如“北京今天是晴天”)添加到對話上下文(messages)中,再次調(diào)用大模型。

1.5 生成最終回答

模型結(jié)合用戶原始問題和工具返回的精準(zhǔn)數(shù)據(jù),生成自然、準(zhǔn)確的最終回復(fù)。


二、實戰(zhàn)案例:實現(xiàn)天氣查詢 AI 助手

下面以 Java 實現(xiàn)的天氣查詢助手為例,完整展示 Function Calling 的落地流程(基于阿里云通義千問 API)。

2.1 第一步:定義工具(核心)

工具是大模型與外部系統(tǒng)的橋梁,需同時定義「模型可識別的工具描述」和「本地執(zhí)行的工具邏輯」。

2.1.1 工具執(zhí)行邏輯(模擬天氣查詢)
/**
 * 執(zhí)行天氣查詢(模擬真實 API 調(diào)用)
 * @param arguments 模型傳入的參數(shù) JSON 字符串,格式:{"location": "查詢地點"}
 * @return 工具執(zhí)行結(jié)果,格式:"{位置}今天是{天氣}"
 */
public String execute(String arguments) {
    try {
        // 解析模型傳入的參數(shù)
        JsonNode argsNode = objectMapper.readTree(arguments);
        String location = argsNode.get("location").asText();

        // 模擬調(diào)用真實天氣 API,返回隨機天氣結(jié)果
        List<String> weatherConditions = Arrays.asList("晴天", "多云", "雨天");
        String randomWeather = weatherConditions.get(new Random().nextInt(weatherConditions.size()));

        return location + "今天是" + randomWeather + "。";
    } catch (IOException e) {
        // 異常處理:參數(shù)解析失敗時返回友好提示
        return "無法解析地點參數(shù),請檢查輸入格式。";
    }
}
2.1.2 定義模型可識別的工具描述

模型需要通過標(biāo)準(zhǔn)化的 JSON 結(jié)構(gòu)識別工具,核心字段說明:

{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "查詢指定城市/縣區(qū)的實時天氣,適用于用戶詢問天氣相關(guān)問題時。",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "城市或縣區(qū)名稱,例如:北京市、杭州市、余杭區(qū)"
                }
            },
            "required": ["location"]
        }
    }
}
  • type:字段固定為"function";
  • function:字段為 Object 類型;
    • name:字段為自定義的工具函數(shù)名稱,建議使用與函數(shù)相同的名稱,如get_current_weather或get_current_time;
    • description:字段是對工具函數(shù)功能的描述,大模型會參考該字段來選擇是否使用該工具函數(shù)。
    • parameters:字段是對工具函數(shù)入?yún)⒌拿枋?,類型?Object ,大模型會參考該字段來進行入?yún)⒌奶崛 H绻ぞ吆瘮?shù)不需要輸入?yún)?shù),則無需指定parameters參數(shù)。
      • type:字段固定為"object";
      • properties:字段描述了入?yún)⒌拿Q、數(shù)據(jù)類型與描述,為 Object 類型,Key 值為入?yún)⒌拿Q,Value 值為入?yún)⒌臄?shù)據(jù)類型與描述;
    • required:字段指定哪些參數(shù)為必填項,為 Array 類型。

2.2 第二步:完整代碼實現(xiàn)

2.2.1 創(chuàng)建Maven工程

使用IntelliJ IDEA創(chuàng)建一個Maven工程,完成工程初始化。

2.2.2 引入核心依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.devpotato</groupId>
    <artifactId>chat-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <packaging>jar</packaging>

    <name>ChatService</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jackson.version>2.15.0</jackson.version>
    </properties>

    <dependencies>
        <!--        spring-boot        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        openai        -->
        <dependency>
            <groupId>com.openai</groupId>
            <artifactId>openai-java</artifactId>
            <version>4.28.0</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-stdlib-jdk8</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.openai</groupId>
            <artifactId>openai-java-client-okhttp</artifactId>
            <version>4.28.0</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-stdlib-jdk8</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>2.3.20-RC3</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-stdlib</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Source: https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib -->
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib</artifactId>
            <version>2.3.20-RC3</version>
            <scope>compile</scope>
        </dependency>

        <!--        jackson        -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!--        guava        -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
        
        <!--        lombok        -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
        <repository>
            <name>Central Portal Snapshots</name>
            <id>central-portal-snapshots</id>

            <url>https://central.sonatype.com/repository/maven-snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

引入依賴后,點擊IDEA的「Refresh」按鈕,下載并加載依賴包,確保工程無依賴報錯。

2.2.3 工程配置文件

在src/main/resources目錄下創(chuàng)建application.yml文件,配置服務(wù)端口(默認(rèn)8080,可根據(jù)需求修改):

server:
  port: 8080
2.2.4 解決跨域問題

由于前端頁面與后端服務(wù)可能存在跨域(CORS)問題,導(dǎo)致前端無法正常調(diào)用后端API,因此需要添加跨域過濾器。創(chuàng)建MyFilter類,實現(xiàn)Filter接口,具體代碼如下:

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 解決Chrome等瀏覽器訪問本地服務(wù)的跨域問題
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 允許所有域名跨域訪問(生產(chǎn)環(huán)境建議指定具體域名,提升安全性)
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允許的請求方式
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // 允許的請求頭
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type");
        // 繼續(xù)執(zhí)行過濾鏈
        chain.doFilter(request, response);
    }
}
2.2.5 天氣工具封裝類
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 天氣查詢工具封裝
 * 包含:模型識別的工具定義 + 本地執(zhí)行邏輯
 */
@Component
public class WeatherTool {
    // 工具名稱(需與注冊給模型的名稱一致)
    public static final String FUNCTION_NAME = "get_current_weather";
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 構(gòu)建供模型識別的工具定義
     */
    public ChatCompletionTool buildToolDefinition() {
        // 定義入?yún)傩?        Map<String, Object> locationProperty = new HashMap<>();
        locationProperty.put("type", "string");
        locationProperty.put("description", "城市或縣區(qū)名稱,例如:北京市、杭州市、余杭區(qū)");

        Map<String, Object> properties = new HashMap<>();
        properties.put("location", locationProperty);

        // 構(gòu)建參數(shù)規(guī)范
        FunctionParameters functionParameters = FunctionParameters.builder()
                .putAdditionalProperty("type", JsonValue.from("object"))
                .putAdditionalProperty("properties", JsonValue.from(properties))
                .putAdditionalProperty("required", JsonValue.from(Arrays.asList("location")))
                .build();

        // 構(gòu)建函數(shù)定義
        FunctionDefinition functionDefinition = FunctionDefinition.builder()
                .name(FUNCTION_NAME)
                .description("查詢指定城市/縣區(qū)的實時天氣,適用于用戶詢問天氣相關(guān)問題時。")
                .parameters(functionParameters)
                .build();

        // 構(gòu)建完整的工具定義
        return ChatCompletionTool.ofFunction(ChatCompletionFunctionTool.builder()
                .type(JsonValue.from("function"))
                .function(functionDefinition)
                .build());
    }

    /**
     * 執(zhí)行天氣查詢(模擬真實 API 調(diào)用)
     */
    public String execute(String arguments) {
        try {
            JsonNode argsNode = objectMapper.readTree(arguments);
            String location = argsNode.get("location").asText();

            List<String> weatherConditions = Arrays.asList("晴天", "多云", "雨天");
            String randomWeather = weatherConditions.get(new Random().nextInt(weatherConditions.size()));

            return location + "今天是" + randomWeather + "。";
        } catch (IOException e) {
            return "無法解析地點參數(shù),請檢查輸入格式。";
        }
    }
}
2.2.6 核心對話控制器
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.function.Function;

/**
 * 通義千問 Function Calling 核心控制器
 * 實現(xiàn):多輪對話 + 工具調(diào)用完整流程
 */
@RestController
@RequestMapping("/chat")
public class ChatController {
    // 配置項(建議從配置文件/環(huán)境變量讀取,此處為演示)
    private static final String API_KEY = "xxx";
    private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
    private static final String LLM_MODEL = "qwen-plus";
    private static final String SYSTEM_PROMPT = "你是一個智能天氣查詢助手,僅在用戶詢問天氣時調(diào)用天氣工具,其他問題直接友好回復(fù)。";

    // 對話歷史(單用戶演示,多用戶需按會話ID隔離)
    private static final List<ChatCompletionMessageParam> messageHistoryList = new ArrayList<>();
    // OpenAI 客戶端(兼容通義千問)
    private static final OpenAIClient client = OpenAIOkHttpClient.builder()
            .apiKey(API_KEY)
            .baseUrl(BASE_URL)
            .build();
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 工具列表 + 工具執(zhí)行器映射(便于擴展)
    private static final List<ChatCompletionTool> toolList = new ArrayList<>();
    private static final Map<String, ToolExecutor> toolExecutorMap = new HashMap<>();

    // 初始化工具
    static {
        try {
            WeatherTool weatherTool = new WeatherTool();
            toolList.add(weatherTool.buildToolDefinition());
            toolExecutorMap.put(WeatherTool.FUNCTION_NAME, weatherTool::execute);
        } catch (Exception e) {
            throw new RuntimeException("工具初始化失敗", e);
        }
    }

    // 工具執(zhí)行器函數(shù)式接口(簡化工具擴展)
    @FunctionalInterface
    public interface ToolExecutor {
        String execute(String arguments);
    }

    /**
     * 處理用戶消息,返回最終回復(fù)
     * @param request 請求體,格式:{"message": "用戶問題"}
     * @return 模型最終回復(fù)
     */
    @PostMapping("")
    public String chat(@RequestBody Map<String, Object> request) {
        String userInput = request.get("message").toString();

        // 1. 添加用戶消息到對話歷史
        ChatCompletionUserMessageParam userMessage = ChatCompletionUserMessageParam.builder()
                .role(JsonValue.from("user"))
                .content(userInput)
                .build();
        messageHistoryList.add(ChatCompletionMessageParam.ofUser(userMessage));

        try {
            // 2. 第一次調(diào)用模型,判斷是否需要調(diào)用工具
            ChatCompletion completion = callModel();
            ChatCompletionMessage assistantMsg = completion.choices().get(0).message();
            addAssistantMessageToHistory(assistantMsg);

            // 3. 無需調(diào)用工具,直接返回結(jié)果
            if (!hasToolCall(assistantMsg)) {
                return assistantMsg.content().orElse("抱歉,我暫時無法回答這個問題。");
            }

            // 4. 需要調(diào)用工具,循環(huán)處理(支持多輪工具調(diào)用)
            while (hasToolCall(assistantMsg)) {
                ChatCompletionMessageToolCall toolCall = assistantMsg.toolCalls().get().get(0);
                String toolId = toolCall.function().get().id();
                String funcName = toolCall.function().get().function().name();
                String args = toolCall.function().get().function().arguments();

                // 執(zhí)行工具調(diào)用
                String toolResult = toolExecutorMap.getOrDefault(funcName, arg -> "未找到工具:" + funcName).execute(args);

                // 5. 將工具結(jié)果加入對話歷史
                ChatCompletionToolMessageParam toolMsg = ChatCompletionToolMessageParam.builder()
                        .role(JsonValue.from("tool"))
                        .toolCallId(toolId)
                        .content(toolResult)
                        .build();
                messageHistoryList.add(ChatCompletionMessageParam.ofTool(toolMsg));

                // 6. 二次調(diào)用模型,生成最終回答
                completion = callModel();
                assistantMsg = completion.choices().get(0).message();
                addAssistantMessageToHistory(assistantMsg);
            }

            return assistantMsg.content().orElse("");
        } catch (Exception e) {
            e.printStackTrace();
            return "處理請求時出錯:" + e.getMessage();
        }
    }

    /**
     * 調(diào)用大模型核心方法
     */
    private ChatCompletion callModel() {
        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addSystemMessage(SYSTEM_PROMPT)
                .messages(messageHistoryList)
                .model(LLM_MODEL)
                .tools(toolList)
                .parallelToolCalls(true) // 支持并行工具調(diào)用
                .build();
        return client.chat().completions().create(params);
    }

    /**
     * 將助手消息加入對話歷史
     */
    private void addAssistantMessageToHistory(ChatCompletionMessage msg) {
        ChatCompletionAssistantMessageParam.Builder builder = ChatCompletionAssistantMessageParam.builder()
                .role(JsonValue.from("assistant"))
                .content(msg.content().orElse(""));
        if (hasToolCall(msg)) {
            builder.toolCalls(msg.toolCalls().get());
        }
        messageHistoryList.add(ChatCompletionMessageParam.ofAssistant(builder.build()));
    }

    /**
     * 判斷模型回復(fù)是否包含工具調(diào)用
     */
    private boolean hasToolCall(ChatCompletionMessage msg) {
        return msg.toolCalls().isPresent() && !msg.toolCalls().get().isEmpty();
    }
}
2.2.7 啟動類開發(fā)

創(chuàng)建StartServer類,作為Spring Boot工程的啟動入口,代碼如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StartServer {

    public static void main(String[] args) {
        // 啟動Spring Boot服務(wù)
        SpringApplication.run(StartServer.class, args);
        System.out.println("智能客服后端服務(wù)啟動成功,端口:8080");
    }
}

三、前端頁面搭建(簡易版)

前端采用簡單的HTML+JavaScript搭建聊天界面,實現(xiàn)用戶輸入提問、展示客服回復(fù)的功能。創(chuàng)建index.html文件,代碼如下(可直接在瀏覽器中打開使用):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>電商客服中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f5f7fa;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 800px;
            height: 80vh;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background-color: #409eff;
            color: #fff;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .chat-header img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #fff;
        }

        .chat-header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }

        .message {
            margin-bottom: 15px;
            max-width: 70%;
            display: flex;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            margin-left: auto;
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            margin: 0 8px;
            flex-shrink: 0;
        }

        .user-message .message-content {
            background-color: #409eff;
            color: #fff;
            border-radius: 10px 10px 0 10px;
        }

        .bot-message .message-content {
            background-color: #fff;
            color: #333;
            border-radius: 10px 10px 10px 0;
            border: 1px solid #eee;
        }

        .message-content {
            padding: 10px 15px;
            word-wrap: break-word;
            line-height: 1.4;
        }

        /* 快捷按鈕區(qū)域樣式 */
        .quick-buttons {
            padding: 10px 15px;
            border-top: 1px solid #eee;
            background-color: #fafafa;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .quick-button {
            padding: 6px 15px;
            background-color: #e8f4ff;
            color: #409eff;
            border: 1px solid #d1e9ff;
            border-radius: 20px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s;
        }

        .quick-button:hover {
            background-color: #409eff;
            color: #fff;
            border-color: #409eff;
        }

        .chat-input {
            display: flex;
            padding: 15px;
            border-top: 1px solid #eee;
            background-color: #fff;
        }

        #message-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
            resize: none;
            height: 45px;
            max-height: 120px;
        }

        #message-input:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }

        #send-button {
            margin-left: 10px;
            padding: 0 20px;
            background-color: #409eff;
            color: #fff;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        #send-button:hover {
            background-color: #337ecc;
        }

        #send-button:disabled {
            background-color: #b3d8ff;
            cursor: not-allowed;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .empty-hint {
            text-align: center;
            color: #999;
            padding: 50px 0;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <img src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMjAiIGN5PSIyMCIgcj0iMjAiIGZpbGw9IiM0MDllZmYiLz4KPHBhdGggZD0iTTE1IDI1QzE1IDI3LjcxIDE2Ljk5IDI5IDE5IDI5QzIxLjAxIDI5IDIzIDI3LjcxIDIzIDI1QzIzIDIyLjc5IDIxLjAxIDIxIDE5IDIxQzE2Ljk5IDIxIDE1IDIyLjc5IDE1IDI1WiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==" alt="客服圖標(biāo)">
            <h2>在線客服中心</h2>
        </div>
        <div class="chat-messages" id="chat-messages">
            <div class="empty-hint" id="empty-hint">歡迎咨詢,我是您的專屬客服??</div>
        </div>
        
        <!-- 新增快捷按鈕區(qū)域 -->
        <div class="quick-buttons" id="quick-buttons">
            <div class="quick-button" onclick="sendQuickMessage('查看訂單')">查看訂單</div>
            <div class="quick-button" onclick="sendQuickMessage('查看物流')">查看物流</div>
            <div class="quick-button" onclick="sendQuickMessage('申請退款')">申請退款</div>
            <div class="quick-button" onclick="sendQuickMessage('修改收貨地址')">修改收貨地址</div>
            <div class="quick-button" onclick="sendQuickMessage('商品質(zhì)量問題')">商品質(zhì)量問題</div>
        </div>
        
        <div class="chat-input">
            <textarea id="message-input" placeholder="請輸入您想咨詢的問題..." onkeydown="if(event.keyCode===13&&!event.shiftKey){event.preventDefault();sendMessage();}"></textarea>
            <button id="send-button" onclick="sendMessage()">發(fā)送</button>
        </div>
    </div>

    <script>
        // 獲取DOM元素
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const chatMessages = document.getElementById('chat-messages');
        const emptyHint = document.getElementById('empty-hint');

        // 頭像URL(使用base64編碼的SVG,也可以替換為實際圖片URL)
        const BOT_AVATAR = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzYiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCAzNiAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTgiIGN5PSIxOCIgcj0iMTgiIGZpbGw9IiM0MDllZmYiLz4KPHBhdGggZD0iTTEzIDIyQzEzIDI0LjIxIDE0Ljk5IDI2IDE3IDI2QzE5LjAxIDI2IDIxIDI0LjIxIDIxIDIyQzIxIDE5Ljc5IDE5LjAxIDE4IDE3IDE4QzE0Ljk5IDE4IDEzIDE5Ljc5IDEzIDIyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==';
        const USER_AVATAR = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzYiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCAzNiAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTgiIGN5PSIxOCIgcj0iMTgiIGZpbGw9IiNmZmYwMDAiLz4KPHBhdGggZD0iTTEyIDIwQzEyIDIyLjcxIDEzLjk5IDI1IDE2IDI1QzE4LjAxIDI1IDIwIDIyLjcxIDIwIDIwQzIwIDE3Ljc5IDE4LjAxIDE1IDE2IDE1QzEzLjk5IDE1IDEyIDE3Ljc5IDEyIDIwWiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTIwIDI5QzIwIDI5IDE3IDMwIDE3IDMwQzE0IDMwIDEyIDI5IDEyIDI5QzEyIDI5IDEyIDI3IDEyIDI3QzEyIDI3IDE0IDI2IDE2IDI2QzE4IDI2IDIwIDI3IDIwIDI3QzIwIDI3IDIwIDI5IDIwIDI5WiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==';

        // 自動調(diào)整輸入框高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight > 45 ? this.scrollHeight : 45) + 'px';
        });

        // 快捷消息發(fā)送函數(shù)
        function sendQuickMessage(message) {
            // 將快捷消息填入輸入框
            messageInput.value = message;
            messageInput.style.height = 'auto';
            messageInput.style.height = (messageInput.scrollHeight > 45 ? messageInput.scrollHeight : 45) + 'px';
            
            // 自動發(fā)送該消息
            sendMessage();
        }

        // 發(fā)送消息函數(shù)
        async function sendMessage() {
            const message = messageInput.value.trim();
            
            // 驗證輸入內(nèi)容
            if (!message) {
                alert('請輸入咨詢內(nèi)容!');
                return;
            }

            // 禁用發(fā)送按鈕和輸入框
            sendButton.disabled = true;
            messageInput.disabled = true;

            try {
                // 隱藏空提示
                emptyHint.style.display = 'none';

                // 添加用戶消息到聊天窗口
                addMessageToChat(message, 'user');
                
                // 清空輸入框并恢復(fù)高度
                messageInput.value = '';
                messageInput.style.height = '45px';

                // 添加加載狀態(tài)
                const loadingId = addLoadingMessage();

                // 調(diào)用后端接口
                const response = await fetch('http://127.0.0.1:8080/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: message })
                });

                // 移除加載狀態(tài)
                removeLoadingMessage(loadingId);

                // 處理響應(yīng)
                if (response.ok) {
                    const data = await response.text();
                    // 添加客服回復(fù)到聊天窗口
                    addMessageToChat(data, 'bot');
                } else {
                    addMessageToChat('抱歉,服務(wù)器暫時無法響應(yīng),請稍后再試!', 'bot');
                    console.error('接口請求失敗:', response.status);
                }
            } catch (error) {
                // 移除加載狀態(tài)
                const loadingElements = document.querySelectorAll('.loading-message');
                loadingElements.forEach(el => el.remove());
                
                addMessageToChat('網(wǎng)絡(luò)錯誤,請檢查您的網(wǎng)絡(luò)連接!', 'bot');
                console.error('請求出錯:', error);
            } finally {
                // 恢復(fù)發(fā)送按鈕和輸入框
                sendButton.disabled = false;
                messageInput.disabled = false;
                messageInput.focus();
                
                // 滾動到最新消息
                scrollToBottom();
            }
        }

        // 添加消息到聊天窗口
        function addMessageToChat(content, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            
            // 創(chuàng)建頭像元素
            const avatarImg = document.createElement('img');
            avatarImg.className = 'message-avatar';
            avatarImg.src = sender === 'user' ? USER_AVATAR : BOT_AVATAR;
            avatarImg.alt = sender === 'user' ? '用戶頭像' : '客服頭像';
            
            // 創(chuàng)建消息內(nèi)容元素
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;
            
            // 組裝消息元素
            messageDiv.appendChild(avatarImg);
            messageDiv.appendChild(contentDiv);
            
            chatMessages.appendChild(messageDiv);
            
            // 滾動到最新消息
            scrollToBottom();
        }

        // 添加加載中的消息
        function addLoadingMessage() {
            const loadingId = 'loading-' + Date.now();
            const loadingDiv = document.createElement('div');
            loadingDiv.id = loadingId;
            loadingDiv.className = 'message bot-message loading-message';
            
            // 創(chuàng)建客服頭像
            const avatarImg = document.createElement('img');
            avatarImg.className = 'message-avatar';
            avatarImg.src = BOT_AVATAR;
            avatarImg.alt = '客服頭像';
            
            // 創(chuàng)建加載內(nèi)容
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.innerHTML = '<div class="loading"></div>';
            
            // 組裝加載消息
            loadingDiv.appendChild(avatarImg);
            loadingDiv.appendChild(contentDiv);
            chatMessages.appendChild(loadingDiv);
            
            scrollToBottom();
            return loadingId;
        }

        // 移除加載中的消息
        function removeLoadingMessage(loadingId) {
            const loadingDiv = document.getElementById(loadingId);
            if (loadingDiv) {
                loadingDiv.remove();
            }
        }

        // 滾動到聊天底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 監(jiān)聽輸入框回車事件(兼容)
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight > 45 ? this.scrollHeight : 45) + 'px';
        });
        
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>

四、系統(tǒng)測試


五、總結(jié)

  1. Function Calling 的核心是大模型+外部工具的協(xié)作流程,通過“問題傳遞→模型決策→工具執(zhí)行→結(jié)果整合”四步解決大模型無法直接處理的問題;
  2. 落地 Function Calling 的關(guān)鍵是標(biāo)準(zhǔn)化的工具定義(讓模型識別)和靈活的工具執(zhí)行器映射(便于擴展);
  3. 生產(chǎn)環(huán)境中需注意對話歷史隔離(多用戶場景)、配置項解耦、異常友好處理三大核心點。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容