$ ollama run llama3.2:latest
>>> Explain what Python is in one sentence.
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility, often used for web development, data analysis, machine learning, automation, and more.
>>> from ollama import chat
>>> messages = [
... {
... "role": "user",
... "content": "Explain what Python is in one sentence.",
... },
... ]
>>> response = chat(model="llama3.2:latest", messages=messages)
>>> print(response.message.content)
Python is a high-level, interpreted programming language that is widely used for its simplicity, readability, and versatility, making it an ideal choice for web development, data analysis, machine learning, automation, and more.
>>> messages = [
... {"role": "system", "content": "You are an expert Python tutor."},
... {
... "role": "user",
... "content": "Define list comprehensions in a sentence."... },
... ]
>>> response = chat(model="llama3.2:latest", messages=messages)
>>> print(response.message.content)
List comprehensions are a concise and expressive way to create new lists by performing operations on existing lists or iterables, using a compact syntax that combines conditional statements and iteration.
>>> messages.append(response.message) # Keep context>>> messages.append(
... {
... "role": "user",
... "content": "Provide a short, practical example."... }
... )
>>> response = chat(model="llama3.2:latest", messages=messages)
>>> print(response.message.content)
Here's an example of a list comprehension:
```python
numbers = [1, 2, 3, 4, 5]
double_numbers = [num * 2 for num in numbers if num % 2 == 0]
print(double_numbers) # Output: [2, 4, 6]
在这个例子中,你要将`numbers`列表中的每个数字乘以 2,然后只保留原数字为偶数的结果。
在这里,你发起了一场关于 Python 列表推导式的对话。模型回复后,你将答案添加到消息列表中,以便模型将其用作上下文。接下来,你运行另一次聊天交互,并获取基于提供的上下文的响应。
如果您正在构建命令行界面 (CLI)和聊天应用程序,那么 chat streaming(聊天流)功能可以让模型响应更具交互性和流畅性。请参考以下脚本:
```python
# streams.py
from ollama import chat
stream = chat(
model="llama3.2:latest",
messages=[
{
"role": "user",
"content": "Explain Python dataclasses with a quick example."
}
],
stream=True,
)
for chunk in stream:
print(chunk.message.content, flush=True)
>>> from ollama import generate
>>> response = generate(
... model="llama3.2:latest",
... prompt="Explain what Python is in one sentence."... )
>>> print(response.response)
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. It is widely used in various fields such as web development, data analysis, artificial intelligence, and more.
>>> from ollama import generate
>>> prompt = '''Write a Python function fizzbuzz(n: int) -> List[str] that:
... - Returns a list of strings for the numbers 1..n
... - Uses "Fizz" for multiples of 3
... - Uses "Buzz" for multiples of 5
... - Uses "FizzBuzz" for multiples of both 3 and 5
... - Uses the number itself (as a string) otherwise
... - Raises ValueError if n < 1
... Include type hints compatible with Python 3.8.'''>>> response = generate(model="codellama:latest", prompt=prompt)
>>> print(response.response)
```python
from typing importListdeffizzbuzz(n: int) -> List[str]:
if n < 1:
raise ValueError("n must be greater than or equal to 1")
result = []
for i inrange(1, n+1):
if i % 3 == 0and i % 5 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
在这个例子中,你使用了`codellama:latest`模型,该模型旨在根据自然语言提示词生成代码。
模型生成代码后,请检查代码并进行快速测试。将生成的代码复制到 REPL 会话中,并以整数作为参数调用它:
```python
>>>from typing importList>>>deffizzbuzz(n: int) -> List[str]:...if n < 1:...raise ValueError("n must be greater than or equal to 1")... result = []...for i inrange(1, n+1):...if i % 3 == 0and i % 5 == 0:... result.append("FizzBuzz")...elif i % 3 == 0:... result.append("Fizz")...elif i % 5 == 0:... result.append("Buzz")...else:... result.append(str(i))...return result...>>> fizzbuzz(16)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', ..., 'FizzBuzz', '16']
# tool_calling.pyimport math
from ollama import chat
# Define a tool as a Python functiondefsquare_root(number: float) -> float:
"""Calculate the square root of a number.
Args:
number: The number to calculate the square root for.
Returns:
The square root of the number.
"""return math.sqrt(number)
messages = [
{
"role": "user",
"content": "What is the square root of 36?",
}
]
response = chat(
model="llama3.2:latest",
messages=messages,
tools=[square_root] # Pass the tools along with the prompt
)
# Append the response for context
messages.append(response.message)
if response.message.tool_calls:
tool = response.message.tool_calls[0]
# Call the tool
result = square_root(float(tool.function.arguments["number"]))
# Append the tool result
messages.append(
{
"role": "tool",
"tool_name": tool.function.name,
"content": str(result),
}
)
# Obtain the final answer
final_response = chat(model="llama3.2:latest", messages=messages)
print(final_response.message.content)