还不会function-call?看完这篇就懂了

函数调用

使模型能够获取数据并执行操作。

函数调用为大模型提供了一种强大而灵活的方式来与您的代码或外部服务进行交互

# Function will be used outside LLM
def get_weather(location: str, unit: str):
    print(f"\nGetting the weather for {location} in {unit}...")
    
    fake_weather_of_Dallas = "The weather is 98 degrees fahrenheit, with partlycloudy skies and a low chance of rain."
    fake_weather_of_SF = "Clouds giving way to sun Hi: 76° Tonight: Mainly clear early, then areas of low clouds forming Lo: 56°"
    
    if 'Francisco' in location :
        return fake_weather_of_SF
    elif 'Dallas' in location :
        return fake_weather_of_Dallas
    else :
        return "unknowm city"

# Tool_call procedure
def tool_call_infer(client, model_name) :
    # Prepare request-1 params
    tools = [{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City and state, e.g., 'San Francisco, CA'"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location", "unit"]
            }
        }
    }]
    tool_choice={"type": "function", "function": {"name": "get_weather"}}
    city = "San Francisco"
    # city = "Dallas"
    chat_prompt = [{"role": "user", "content": f"What's the weather like in {city}?"}]

    # Request-1
    response = client.chat.completions.create(
        model=model_name,
        messages=chat_prompt,
        temperature=0,
        max_tokens=200,
        tools=tools,
        tool_choice=tool_choice
    )

    # Check response-1
    tool_call_ret = response.choices[0].message.tool_calls[0]
    print(f"Function called: {tool_call_ret.function.name}")
    print(f"Arguments: {tool_call_ret.function.arguments}")

    # Call function with response-1
    weather_by_func = get_weather(**json.loads(tool_call_ret.function.arguments))

    # Prepare request-2 params
    # *system_prompt is needed in some case
    system_prompt = {
        "role": "system", 
        "content": "You are a helpful assistant with tool calling capabilities. When you receive a tool call response, use the output to format an answer to the orginal use question."
    }
    # append func call ret in request-2 params
    func_ret_in_prompt = {
        "role": "tool", 
        "content": weather_by_func,
        "tool_call_id": tool_call_ret.id
    }

    chat_prompt.append(system_prompt)
    chat_prompt.append(func_ret_in_prompt)

    # Request-2
    response = client.chat.completions.create(
            messages=chat_prompt,
            temperature=0,
            max_tokens=200,
            model=model_name,
            # tools=tools,
            # tool_choice="none"
            )

    print("\nFinal output : \n", response.choices[0].message.content)

if __name__ == "__main__":
    model_name = "deepseek"
    client = OpenAI(base_url="http://localhost:8888/v1", api_key="dummy")
    tool_call_infer(client, model_name)

启动推理服务,并根据当前配置修改脚本最后的model_name和端口号(85、86行处);
服务启动后,通过python执行脚本,发起请求;

调用成功后会得到如下预期结果:

  • 推理模型为DeepSeek-R1-AWQ
Function called: get_weather
Arguments: {"location": "San Francisco", "unit": "celsius"}

Getting the weather for San Francisco in celsius...

Final output : 
 
Okay, the user asked about the weather in San Francisco. Let me check the tool response. The current condition is "Clouds giving way to sun" with a high of 76°F. Tonight, it'll be mainly clear early, then areas of low clouds forming with a low of 56°F. I need to present this info clearly. Start with the current weather, mention the high, then the tonight forecast with the low. Keep it friendly and concise. Maybe add a note about the temperature change in the evening.
</think>

Right now in San Francisco, the clouds are clearing up for sunshine with a high of **76°F**. Tonight, skies will be mostly clear early, followed by some low clouds rolling in, and temperatures dropping to a low of **56°F**. A pleasant day with mild evening cooling! 🌤️
  • 推理模型为Meta-Llama-3.1-8B-Instruct
Function called: get_weather
Arguments: {"location": "San Francisco, CA", "unit": "fahrenheit"}

Getting the weather for San Francisco, CA in fahrenheit...

Final output : 
 The current weather in San Francisco is mostly sunny with a high temperature of 76°F (24°C). Tonight, it will be mainly clear in the early hours, but low clouds will start to form later. The low temperature tonight is expected to be around 56°F (13°C).
