> ## Documentation Index
> Fetch the complete documentation index at: https://ikun.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent 上下文

## 代码

```python cookbook/agent_concepts/context/02-agent_context.py theme={null}
import json
from textwrap import dedent

import httpx
from agno.agent import Agent
from agno.models.openai import OpenAIChat


def get_top_hackernews_stories(num_stories: int = 5) -> str:
    """获取并返回 HackerNews 的热门故事。

    参数：
        num_stories：要检索的热门故事的数量（默认为 5）
    返回：
        包含故事详情（标题、URL、得分等）的 JSON 字符串
    """
    # 获取热门故事
    stories = [
        {
            k: v
            for k, v in httpx.get(
                f"https://hacker-news.firebaseio.com/v0/item/{id}.json"
            )
            .json()
            .items()
            if k != "kids"  # 排除讨论串
        }
        for id in httpx.get(
            "https://hacker-news.firebaseio.com/v0/topstories.json"
        ).json()[:num_stories]
    ]
    return json.dumps(stories, indent=4)


# 创建一个可以访问实时 HackerNews 数据的上下文感知 Agent
agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    # 上下文中的每个函数都将在运行时进行评估
    context={"top_hackernews_stories": get_top_hackernews_stories},
    # 或者，你也可以手动将上下文添加到指令中
    instructions=dedent("""\
        你是一位富有洞察力的科技趋势观察者！📰

        以下是 HackerNews 的热门故事：
        {top_hackernews_stories}\
    """),
    # add_state_in_messages 将使 `top_hackernews_stories` 变量
    # 在指令中可用
    add_state_in_messages=True,
    markdown=True,
)

# 示例用法
agent.print_response(
    "总结 HackerNews 的热门故事，并识别任何有趣的趋势。",
    stream=True,
)
```

## 用法

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="安装库">
    ```bash theme={null}
    pip install -U agno httpx
    ```
  </Step>

  <Step title="运行示例">
    <CodeGroup>
      ```bash Mac theme={null}
      python cookbook/agent_concepts/context/02-agent_context.py
      ```

      ```bash Windows theme={null}
      python cookbook/agent_concepts/context/02-agent_context.py
      ```
    </CodeGroup>
  </Step>
</Steps>
