Skip to content

Latest commit

 

History

History
516 lines (393 loc) · 12.4 KB

File metadata and controls

516 lines (393 loc) · 12.4 KB
Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0784
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
本教程同步发布在: 

     个人网站: `https://oeasy.org` 
     蓝桥云课: `https://www.lanqiao.cn/courses/3584` 
     GitHub: `https://github.com/overmind1980/oeasy-python-tutorial` 
     Gitee: `https://gitee.com/overmind1980/oeasypython` 
---

文生图模型调用

回忆

  • 上次 通过messages
    • 给大语言模型 添加了聊天记录
    • 这样大语言模型 就有了 记忆
    • 成为了智能体(agent)

图片描述

  • 但是
    • 目前智能体无法知道
    • 当前日期时间
    • 怎么办呢?🤔

原始代码

from openai import OpenAI

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=[
        {
            'role': 'system',
            'content': '你是智能助手'
        },
        {
            'role': 'user',
            'content': input("我:")
        }
    ],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='', flush=True)

  • 运行结果

图片描述

目标

  • 如何让大模型查询到当前时间?

图片描述

查询时间

import time
time.asctime()
  • 可以在shell运行命令
    • 得到日期时间

图片描述

  • 可以一上来
    • 就把 日期时间
    • 作为 上下文
    • 交代给 大模型

系统人设

  • 原来是 将 大模型设置为 猫
    • 现在是 把系统时间 直接告诉大模型

图片描述

交代时间日期

from openai import OpenAI
import time

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=[
        {
            'role': 'system',
            'content': '你是智能助手,当前时间是' + time.asctime() 
        },
        {
            'role': 'user',
            'content': input("我:")
        }
    ],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='', flush=True)

  • 确实可以得到
    1. 日期
    2. 时间

图片描述

  • 但是所有东西都直接堆在
    • system 的环境上下文中
    • 还是太多了

条件

  • 根据问题判断
    • 如果包含
      1. 几点
      2. 现在
      3. 几号
      4. 星期几
    • 就调用time.asctime()
      • 并且给到上下文

图片描述

代码

from openai import OpenAI
import time

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

# 获取用户输入
user_question = input('请输入您的问题: ')

# 检测是否包含时间相关关键词
time_keywords = ['几点', '现在', '几号', '星期几']
has_time_question = any(keyword in user_question for keyword in time_keywords)

# 构建系统消息
system_content = 'You are a helpful assistant.'
if has_time_question:
    current_time = time.asctime()
    system_content += f' 当前时间是: {current_time}'

response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=[
        {
            'role': 'system',
            'content': system_content
        },
        {
            'role': 'user',
            'content': user_question
        }
    ],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='', flush=True)

运行效果

图片描述

  • 除了使用time.asctime()
date
  • shell中的 date命令
    • 也可以得到当前时间、日期

图片描述

  • 可以在python里面调用shell命令吗?

尝试调用

import os
os.system('date')
  • 运行结果

图片描述

  • 可以把shell命令
    • 作为子进程 来执行吗?

图片描述

子进程模式

import subprocess
result = subprocess.run(['date'], capture_output=True, text=True)
print(result.stdout)
  • 运行结果

图片描述

  • 可以用子进程的方式
    • 替换原来的 time.asctime() 吗?

图片描述

新模式

from openai import OpenAI
import subprocess

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

# 获取用户输入
user_question = input('请输入您的问题: ')

# 检测是否包含时间相关关键词
time_keywords = ['几点', '现在', '几号', '星期几']
has_time_question = any(keyword in user_question for keyword in time_keywords)

# 构建系统消息
system_content = 'You are a helpful assistant.'
if has_time_question:
    try:
        # 使用subprocess调用系统date命令获取时间
        result = subprocess.run(['date'], capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            current_time = result.stdout.strip()
        else:
            current_time = "无法获取当前时间"
    except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
        current_time = "无法获取当前时间"
    system_content += f' 当前时间是: {current_time}'

response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=[
        {
            'role': 'system',
            'content': system_content
        },
        {
            'role': 'user',
            'content': user_question
        }
    ],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='', flush=True)

  • 运行顺利

图片描述

  • 他为什么会运行顺利呢?

输出上下文

from openai import OpenAI
import subprocess
def show_messages(messages):
    print()
    counter = 1
    for message in messages:
        print("\033[4" + str(counter) + "m",end="")
        print(message,end="")
        print("\33[0m")
        counter = counter + 1
        if counter == 7:
            counter = 1

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