<think>嗯,用户遇到了“Call to undefined function Think\imagecreate()”这个错误。首先,我需要分析这个问题可能的原因。imagecreate()是PHP的GD库中的一个函数,所以这个错误通常意味着GD库没有安装或者没有启用。 用户使用的是ThinkPHP框架,可能在代码中调用了图像处理功能,但环境缺少必要的扩展。接下来,我要考虑不同的服务器环境,比如Linux、Windows,或者可能使用了Docker,因为不同环境下安装GD库的方法不同。 然后,我需要检查GD库是否已经安装。用户可能需要通过phpinfo()来查看当前PHP环境是否加载了GD库。如果没有,就需要指导他们如何安装。比如在Ubuntu上安装php-gd,CentOS用yum或者dnf,Windows则要修改php.ini文件,启用扩展。 另外,安装完GD库后,可能需要重启Web服务器,比如Apache或Nginx,或者重启PHP-FPM服务,这样才能使改动生效。同时,用户可能会忽略这一步,导致问题依旧存在,所以需要提醒他们重启服务。 还有,有些情况下,GD库可能安装了但版本不兼容,或者配置不正确。这时候需要确认安装的GD库版本是否与PHP版本匹配,或者是否有其他扩展冲突。 另外,可能用户使用的是共享主机,没有权限安装扩展,这时候需要联系主机提供商。或者他们在使用Docker,需要在Dockerfile中安装GD库并重新构建镜像。 最后,测试是否解决的方法是创建一个简单的PHP脚本调用phpinfo()或者直接调用imagecreate()函数,看是否还报错。如果问题依旧,可能需要进一步排查安装步骤是否正确,或者查看错误日志获取更多信息。 总结下来,解决步骤大致是:确认GD库是否安装→安装对应的扩展→重启服务→测试验证。需要分不同操作系统给出具体指令,并提醒用户注意权限和重启服务的重要性。同时,考虑到用户可能对命令行不熟悉,给出具体的命令示例会更帮助。比如Ubuntu的apt install,CentOS的yum install,Windows修改php.ini等。 另外,可能需要提醒用户,某些框架或CMS可能有额外的配置要求,或者缓存问题,安装后需要清除缓存。但在这个案例中,ThinkPHP可能不需要额外配置,主要是GD库的问题。 用户可能遇到的问题还包括:PHP版本过旧,不支持某些GD功能,或者安装时依赖包缺失导致安装失败。这时候需要指导用户更新PHP版本,或者安装依赖包,比如libpng、libjpeg等。 最后,确保回答清晰,分步骤说明,让用户能一步步跟着操作,解决问题。</think>出现 `Call to undefined function Think\imagecreate()` 错误时,通常是因为 PHP 的 **GD 图形库扩展未启用或未安装**。以下是分步解决方案: --- ### 1. **问题根源** - `imagecreate()` 是 PHP GD 库提供的函数,用于创建图像资源。 - 当 PHP 环境未加载 GD 扩展时,调用此函数会触发该错误。 --- ### 2. **解决方案** #### **步骤 1:检查 GD 库是否已安装** - 创建一个 PHP 文件(如 `info.php`),写入以下内容: ```php <?php phpinfo(); ?> ``` - 通过浏览器访问此文件,搜索 `GD Support`: - 如果显示 `enabled`,说明 GD 已启用。 - 如果未找到,需安装并启用 GD 库。 --- #### **步骤 2:安装 GD 扩展** 根据不同操作系统选择安装方式: ##### **Linux 系统(Apache/Nginx)** - **Ubuntu/Debian**: ```bash sudo apt update sudo apt install php-gd ``` - **CentOS/RHEL**: ```bash sudo yum install php-gd # 或(PHP 7.4+) sudo dnf install php-gd ``` ##### **Windows 系统** 1. 打开 `php.ini` 文件(路径如 `C:\php\php.ini`)。 2. 找到 `;extension=gd` 并删除行首的分号 `;`,改为: ```ini extension=gd ``` 3. 保存文件并重启 Web 服务器(如 Apache)。 ##### **Docker 环境** 在 Dockerfile 中安装 GD: ```dockerfile RUN apt-get update && apt-get install -y php-gd # 或 Alpine 系统 RUN apk add --no-cache php8-gd ``` --- #### **步骤 3:重启 Web 服务** 安装后必须重启服务以生效: - **Apache**: ```bash sudo service apache2 restart ``` - **Nginx + PHP-FPM**: ```bash sudo service php-fpm restart sudo service nginx restart ``` --- #### **步骤 4:验证安装** 再次访问 `info.php`,确认 `GD Support` 已启用。 --- ### 3. **其他注意事项** 1. **ThinkPHP 版本**:确保框架版本兼容当前 PHP 环境。 2. **PHP 版本**:GD 库需与 PHP 版本匹配(如 PHP 7.x 使用 `php7.x-gd`)。 3. **依赖项**:GD 库可能依赖其他组件(如 libjpeg、libpng),需一并安装: ```bash sudo apt install libjpeg-dev libpng-dev ``` --- ### 4. **代码测试** 安装成功后,使用以下代码测试: ```php <?php $im = imagecreate(100, 100); if ($im) { echo "GD 库已正常工作!"; imagedestroy($im); } ``` 若输出成功,则问题已解决。 --- 通过以上步骤,应能解决 `Call to undefined function Think\imagecreate()` 错误。如果问题依旧,请检查 PHP 错误日志或联系服务器管理员。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值