Skip to content

手把手教你 AI 顾投:在 Ollama 中使用 Python 调用金融 API 服务

作者:老余捞鱼

原创不易,转载请标明出处及原作者。

写在前面的话:尽管Ollama本身不是一个大型语言模型(LLM)开发工具,而是一个LLM的平台。但它最近宣布了其系统中直接使用工具调用的功能,本文主要介绍了最新版本的主要更新,特别是关于功能调用的使用,并演示了如何在Ollama 中使用 Python 调用外部 API 服务。

一、 部署 Ollama 在本地运行


1.1 设置开发环境

在开始编写代码之前,最好的做法是建立一个新的开发环境,以保持我们的项目各自独立。我使用 conda 来实现这一点,但您也可以使用自己喜欢的工具。

PS C:\Users\thoma> conda create -n ollama_tools python=3.11 -y
PS C:\Users\thoma> conda activate ollama_tools
(ollama_tools) PS C:\Users\thoma> pip install jupyter yfinance ollama

1.2 安装 Ollama

访问 ollama.com,为你的系统下载最新版本的 Ollama,然后安装。检查您的版本。您至少需要 下载 0.3.0 版才能使用工具调用。

(ollama_tools) PS C:\Users\thoma> ollama --version
ollama version is 0.3.0

选择您的 LLM 模型并通过 Ollama 下载,有关允许使用工具的 Ollama兼容型号列表,请查看其网站的这一部分。

Get up and running with large language models.


一旦决定要使用哪种型号,就可以使用 Ollama 将其提取(下载)到本地系统。例如,我选择使用 Llama 3.1 8B 型号。

(ollama_tools) PS C:\Users\thoma> ollama pull llama3.1

大概一到两分钟完成后,您可以通过以下方式查看本地系统中的型号

(ollama_tools) PS C:\Users\thoma> ollama list

例如,要运行一个模型(在与之交互之前需要这样做),请使用运行命令

(ollama_tools) PS C:\Users\thoma> ollam run llama3.1:latest --keepalive 120m

进入 >>> 提示符后,可以直接退出,模型将继续在后台运行 120 分钟,然后自动卸载。

二、为什么需要使用工具

我们要求使用工具的原因是,LLMs的知识一般都有一个截止日期。这意味着他们不了解时事、形势等……除非他们能直接访问互联网,而大多数LLMs都不能。

因此,如果你问LLMs北京目前的气温是多少它是无法告诉你的。举例来说,某只股票的当前价格也是如此。要回答我们的问题,首先需要一个函数来返回股票的当前价格。查找股票当前价格的代码示例如下:

>>> what is the current price of MSFT (Microsoft)

As I'm a large language model, I don't have direct access to real-time market data. However, I can suggest some
ways for you to find out the current stock price of Microsoft (MSFT):

1. **Financial websites**: Visit reputable financial websites like:
        * Yahoo Finance (finance.yahoo.com)
        * Google Finance (finance.google.com)
        * Bloomberg (bloomberg.com)
        * CNBC (cnbc.com)
2. **Stock market apps**: Use a mobile app like:
        * Robinhood
        * Fidelity Investments
        * eTrade
        * TradingView
3. **Direct from the source**: Visit Microsoft's investor relations page (ir.microsoft.com) for real-time stock
data.

As of my knowledge cutoff, the current price of MSFT was around $245-$250 per share. However, please note that
this information may be outdated, and I recommend checking a reliable financial website or app for the most recent
and accurate price.

If you want to get an estimate, here are some historical price ranges:

* 52-week high: around $280
* 52-week low: around $210

Keep in mind that stock prices can fluctuate rapidly due to various market factors. Always consult multiple
sources or a financial advisor for more precise and up-to-date information.

首先需要一个函数来返回股票的当前价格。我们可以使用雅虎财经的API,如下:

import yfinance as yf

def get_current_stock_price(ticker_symbol):

  # Get the stock data
  stock = yf.Ticker(ticker_symbol)

  # Get the current price
  current_price = stock.history(period='1d')['Close'].iloc[0]

  return current_price

现在,向 Ollama 指定工具(功能)。

import ollama

# Want the current price of Microsoft - ticker symbol MSFT

response = ollama.chat(
    model='llama3.1',
    messages=[{'role': 'user','content': 
        'What is the current price of MSFT'}],

  # provide a tool to get the current price of a stock
    tools=[{
      'type': 'function',
      'function': {
        'name': 'get_current_stock_price',
        'description': 'Get the current price for a stock',
        'parameters': {
          'type': 'object',
          'properties': {
            'ticker_symbol': {
              'type': 'string',
              'description': 'The ticker symbol of the stock',
            },
          },
          'required': ['ticker_symbol'],
        },
      },
    },
  ],
)

print(response['message']['tool_calls'])

动态调用工具(Call the tool dynamically)

# Create a dictionary mapping function names to functions
function_map = {
    'get_current_stock_price': get_current_stock_price,
    # Add more functions here as needed
}

def call_function_safely(response, function_map):
    # Extract the function name and arguments from the response
    tool_call = response['message']['tool_calls'][0]
    function_name = tool_call['function']['name']
    arguments = tool_call['function']['arguments']

    # Look up the function in the function map
    function_to_call = function_map.get(function_name)

    if function_to_call:
        try:
            # Call the function with the arguments
            result = function_to_call(**arguments)
            print(f"The current price of {arguments['ticker_symbol']} is : {result}")
        except TypeError as e:
            print(f"Argument error: {e}")
    else:
        print(f"{function_name} is not a recognized function")

call_function_safely(response, function_map)

输出结果如下:

The current price of MSFT is : 427.4599914550781

到这里已经完成了整个在Ollama 中使用 Python 调用雅虎财经的 API 服务,希望这篇文章对您有用。


本文内容仅仅是技术探讨和学习,并不构成任何投资建议。
转发请注明原作者

Published inAI&Invest专栏

Be First to Comment

    发表回复