# 获取用户输入
user_question = input('请输入您的问题: ')

# 检测是否包含时间相关关键词
time_keywords = ['几点', '现在', '几号', '星期几']
has_time_question = any(keyword in user_question for keyword in time_keywords)

# 构建系统消息
system_content = 'You are a helpful assistant.'
if has_time_question:
    try:
        # 使用subprocess调用系统date命令获取时间
        result = subprocess.run(['date'], capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            current_time = result.stdout.strip()
        else:
            current_time = "无法获取当前时间"
    except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
        current_time = "无法获取当前时间"
    system_content += f' 当前时间是: {current_time}'

messages = [
        {
            'role': 'system',
            'content': system_content
        },
        {
            'role': 'user',
            'content': user_question
        }
    ]

show_messages(messages)
response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=messages,
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content, end='', flush=True)


上下文效果

图片描述

  • 由于用户提示词 匹配了
    • 时间相关词
    • 于是 当前时间被 翻到了系统人设中

新的问题

  • 我想知道当前目录

图片描述

当前可以使用时间关键词匹配的话执行 date 命令,但如果是想问和系统目录相关的,如何让它匹配到 pwd命令呢?

修改代码

  • 判断是否符合目录关键词

图片描述

  • 如果匹配的话
    • 还是加入到系统人设中

图片描述

from openai import OpenAI
import subprocess
def show_messages(messages):
    print()
    counter = 1
    for message in messages:
        print("\033[4" + str(counter) + "m",end="")
        print(message,end="")
        print("\33[0m")
        counter = counter + 1
        if counter == 7:
            counter = 1

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1',
    api_key = 'ms-5a818c2a-7605-41bd-9183-416f78373fda'
)

# 获取用户输入
user_question = input('请输入您的问题: ')

# 检测是否包含时间相关关键词
time_keywords = ['几点', '现在', '几号', '星期几']
has_time_question = any(keyword in user_question for keyword in time_keywords)

# 检测是否包含目录相关关键词
dir_keywords = ['目录', '路径', '当前目录', 'pwd']
has_dir_question = any(keyword in user_question for keyword in dir_keywords)

# 构建系统消息
system_content = 'You are a helpful assistant.'
if has_time_question:
    try:
        # 使用subprocess调用系统date命令获取时间
        result = subprocess.run(['date'], capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            current_time = result.stdout.strip()
        else:
            current_time = "无法获取当前时间"
    except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
        current_time = "无法获取当前时间"
    system_content += f' 当前时间是: {current_time}'

if has_dir_question:
    try:
        # 使用subprocess调用系统pwd命令获取当前目录
        result = subprocess.run(['pwd'], capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            current_dir = result.stdout.strip()
        else:
            current_dir = "无法获取当前目录"
    except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
        current_dir = "无法获取当前目录"
    system_content += f' 当前目录是: {current_dir}'

messages = [
        {
            'role': 'system',
            'content': system_content
        },
        {
            'role': 'user',
            'content': user_question
        }
    ]

show_messages(messages)
response = client.chat.completions.create(
    model='Qwen/Qwen3-Next-80B-A3B-Instruct', # ModelScope Model-Id
    messages=messages,
    stream=True
)

# 处理响应
try:
    # 尝试处理流式响应
    for chunk in response:
        if hasattr(chunk, 'choices') and chunk.choices and hasattr(chunk.choices[0], 'delta') and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end='', flush=True)
except AttributeError:
    # 如果response不是预期的格式,尝试直接处理非流式响应
    try:
        # 尝试作为非流式响应处理
        if hasattr(response, 'choices') and response.choices:
            print(response.choices[0].message.content)
        else:
            print("获取响应时出现格式问题:")
            print(response)
    except Exception as e:
        print(f"处理响应时发生错误:{e}")


结果

图片描述

  • 如果两个模式 都匹配

图片描述

  • 但是 这是
    • 一个个地 往系统人设上面叠加内容啊
    • 能否充分利用大模型的 推理能力呢?

总结

  • 这次 我们让智能体
    • 知道 日期和时间
    • 甚至 使用起 终端工具

图片描述

  • 如何让 智能体
    • 更好地使用 终端工具 呢?
  • 下次再说👋

  • 本文来自 oeasy Python 系统教程。
  • 想完整、扎实学 Python,
  • 搜索 oeasy 即可。