|
2 | 2 |
|
3 | 3 | A model controlled by a local function.
|
4 | 4 |
|
5 |
| -[`FunctionModel`][pydantic_ai.models.function.FunctionModel] is similar to [`TestModel`][pydantic_ai.models.test.TestModel], |
| 5 | +[`FunctionModel`][pydantic_ai.models.function.FunctionModel] is similar to [`TestModel`](test.md), |
6 | 6 | but allows greater control over the model's behavior.
|
7 | 7 |
|
8 | 8 | Its primary use case is for more advanced unit testing than is possible with `TestModel`.
|
9 | 9 |
|
| 10 | +Here's a minimal example: |
| 11 | + |
| 12 | +```py {title="function_model_usage.py" call_name="test_my_agent" lint="not-imports"} |
| 13 | +from pydantic_ai import Agent |
| 14 | +from pydantic_ai.messages import Message, ModelResponse |
| 15 | +from pydantic_ai.models.function import FunctionModel, AgentInfo |
| 16 | + |
| 17 | +my_agent = Agent('openai:gpt-4o') |
| 18 | + |
| 19 | + |
| 20 | +async def model_function(messages: list[Message], info: AgentInfo) -> ModelResponse: |
| 21 | + print(messages) |
| 22 | + """ |
| 23 | + [ |
| 24 | + UserPrompt( |
| 25 | + content='Testing my agent...', |
| 26 | + timestamp=datetime.datetime(...), |
| 27 | + role='user', |
| 28 | + message_kind='user-prompt', |
| 29 | + ) |
| 30 | + ] |
| 31 | + """ |
| 32 | + print(info) |
| 33 | + """ |
| 34 | + AgentInfo( |
| 35 | + function_tools=[], allow_text_result=True, result_tools=[], model_settings=None |
| 36 | + ) |
| 37 | + """ |
| 38 | + return ModelResponse.from_text('hello world') |
| 39 | + |
| 40 | + |
| 41 | +async def test_my_agent(): |
| 42 | + """Unit test for my_agent, to be run by pytest.""" |
| 43 | + with my_agent.override(model=FunctionModel(model_function)): |
| 44 | + result = await my_agent.run('Testing my agent...') |
| 45 | + assert result.data == 'hello world' |
| 46 | +``` |
| 47 | + |
| 48 | +See [Unit testing with `FunctionModel`](../../testing-evals.md#unit-testing-with-functionmodel) for detailed documentation. |
| 49 | + |
10 | 50 | ::: pydantic_ai.models.function
|
0 commit comments