ollama客户端已经支持函数调用
pip install ollama
import json import ollama import asyncio # Simulates an API call to get flight times # In a real application, this would fetch data from a live database or API def get_flight_times(departure: str, arrival: str) -> str: flights = { 'NYC-LAX': {'departure': '08:00 AM', 'arrival': '11:30 AM', 'duration': '5h 30m'}, 'LAX-NYC': {'departure': '02:00 PM', 'arrival': '10:30 PM', 'duration': '5h 30m'}, 'LHR-JFK': {'departure': '10:00 AM', 'arrival': '01:00 PM', 'duration': '8h 00m'}, 'JFK-LHR': {'departure': '09:00 PM', 'arrival': '09:00 AM', 'duration': '7h 00m'}, 'CDG-DXB': {'departure': '11:00 AM', 'arrival': '08:00 PM', 'duration': '6h 00m'}, 'DXB-CDG': {'departure': '03:00 AM', 'arrival': '07:30 AM', 'duration': '7h 30m'}, } key = f'{departure}-{arrival}'.upper() return json.dumps(flights.get(key, {'error': 'Flight not found'})) async def run(model: str): client = ollama.AsyncClient() # Initialize conversation with a user query messages = [{'role': 'user', 'content': 'What is the flight time from New York (NYC) to Los Angeles (LAX)?'}] # First API call: Send the query and function description to the model response = await client.chat( model=model, messages=messages, tools=[ { 'type': 'function', 'function': { 'name': 'get_flight_times', 'description': 'Get the flight times between two cities', 'parameters': { 'type': 'object', 'properties': { 'departure': { 'type': 'string', 'description': 'The departure city (airport code)', }, 'arrival': { 'type': 'string', 'description': 'The arrival city (airport code)', }, }, 'required': ['departure', 'arrival'], }, }, }, ], ) # Add the model's response to the conversation history messages.append(response['message']) # Check if the model decided to use the provided function if not response['message'].get('tool_calls'): print("The model didn't use the function. Its response was:") print(response['message']['content']) return # Process function calls made by the model if response['message'].get('tool_calls'): available_functions = { 'get_flight_times': get_flight_times, } for tool in response['message']['tool_calls']: function_to_call = available_functions[tool['function']['name']] function_response = function_to_call(tool['function']['arguments']['departure'], tool['function']['arguments']['arrival']) # Add function response to the conversation messages.append( { 'role': 'tool', 'content': function_response, } ) # Second API call: Get final response from the model final_response = await client.chat(model=model, messages=messages) print(final_response['message']['content']) # Run the async function asyncio.run(run('llama3.1'))
网友回复
DLNA与UPnP的区别和不同?
苏超自建抢票app,通过先预约再抽签化解高并发抢票?
python如何让给电脑在局域网中伪装成电视接收手机的投屏图片视频播放?
如何结合python+js如何自己的视频编码与加密播放直播?
python如何在电脑上通过局域网将本地视频或m3u8视频投屏电视播放?
腾讯视频爱奇艺优酷vip电影电视剧视频如何通过python绕过vip收费直接观看?
有没有可免费观看全球电视台直播m3u8地址url的合集?
有没有实现观影自由的免vip影视苹果 CMS V10 API的可用url?
python如何实时检测电脑usb插入检测报警?
如何判断真人操作的鼠标移动直线轨迹与机器操作的轨迹?