शुरू करेंमुफ़्त में शुरू करें

MCP से Resource और Prompt फ़ेच करें

आपका currency सर्वर एक resource (file://currencies.txt) और एक prompt (convert_currency_prompt) एक्सपोज़ करता है, जो यूज़र की रिक्वेस्ट को task-विशेष संदर्भ और नियमों के साथ जोड़ते हैं. किसी LLM को फ़ीड करने के लिए, क्लाइंट को दोनों चीज़ें एक साथ फ़ेच करनी होंगी. get_context_from_mcp() नाम का एक helper फंक्शन इम्प्लीमेंट कीजिए जो resource टेक्स्ट और prompt टेक्स्ट (जिसमें यूज़र की क्वेरी पहले से भरी हो) रिटर्न करे, ताकि कॉलर उससे संदेश बना सके.

currency_server.py फ़ाइल में एक tool, resource, और prompt उपलब्ध है. उसी session का उपयोग करते हुए resource पढ़िए और यूज़र के इनपुट के साथ prompt लीजिए.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Model Context Protocol (MCP) परिचय

पाठ्यक्रम देखें

अभ्यास निर्देश

  • सेशन के अंदर, "file://currencies.txt" पर मौजूद resource को पढ़ने वाली मेथड कॉल करें.
  • यूज़र के इनपुट के साथ नाम से prompt लेने वाली मेथड कॉल करें: prompt का नाम "convert_currency_prompt" रखें और arguments डिक्शनरी में key "currency_request" और value user_query का उपयोग करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
    """Fetch resource content and prompt text from the MCP server."""
    params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

            # Read the resource (supported currencies)
            resource_result = await session.____("file://currencies.txt")
            resource_text = resource_result.contents[0].text

            # Get the prompt with the user's query
            prompt_result = await session.____("convert_currency_prompt",
                arguments={"currency_request": user_query})
            prompt_text = prompt_result.messages[0].content.text

            return resource_text, prompt_text

print(asyncio.run(get_context_from_mcp("How much is 50 GBP in euros?")))
कोड संपादित करें और चलाएँ